Skip to main content

A4F Python SDK

PyPI version Python License: MIT Downloads Code style: black Type Checker: mypy PyPI - Wheel

The official Python SDK for A4F — your unified AI gateway to seamlessly access hundreds of AI models across providers through a single, powerful API.


Table of Contents


🚀 Installation

Prerequisites

  • Python 3.8+ required
  • pip package manager

Install via pip

pip install a4f

🔄 Quick Start

1. Get Your API Key

Sign up at A4F.co and obtain your API key from the dashboard.

2. Initialize the Client

from a4f import A4F

# Initialize with API key
client = A4F(api_key="your_api_key_here")

3. Make Your First Request

response = client.chat.create(
    model="provider-3/gpt-5-nano",
    messages=[
        {"role": "system", "content": "You are a helpful AI assistant."},
        {"role": "user", "content": "Explain quantum computing in simple terms."}
    ],
    max_tokens=500,
    temperature=0.7
)

print(response.choices[0].message.content)

🔑 Authentication

Environment Variables (Recommended)

export A4F_API_KEY="your_api_key_here"
from a4f import A4F

# Automatically uses A4F_API_KEY environment variable
client = A4F()

Direct API Key

from a4f import A4F

client = A4F(api_key="your_api_key_here")

Configuration File

import os
from a4f import A4F

# Load from config file
api_key = os.getenv("A4F_API_KEY")
client = A4F(api_key=api_key)

🌟 Core Features

💬 Chat Completions

Basic Chat

response = client.chat.completions.create(
    model="provider-3/gpt-5-nano",
    messages=[
        {"role": "user", "content": "What is machine learning?"}
    ],
    max_tokens=150,
    temperature=0.5
)

print(response.choices[0].message.content)

Streaming Responses

stream = client.chat.completions.create(
    model="provider-3/gpt-5-nano",
    messages=[
        {"role": "user", "content": "Count from 1 to 10 slowly"}
    ],
    stream=True,
    max_tokens=100
)

print("Streaming response:")
for chunk in stream:
    if chunk.has_content:
        print(chunk.content, end="", flush=True)
print("\n")

Advanced Chat with System Prompts

response = client.chat.completions.create(
    model="provider-3/gpt-5-nano",
    messages=[
        {
            "role": "system", 
            "content": "You are an expert data scientist. Provide detailed, technical explanations."
        },
        {
            "role": "user", 
            "content": "Explain the difference between supervised and unsupervised learning."
        }
    ],
    max_tokens=800,
    temperature=0.3,
    top_p=0.9
)

🖼️ Image Generation

Text-to-Image

image_response = client.images.generate(
    model="provider-4/imagen-4",
    prompt="A serene mountain landscape at sunset with a crystal clear lake reflecting the sky",
    size="1024x1024",
    quality="standard",
    n=1
)

# Save the image
image_url = image_response.data[0].url
print(f"Generated image: {image_url}")

Image Editing

with open("original_image.jpg", "rb") as image_file:
    edited_image = client.images.edit(
        model="provider-3/flux-kontext-pro",
        image=image_file,
        prompt="Convert the cartoon characters to photorealistic people",
        size="1024x1024"
    )
    
print(f"Edited image: {edited_image.data[0].url}")

🎙️ Audio Processing

Speech-to-Text (Transcription)

# Transcribe audio file
with open("meeting_recording.mp3", "rb") as audio_file:
    transcription = client.audio.transcriptions.create(
        file=audio_file,
        model="provider-3/whisper-1"
    )
    
print(f"Transcription: {transcription}")

Text-to-Speech (TTS)

speech_response = client.audio.speech.create(
    input="Hello! This is a demonstration of high-quality text-to-speech conversion using the A4F SDK.",
    model="provider-3/gemini-2.5-flash-preview-tts",
    voice="Orus",
    response_format="mp3",
    speed=1.0
)

# Save audio to file
speech_response.write_to_file("generated_speech.mp3")
print("Speech saved to generated_speech.mp3")

🔎 Text Embeddings

Single Text Embedding

embedding_response = client.embeddings.create(
    model="provider-6/qwen3-embedding-4b",
    input="The quick brown fox jumps over the lazy dog"
)

vector = embedding_response.data[0].embedding
print(f"Embedding dimension: {len(vector)}")

Batch Embeddings

texts = [
    "Machine learning is a subset of artificial intelligence.",
    "Natural language processing enables computers to understand human language.",
    "Computer vision allows machines to interpret visual information."
]

embeddings = client.embeddings.create(
    model="provider-6/qwen3-embedding-4b",
    input=texts
)

for i, embedding_obj in enumerate(embeddings.data):
    print(f"Text {i+1} embedding dimension: {len(embedding_obj.embedding)}")

⚙️ Advanced Configuration

Client Configuration

from a4f import A4F
import logging

# Configure comprehensive client settings
client = A4F(
    api_key="your_api_key_here",
    timeout=60  # Request timeout in seconds
)

Request-Level Configuration

# Per-request configuration
response = client.chat.completions.create(
    model="provider-3/gpt-5-nano",
    messages=[{"role": "user", "content": "Hello!"}],
    timeout=30,           # Override default timeout
)

Model Parameters

# Comprehensive parameter configuration
response = client.chat.completions.create(
    model="provider-3/gpt-5-nano",
    messages=[{"role": "user", "content": "Write a creative story."}],
    max_tokens=1000,
    temperature=0.8,      # Creativity level (0.0 - 2.0)
    top_p=0.9           # Nucleus sampling
)

❌ Error Handling

Error Handling

from a4f import A4F

client = A4F(api_key="your_api_key_here")

try:
    response = client.chat.create(
        model="provider-3/gpt-5-nano",
        messages=[{"role": "user", "content": "Hello!"}]
    )
    print(response.choices[0].message.content)
    
except Exception as e:
    print(f"Unexpected error: {e}")

🏭 Production Considerations

Environment Configuration

import os
from a4f import A4F

class A4FConfig:
    def __init__(self):
        self.api_key = os.getenv("A4F_API_KEY")
        self.timeout = int(os.getenv("A4F_TIMEOUT", "60"))
        self.max_retries = int(os.getenv("A4F_MAX_RETRIES", "3"))
        
    def create_client(self):
        return A4F(
            api_key=self.api_key,
            timeout=self.timeout,
            max_retries=self.max_retries
        )

# Usage
config = A4FConfig()
client = config.create_client()

Logging and Monitoring

import logging
from a4f import A4F

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

logger = logging.getLogger(__name__)

def monitored_chat_request(client, messages, model="provider-3/gpt-5-nano"):
    try:
        logger.info(f"Making chat request with model: {model}")
        
        response = client.chat.completions.create(
            model=model,
            messages=messages
        )
        
        logger.info(f"Request successful. Tokens used: {response.usage.total_tokens}")
        return response
        
    except Exception as e:
        logger.error(f"Request failed: {str(e)}")
        raise

📚 API Reference

Chat Completions

Parameter Type Default Description
model str Required Model identifier (e.g., "provider-3/gpt-5-nano")
messages List[Dict] Required Conversation messages
max_tokens int None Maximum tokens to generate
temperature float 1.0 Sampling temperature (0.0-2.0)
top_p float 1.0 Nucleus sampling parameter
stream bool False Enable streaming responses

Image Generation

Parameter Type Default Description
prompt str Required Text description of the image
model str Required Image model identifier
size str "1024x1024" Image dimensions
quality str "standard" Image quality ("standard" or "hd")
n int 1 Number of images to generate

Audio Processing

Parameter Type Default Description
file BinaryIO Required Audio file to process
model str Required Audio model identifier

Embeddings

Parameter Type Default Description
input Union[str, List[str]] Required Text(s) to embed
model str Required Embedding model identifier

🌐 What is A4F?

A4F.co is a revolutionary AI gateway that simplifies interaction with multiple AI providers. Instead of integrating with OpenAI, Anthropic, Google, and others separately, A4F provides one consistent API to access them all, making development faster, cheaper, and more reliable.

Key Benefits

Feature Description Benefits
🌐 Unified API Consistent interface for all models Reduced complexity, faster development
💰 Free Tier Start building with no upfront costs Risk-free experimentation
⚡ High Availability Built-in failover & load balancing 99.9% uptime guarantee
💸 Cost Optimization Smart routing & price-performance tuning Up to 40% cost savings
🔒 Privacy Controls Granular provider selection Enterprise-grade security
🚀 Production-Ready Enterprise scalability and support Mission-critical reliability

Model Coverage

  • Text Generation: GPT-4, Claude, Gemini, Llama, Qwen, and more
  • Image Generation: DALL-E, Stable Diffusion, Imagen
  • Audio Processing: Whisper, Google Cloud TTS
  • Embeddings: OpenAI, Cohere, Sentence Transformers
  • Specialized Models: Code generation, translation, summarization

📧 Support & Resources

Documentation & Guides

Community

Developer Resources


📄 License

This project is licensed under the MIT License. See the LICENSE file for details.


Built with ❤️ by the A4F Team — Your Unified AI Gateway

Ready to get started? Sign up for free and get your API key today!

Metadata

Release files for a4f 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for a4f 0.1.0
File Size Uploaded
a4f-0.1.0.tar.gz 99.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for a4f 0.1.0
File Interpreter ABI Platform
a4f-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 245.5 kB

Release files / a4f-0.1.0.tar.gz

Download URL a4f-0.1.0.tar.gz
Size 99.6 kB
Tags Source
SHA-256 checksum
How to use checksums
25cbf66122891f4d945e69aafab6995cdb9edfad22438c6b238fc055ca19740f
BLAKE2b-256 checksum
How to use checksums
060146b8e32e728d536fcee09a86f0b51ec9763690b92a2be1d9cd72cb5c9abc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.23

Release files / a4f-0.1.0-py3-none-any.whl

Download URL a4f-0.1.0-py3-none-any.whl
Size 145.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e70ef378915d51a7dfc6185a0361e467546e1edbc0220c68359c66b9fee119de
BLAKE2b-256 checksum
How to use checksums
5c93d928450a9fceed717a38ae86d518a4b69427496f593191881743eca323ec
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.23

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page