A helper for creating AI-powered functions using OpenAI's API
Project description
AI Function Helper
Streamline your AI-powered Python functions with ease!
🌟 Key Features
- Seamless OpenAI Integration: Easy setup with various AI models (GPT-3.5, GPT-4, Mistral, etc.)
- Flexible Function Decorators: Customize AI-powered tasks with ease
- Synchronous and Asynchronous Support: Use AI functions in both sync and async contexts
- Batch Processing: Efficiently handle multiple inputs in a single API call
- Robust Error Handling: Automatic retries and comprehensive error management
- Type Safety: Pydantic models for JSON parsing and validation
- Debugging Capabilities: Detailed logging of API interactions
- Function Calling: Support for OpenAI's function calling feature
- Multiple Return Formats: Flexible output handling (JSON, string, raw response)
- Image Input Support: Process and analyze images within your AI functions
- JSON Mode: Automatic JSON response formatting for compatible models
- Customizable System Prompts: Fine-tune AI behavior with detailed instructions
- Error Prevention: Block hijacking attempts and ensure adherence to function parameters
- Conversation History: Maintain context across multiple interactions using HistoryInput
- Timeout Management: Set custom timeouts for API calls
- Custom Base URL: Support for custom OpenAI-compatible endpoints
📚 Table of Contents
- AI Function Helper
🚀 Installation
Install AI Function Helper using pip:
pip install ai-function-helper
🏁 Quick Start
Get up and running with AI Function Helper in just a few lines of code:
from ai_function_helper import AIFunctionHelper
# Initialize AI Function Helper
ai_helper = AIFunctionHelper("your-api-key")
# Create an AI-powered function
@ai_helper.ai_function(model="gpt-3.5-turbo", max_tokens=200)
def generate_short_story(theme: str) -> str:
"""
Generate a short story based on a given theme.
"""
# Use the function
story = generate_short_story(theme="A day in the life of a time traveler")
print(story)
🧠 Core Concepts
AI Function Helper is built around several key concepts:
- AIFunctionHelper Class: The main entry point for creating AI-powered functions.
- AI Function Decorator: Transforms regular Python functions into AI-powered ones, supporting both sync and async usage.
- Pydantic Models: Ensures type safety and easy validation of AI-generated responses.
- Error Handling: Built-in mechanisms for handling API errors and retrying failed calls.
- Debugging: Comprehensive logging options for troubleshooting and optimization.
- JSON Mode: Automatic JSON response formatting for compatible models.
- System Prompts: Customizable instructions to guide AI behavior.
- HistoryInput: Allows for maintaining conversation context across multiple interactions.
- ImageInput: Supports processing and analysis of images within AI functions.
- Tools: Enables the use of custom functions within the AI's reasoning process.
🔧 Advanced Usage
Customizing AI Function Behavior
Fine-tune your AI functions with various parameters:
@ai_helper.ai_function(
model="gpt-4o",
max_tokens=500,
temperature=0.7,
top_p=0.9,
frequency_penalty=0.1,
presence_penalty=0.1,
timeout=60,
show_debug=True,
debug_level=2,
force_json_mode=True,
block_hijack=True,
block_hijack_throw_error=False,
language="French",
disable_prefill=False
)
def advanced_function(input_data: str) -> ComplexResponseModel:
"""
An advanced AI-powered function with custom settings.
"""
Using HistoryInput for Conversation Context
The HistoryInput class allows you to maintain conversation history across multiple interactions:
from ai_function_helper import AIFunctionHelper, HistoryInput
@ai_helper.ai_function(model="gpt-3.5-turbo", max_tokens=4000)
async def chat_response(history: HistoryInput, user_input: str) -> str:
"""
Generate a chat response based on the conversation history and user input.
"""
# Usage
chat_history = HistoryInput([
{"role": "user", "content": "Hello, how are you?"},
{"role": "assistant", "content": "I'm doing well, thank you! How can I assist you today?"}
])
response = await chat_response(history=chat_history, user_input="Tell me a joke")
Image Input Support
Process and analyze images within your AI functions:
from ai_function_helper import AIFunctionHelper, ImageInput
from pathlib import Path
@ai_helper.ai_function(model="gpt-4-vision-preview", max_tokens=300)
def analyze_image(image: ImageInput) -> str:
"""
Analyze the contents of the image and provide a description.
"""
# Using a URL
result = analyze_image(image=ImageInput(url="https://example.com/image.jpg"))
# Using a local file
result = analyze_image(image=ImageInput(url=Path("local_image.jpg")))
JSON Mode Support
AI Function Helper supports automatic JSON mode for compatible models. The following models are currently supported:
- gpt-4o, gpt-4-turbo, gpt-4-turbo-2024-04-09, gpt-3.5-turbo
- gpt-4-1106-preview, gpt-3.5-turbo-1106, gpt-4-0125-preview
- gpt-3.5-turbo-0125, gpt-4-turbo-preview
- mistral-small-2402, mistral-small-latest, mistral-large-2402, mistral-large-latest
You can add support for additional models using the add_json_mode_models method:
AIFunctionHelper.add_json_mode_models(["new-model-1", "new-model-2"])
Asynchronous Usage
AI Function Helper supports both synchronous and asynchronous functions:
@ai_helper.ai_function(model="gpt-3.5-turbo")
async def async_function(input_data: str) -> str:
"""
An asynchronous AI-powered function.
"""
# Usage
import asyncio
async def main():
result = await async_function("Hello, AI!")
print(result)
asyncio.run(main())
Error Handling and Debugging
Enable detailed logging and set retry attempts:
AIFunctionHelper.set_max_retries(3) # Set max retries globally
@ai_helper.ai_function(show_debug=True, debug_level=2)
def debug_example(input_data: str) -> str:
"""
This function will display detailed debug information.
"""
Timeout Management
Set custom timeouts for API calls:
@ai_helper.ai_function(timeout=30)
def time_sensitive_function(input_data: str) -> str:
"""
This function will timeout after 30 seconds if no response is received.
"""
Custom Base URL
Support for custom OpenAI-compatible endpoints:
ai_helper = AIFunctionHelper("your-api-key", base_url="https://your-custom-endpoint.com/v1")
System Message Customization
Customize the system message to guide the AI's behavior:
@ai_helper.ai_function(
model="gpt-4o",
language="Spanish",
block_hijack=True
)
def spanish_assistant(query: str) -> str:
"""
A Spanish-speaking assistant that resists hijacking attempts.
"""
🛠️ Using Tools (Function Calling)
AI Function Helper supports OpenAI's function calling feature, allowing you to define custom functions that the AI can use during its reasoning process:
def get_weather(city: str) -> dict:
"""Get the current weather for a city."""
# Implementation here
@ai_helper.ai_function(
model="gpt-4o",
tools=[get_weather]
)
def plan_trip(destination: str) -> str:
"""
Plan a trip to the specified destination, considering the weather.
"""
result = plan_trip("Paris")
📘 Examples
Simple Text Generation
@ai_helper.ai_function(model="gpt-3.5-turbo", max_tokens=100)
def generate_haiku(theme: str) -> str:
"""
Generate a haiku based on the given theme.
The haiku should follow the 5-7-5 syllable structure and capture the essence of the theme.
"""
haiku = generate_haiku(theme="autumn leaves")
print(haiku)
Interactive Quiz Bot
from pydantic import BaseModel
from typing import List
class QuizQuestion(BaseModel):
question: str
correct_answer: str
@ai_helper.ai_function(model="gpt-3.5-turbo", max_tokens=1500)
async def generate_quiz(topic: str, num_questions: int) -> List[QuizQuestion]:
"""
Generate a quiz on the given topic with the specified number of questions.
Each question should be challenging but appropriate for a general audience.
Provide a clear and concise correct answer for each question.
"""
# Usage
questions = await generate_quiz("Python programming", 3)
for q in questions:
print(f"Q: {q.question}")
print(f"A: {q.correct_answer}\n")
Data Analysis Assistant
from pydantic import BaseModel
from typing import List, Dict
class DataPoint(BaseModel):
timestamp: str
value: float
category: str
class AnalysisResult(BaseModel):
summary: str
trend: str
anomalies: List[Dict[str, any]]
@ai_helper.ai_function(model="gpt-4o", max_tokens=1000)
async def analyze_data(data: List[DataPoint]) -> AnalysisResult:
"""
Analyze the given series of data points and provide insights.
Your analysis should include:
1. A brief summary of the overall data trends.
2. Identification of the primary trend (increasing, decreasing, or stable).
3. Detection of any anomalies or outliers in the data.
Use statistical reasoning to support your analysis.
"""
# Usage
data = [
DataPoint(timestamp="2023-01-01", value=100, category="A"),
DataPoint(timestamp="2023-01-02", value=110, category="B"),
DataPoint(timestamp="2023-01-03", value=105, category="A"),
DataPoint(timestamp="2023-01-04", value=200, category="B"),
DataPoint(timestamp="2023-01-05", value=115, category="A"),
]
result = await analyze_data(data)
print(f"Summary: {result.summary}")
print(f"Trend: {result.trend}")
print("Anomalies:", result.anomalies)
Complex Travel Planner
from pydantic import BaseModel, Field
from typing import List
class Destination(BaseModel):
city: str
country: str
days: int
class Activity(BaseModel):
name: str
description: str
duration: float
class TravelPlan(BaseModel):
destinations: List[Destination]
activities: List[Activity]
budget_estimate: float
def get_weather(city: str, date: str) -> dict:
"""Mock function to get weather forecast"""
return {"temperature": "25°C", "condition": "Sunny"}
def find_hotels(city: str, check_in: str, guests: int) -> List[dict]:
"""Mock function to find hotels"""
return [{"name": "Grand Hotel", "price": 150}, {"name": "Cozy Inn", "price": 100}]
@ai_helper.ai_function(
model="gpt-4o",
max_tokens=2000,
tools=[get_weather, find_hotels]
)
async def plan_trip(destinations: List[str], duration: int, interests: List[str]) -> TravelPlan:
"""
Create a comprehensive travel plan based on the given destinations, duration, and interests.
Use the provided tools to get weather information and find hotels.
"""
# Usage
plan = await plan_trip(
destinations=["Paris", "Rome"],
duration=7,
interests=["history", "food", "art"]
)
print(plan)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ai_function_helper-0.3.3.tar.gz.
File metadata
- Download URL: ai_function_helper-0.3.3.tar.gz
- Upload date:
- Size: 17.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fd858f3623c43a02186ba8341dde19330c8cc4fbddab697fec5a46decc4878be
|
|
| MD5 |
49eed17caaed7847ca97abf14aba31d5
|
|
| BLAKE2b-256 |
f92515323d0551b342092dfd91c4abc469c1fee21d3517cb0303ee69e69c93db
|
File details
Details for the file ai_function_helper-0.3.3-py3-none-any.whl.
File metadata
- Download URL: ai_function_helper-0.3.3-py3-none-any.whl
- Upload date:
- Size: 13.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f0962bd7d220c6f07b8a45d733a5641953a42da4d9db0bd0a05309db8f616b99
|
|
| MD5 |
1d62755c15f699b9880f6a143a995304
|
|
| BLAKE2b-256 |
84d97a9dc508b54bd1a39b57f8c75abcf943e4c7f1b24b05248486788b0e2a3a
|