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 • Installation • Quick Start • Documentation • Contributing
📚 Table of Contents
- Key Features
- Installation
- Quick Start
- Core Concepts
- Advanced Usage
- Error Handling and Debugging
- Examples
- Contributing
- License
🌟 Key Features
- Seamless OpenAI Integration: Easy setup with various AI models (GPT-3.5, GPT-4, etc.)
- Flexible Function Decorators: Customize AI-powered tasks with ease
- Synchronous and Asynchronous Support: Use AI functions in both sync and async contexts
- 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)
🚀 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 (synchronous version)
@ai_helper.ai_function(model="gpt-3.5-turbo", max_tokens=200)
def generate_short_story(theme: 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)
# Asynchronous version
@ai_helper.ai_function(model="gpt-3.5-turbo", max_tokens=200)
async def generate_short_story_async(theme: str):
"""
Generate a short story based on a given theme (async version).
"""
# Use the async function
import asyncio
async def main():
story = await generate_short_story_async(theme="A day in the life of a time traveler")
print(story)
asyncio.run(main())
🧠 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.
🔧 Advanced Usage
Customizing AI Function Behavior
Fine-tune your AI functions with various parameters:
@ai_helper.ai_function(
model="gpt-4",
max_tokens=500,
temperature=0.7,
top_p=0.9,
frequency_penalty=0.1,
presence_penalty=0.1,
timeout=60,
max_retries=3,
show_debug=True,
debug_level=2
)
def advanced_function(input_data: str) -> ComplexResponseModel:
"""
An advanced AI-powered function with custom settings.
"""
Function Formats
AI Function Helper supports multiple function formats to suit various use cases:
-
Using
ai_resultParameter:def func(ai_result: ResponseModel, input: str) -> ResponseModel:
-
Direct Pydantic Model Return:
def func(input: str) -> ResponseModel:
-
String Output:
def func(input: str) -> str:
-
Unspecified Return Type:
def func(input: str):
Synchronous vs Asynchronous Usage
AI Function Helper now supports both synchronous and asynchronous usage:
-
Synchronous Usage:
@ai_helper.ai_function(model="gpt-3.5-turbo") def sync_function(input: str) -> str: """ A synchronous AI-powered function. """ result = sync_function("Hello, AI!") print(result)
-
Asynchronous Usage:
@ai_helper.ai_function(model="gpt-3.5-turbo") async def async_function(input: str) -> str: """ An asynchronous AI-powered function. """ async def main(): result = await async_function("Hello, AI!") print(result) asyncio.run(main())
The ai_function decorator automatically detects whether the decorated function is synchronous or asynchronous and adapts accordingly.
🐞 Error Handling and Debugging
Enable detailed logging and set retry attempts:
@ai_helper.ai_function(max_retries=3, show_debug=True, debug_level=2)
def debug_example(input_data: str) -> ResponseModel:
"""
This function will display detailed debug information and retry up to 3 times on failure.
"""
📘 Examples
1. Simple Text Generation (Synchronous)
@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.
"""
haiku = generate_haiku(theme="autumn leaves")
print(haiku)
2. Complex Data Processing (Asynchronous)
class RecipeResponse(BaseModel):
name: str
ingredients: List[str]
instructions: List[str]
@ai_helper.ai_function(model="gpt-4", max_tokens=500)
async def generate_recipe(cuisine: str, dietary_restrictions: str) -> RecipeResponse:
"""
Generate a recipe based on the given cuisine and dietary restrictions.
"""
async def main():
recipe = await generate_recipe(cuisine="Italian", dietary_restrictions="vegetarian")
print(f"Recipe: {recipe.name}")
print("Ingredients:", ", ".join(recipe.ingredients))
print("Instructions:", "\n".join(f"{i+1}. {step}" for i, step in enumerate(recipe.instructions)))
asyncio.run(main())
🤝 Contributing
We welcome contributions to AI Function Helper! Here's how you can help:
- Fork the repository
- Create a new branch (
git checkout -b feature/amazing-feature) - Make your changes
- Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Please read CONTRIBUTING.md for details on our code of conduct and the process for submitting pull requests.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
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.2.4.tar.gz.
File metadata
- Download URL: ai_function_helper-0.2.4.tar.gz
- Upload date:
- Size: 12.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 |
7534e300894aa34c343209d0d97f181d98cc7be7bea79aa2fcfc3e4536c9bdc4
|
|
| MD5 |
68b6a40262120cf87757e13be9769c7a
|
|
| BLAKE2b-256 |
cf2292dfebf9664e9ace4b35183109eb42fc2a0be9fc0f129ee138432ffd1efe
|
File details
Details for the file ai_function_helper-0.2.4-py3-none-any.whl.
File metadata
- Download URL: ai_function_helper-0.2.4-py3-none-any.whl
- Upload date:
- Size: 10.2 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 |
358e2eadcb0dd258e5a632b4a9e7a813b7ba4b806eacf04dd30d492e8d8805fb
|
|
| MD5 |
b8a7d67a35d29ee4a936b6356a69d44b
|
|
| BLAKE2b-256 |
85a8e9e19656282cc9da1a1d14bfc31b60b4418a2696b8cc536f55e7aec9d7e0
|