openaiWrapperFunction 0.1.2
Decorator for creating OpenAI function tools
Requires Python: >=3.8

# 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

```bash
pip install openaiWrapper
```

## Quick Start

### 1. Get Gemini API Key
Create an API key from [Google AI Studio](https://aistudio.google.com/)

### 2. Import and Configure
```python
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
```python
@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
```python
# 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
```python
# 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
```python
@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
```python
@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:
```python
# 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:
```python
# 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
```bash
git clone https://github.com/pilot4u/openaiWrapper.git
cd openaiWrapper
pip install -e .
```

### Run Tests
```bash
python test/test.py
```

## License
[MIT License](https://commonsclause.com/)