Skip to main content

Decorator for creating OpenAI function tools

Project description

OpenAI & Gemini Function Decorator

This package provides a decorator @openai_function that automatically creates function tools from Python functions and executes them using either:

  • Gemini API (default)
  • OpenAI API
  • Any OpenAI-compatible API

Key Features

  • 🚀 Uses Gemini 2.5 Flash by default (powerful, fast, efficient)
  • 🤖 Supports both Gemini and OpenAI through same interface
  • 🔄 Automatic tool schema generation from function docstrings
  • 🧠 AI-powered parameter generation when called without arguments
  • ⚙️ Full configuration of API keys, models, and endpoints
  • 📄 Supports complex types and default values

Installation

pip install openaiWrapper

Quick Start

1. Get Gemini API Key

Create an API key from Google AI Studio

2. Import and Configure

from openAiWrapper import openai_function, OpenAIWrapper

# Set your Gemini API key
OpenAIWrapper.set_api_key("your-gemini-api-key")

# Optional: Explicitly set Gemini endpoint
OpenAIWrapper.set_base_url("https://generativelanguage.googleapis.com/v1beta/openai/")

3. Define Your Function

@openai_function(temperature=0.7)
def calculate_sum(a: int, b: int) -> int:
    """Sum two integers and return the result"""
    return a + b

4. Use Your Function

# Direct call (bypasses Gemini)
print(calculate_sum(5, 3))  # Output: 8

# Gemini-powered call (parameters generated by AI)
print(calculate_sum())  # Uses AI to determine parameters

# Custom prompt query
print(calculate_sum.query("What is 17 plus 24?"))  # Output: 41

Advanced Usage

Different Models

# Use gemini-1.5-flash-latest
@openai_function(model="gemini-1.5-flash-latest")
def analyze_text(text: str) -> dict:
    """Analyze text and return sentiment and key entities"""
    # Implementation would call external NLP service...
    return {"sentiment": 0.8, "entities": ["Google", "AI"]}

# Use OpenAI models (if configured)
@openai_function(
    model="gpt-4o", 
    base_url="https://api.openai.com/v1/",
    api_key="your-openai-key"
)
def openai_function(text: str) -> str:
    """Process text using OpenAI"""
    return text.upper()

Complex Parameters and Defaults

@openai_function(max_tokens=300)
def generate_email(recipient: str, subject: str, 
                  tone: str = "formal", urgency: int = 3) -> str:
    """
    Generate an email with given parameters
    
    Parameters:
    recipient: Email recipient name
    subject: Email subject
    tone: Writing tone (friendly, formal, urgent) - default: formal
    urgency: Importance level (1-5) - default: 3
    """
    # Implementation would generate email content...
    return f"Dear {recipient},\n\nAbout: {subject}\n\n[Email content]"

Summarization Example

@openai_function()
def summarize_document(text: str, length: str = "medium") -> str:
    """
    Summarize text to specified length
    
    Parameters:
    text: Text to summarize
    length: Summary length ('short', 'medium', 'long' - default: medium)
    """
    if length == "short":
        return text[:100] + "..."  # Simplified example
    elif length == "medium":
        return text[:250] + "..."
    else:
        return text[:500] + "..."
    
# Usage
sample_text = ("Google's Gemini is a powerful AI model " * 20)
print(summarize_document.query(f"Summarize this: {sample_text}"))

Error Handling

Clear error messages for:

  • Missing API keys
  • Gemini/API errors
  • Parameter validation issues
  • Unexpected responses

Switching Providers

To Use OpenAI Instead:

# Configure OpenAI
OpenAIWrapper.set_api_key("your-openai-key")
OpenAIWrapper.set_base_url("https://api.openai.com/v1/")

@openai_function(model="gpt-4o")
def openai_function(text: str) -> str:
    """Process text using OpenAI"""
    return f"Processed: {text}"

To Use Local Endpoints:

# Local AI service (e.g., LocalAI, ollama)
OpenAIWrapper.set_base_url("http://localhost:8080/v1")

@openai_function(model="llama3")
def local_ai_function(query: str) -> str:
    """Answer questions using local AI"""
    return "Response from local AI"

Development

Install Locally

git clone https://github.com/pilot4u/openaiWrapper.git
cd openaiWrapper
pip install -e .

Run Tests

python test/test.py

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

openaiwrapperfunction-0.1.0.tar.gz (11.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

openaiwrapperfunction-0.1.0-py3-none-any.whl (10.9 kB view details)

Uploaded Python 3

File details

Details for the file openaiwrapperfunction-0.1.0.tar.gz.

File metadata

  • Download URL: openaiwrapperfunction-0.1.0.tar.gz
  • Upload date:
  • Size: 11.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.12

File hashes

Hashes for openaiwrapperfunction-0.1.0.tar.gz
Algorithm Hash digest
SHA256 dabd9927d3652ccd380fec2dbc9c3684e38efe833de021a078fb631d9aa5fe14
MD5 c69a315f6bb956c2dc101073eaf48861
BLAKE2b-256 148eaf19a2c20784b2fe13bd754b764dab3edd461ddcc20d841d4bbfdbbe5458

See more details on using hashes here.

File details

Details for the file openaiwrapperfunction-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for openaiwrapperfunction-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6494f960fbb32bcf5ad3bf6b43f38303a421f322fe273cac06e9061a5ff3863f
MD5 f8202b02136b2f1cc6e26668244dac8a
BLAKE2b-256 03bdd5555283aa71c5644b3c8317361704b3d7ef3f5d9e9062698c9c836a865b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page