Skip to main content

A helper for creating AI-powered functions using OpenAI's API

Project description

AI Function Helper

PyPI version License: MIT Python Versions

Streamline your AI-powered Python functions with ease!

Key FeaturesInstallationQuick StartDocumentationContributing


📚 Table of Contents

🌟 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:

  1. AIFunctionHelper Class: The main entry point for creating AI-powered functions.
  2. AI Function Decorator: Transforms regular Python functions into AI-powered ones, supporting both sync and async usage.
  3. Pydantic Models: Ensures type safety and easy validation of AI-generated responses.
  4. Error Handling: Built-in mechanisms for handling API errors and retrying failed calls.
  5. 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:

  1. Using ai_result Parameter:

    def func(ai_result: ResponseModel, input: str) -> ResponseModel:
    
  2. Direct Pydantic Model Return:

    def func(input: str) -> ResponseModel:
    
  3. String Output:

    def func(input: str) -> str:
    
  4. Unspecified Return Type:

    def func(input: str):
    

Synchronous vs Asynchronous Usage

AI Function Helper now supports both synchronous and asynchronous usage:

  1. 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)
    
  2. 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:

  1. Fork the repository
  2. Create a new branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Commit your changes (git commit -m 'Add some amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ai_function_helper-0.2.3.tar.gz (12.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ai_function_helper-0.2.3-py3-none-any.whl (10.2 kB view details)

Uploaded Python 3

File details

Details for the file ai_function_helper-0.2.3.tar.gz.

File metadata

  • Download URL: ai_function_helper-0.2.3.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

Hashes for ai_function_helper-0.2.3.tar.gz
Algorithm Hash digest
SHA256 422441f21ed00dff24253ddca7abaad668d7b446c20d3895378024e1162d8e2a
MD5 fe5b1965ffd968a963dc3efecbd4e904
BLAKE2b-256 6553004bde1de31c15ac9f4ad238e86c4c032ed5cd145c0fc9acfe4b0b73c674

See more details on using hashes here.

File details

Details for the file ai_function_helper-0.2.3-py3-none-any.whl.

File metadata

File hashes

Hashes for ai_function_helper-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 363b8449d11e7cba4fe08a00a54d6353f245c461a50e52ca2814087c6a4f44b1
MD5 bd002289a88a27c0d0ed9e93a48d5af5
BLAKE2b-256 29cce45e58d911c98f8ddba0fae9cb9d6abc3c1443a571cf9c32d31f55ec37cd

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