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.1.tar.gz (11.1 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.1-py3-none-any.whl (11.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: openaiwrapperfunction-0.1.1.tar.gz
  • Upload date:
  • Size: 11.1 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.1.tar.gz
Algorithm Hash digest
SHA256 214f4b96c5479c6a0c2562bc623abe624dfe841ccbb9c016232ceef58c816fe5
MD5 66142114a49fd544fa248b21feddfafd
BLAKE2b-256 a7b171eb77f0023f4307e41eba816932342a6299905bc25ec1ddcd60d93f7c15

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for openaiwrapperfunction-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d2621802d3ddb16f74cffe527a693356149496dacde308beeb03989ed45f0279
MD5 41d7d1f2edd5805c4324dcba1fd1ec9e
BLAKE2b-256 75f4df148314e1b611754ef73aa65ebc58d6ad50f8f76444f437ed26982a3cdb

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