Skip to main content

Concurrent Fast OpenAI calls with Automatic Rate Limiting to avoid hitting limits. Structured Outputs with Pydantic Base Models.

Project description

throttle-openai

A Python library for making concurrent OpenAI API calls with automatic rate limiting and structured outputs using Pydantic models. Credit: Blogpost by Villoro

Installation

pip install throttle-openai

Quick Start

1. Define Your Output Structure

First, create a Pydantic model that defines your expected output structure:

from pydantic import BaseModel, Field
from typing import Literal

class Sentiment_Prediction_Output(BaseModel):
    reasoning: str = Field(description="Reasoning for the sentiment prediction in one sentence.")
    sentiment: Literal['Positive', 'Negative', 'Neutral']

    class Config:
        title = "Sentiment Prediction Output"
        description = "Sentiment prediction with reasoning."

2. Make API Calls

Here's a complete example showing how to analyze sentiments for multiple product reviews:

from throttle_openai import async_batch_chat_completion
import asyncio
import os

async def analyze_sentiment():
    # Prepare batch messages
    batch_messages = [
        {
            "messages": [
                {"role": "system", "content": "You are a sentiment analyzer. Analyze the sentiment of the given text."},
                {"role": "user", "content": "I like this product. It's good."}
            ],
            "id": "1"  # id is optional
        },
        {
            "messages": [
                {"role": "system", "content": "You are a sentiment analyzer. Analyze the sentiment of the given text."},
                {"role": "user", "content": "I don't like this product. It's bad."}
            ],
            "id": "2"
        }
    ]

    # Make concurrent API calls
    output, errors = await async_batch_chat_completion(
        batch_messages=batch_messages,
        gpt_model='gpt-4o-mini',
        pydantic_model=Sentiment_Prediction_Output,
        api_key=os.getenv("OPENAI_API_KEY")
    )

    return output, errors

# Run the analysis
output, errors = asyncio.run(analyze_sentiment())

# Process results
print("Results:", output)
if errors:
    print("Errors:", errors)

Features

  • Concurrent Processing: Automatically handles multiple API calls concurrently
  • Rate Limiting: Built-in rate limiting to prevent hitting OpenAI's API limits
  • Structured Output: Uses Pydantic models for type-safe and validated outputs
  • Error Handling: Separate error collection for failed requests
  • ID Tracking: Optional ID field to track individual requests and responses

Environment Variables

Set your OpenAI API key as an environment variable:

export OPENAI_API_KEY=your_api_key

Complete Example

Check out examples/basic_usage_structured_output.py for a complete example featuring structured outputs.

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

throttle_openai-0.1.3.tar.gz (6.4 kB view details)

Uploaded Source

Built Distribution

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

throttle_openai-0.1.3-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

File details

Details for the file throttle_openai-0.1.3.tar.gz.

File metadata

  • Download URL: throttle_openai-0.1.3.tar.gz
  • Upload date:
  • Size: 6.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.5 CPython/3.10.12 Linux/6.5.0-1025-azure

File hashes

Hashes for throttle_openai-0.1.3.tar.gz
Algorithm Hash digest
SHA256 deca4922fe39e7ba3e84d7eb3f7c92098e1009273cfcc5d1fcadcd1fff955d82
MD5 73a2fdc8dfdc764a8c9f67c91fdd65ae
BLAKE2b-256 3898c3c2505adac0eb44481c47a66b0e573381bef9fe8b6f2aa4e001f23e6d83

See more details on using hashes here.

File details

Details for the file throttle_openai-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: throttle_openai-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 8.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.5 CPython/3.10.12 Linux/6.5.0-1025-azure

File hashes

Hashes for throttle_openai-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 07cfe65a2f0e6273499513fa39ccd84d787cd551335230609a2811765a8187b0
MD5 82df74b819785f67a0895359c206b3bd
BLAKE2b-256 dfafb0e50ab56f65aae382aeb00d0724a1f7707b322d6d2b5fdde112114476b3

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