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.2.tar.gz (13.2 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.2-py3-none-any.whl (12.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: openaiwrapperfunction-0.1.2.tar.gz
  • Upload date:
  • Size: 13.2 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.2.tar.gz
Algorithm Hash digest
SHA256 d72c5b081b299624dfbf2e503f640ea2d89b4252642bcc7baae6a1cc3bd19fe5
MD5 71c06f0eb421ab49e12e11e8c26c50f9
BLAKE2b-256 cddab561d7a057089fc78e98f404dd9b5f592726afead8c81561328f9f75eb48

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for openaiwrapperfunction-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 f6cb036e938efdca35ec7e2a36faf7a87fa2246ff880797e63494aa36bbae80f
MD5 f36e91a5fb8a99367654dbb476ea0af4
BLAKE2b-256 d59487ccb1eaee1b6f47844c046525599855865a1fb4904f91d512ca7f9c9134

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