Catalog PyPI
PACKAGE EXPLORERView in registry

a4f

PyPI

Official Python SDK for A4F - Unified AI Gateway for chat, images, audio, and embeddings

a4faiapiartificialchat-gptcliclientembeddingsfreeimage-generationintelligencelearningllmmachinemlsdk
All keywords (17)
speech-recognition
Versions collected1
Direct dependencies11From release 0.1.0
Last observed20 Oct, 16:42 UTC

README

Version 0.1.0 documentation

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

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

ParameterTypeDefaultDescription
modelstrRequiredModel identifier (e.g., "provider-3/gpt-5-nano")
messagesList[Dict]RequiredConversation messages
max_tokensintNoneMaximum tokens to generate
temperaturefloat1.0Sampling temperature (0.0-2.0)
top_pfloat1.0Nucleus sampling parameter
streamboolFalseEnable streaming responses

Image Generation

ParameterTypeDefaultDescription
promptstrRequiredText description of the image
modelstrRequiredImage model identifier
sizestr"1024x1024"Image dimensions
qualitystr"standard"Image quality ("standard" or "hd")
nint1Number of images to generate

Audio Processing

ParameterTypeDefaultDescription
fileBinaryIORequiredAudio file to process
modelstrRequiredAudio model identifier

Embeddings

ParameterTypeDefaultDescription
inputUnion[str, List[str]]RequiredText(s) to embed
modelstrRequiredEmbedding 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

FeatureDescriptionBenefits
🌐 Unified APIConsistent interface for all modelsReduced complexity, faster development
💰 Free TierStart building with no upfront costsRisk-free experimentation
⚡ High AvailabilityBuilt-in failover & load balancing99.9% uptime guarantee
💸 Cost OptimizationSmart routing & price-performance tuningUp to 40% cost savings
🔒 Privacy ControlsGranular provider selectionEnterprise-grade security
🚀 Production-ReadyEnterprise scalability and supportMission-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!

Downloads & popularity

Awaiting observations

No metric observations yet

Download counts and popularity will appear here as the collector receives them.

Versions 1

Collected releases
VersionPublishedDirect dependenciesOpen version
0.1.026 Sept 202511

Package advisories

0
No matching advisories collected

This describes our collected data; it is not a security assessment.

Metadata history

Meaningful changes
Current collected state Current

Observed since 20 Oct, 16:42 UTC

No superseded metadata states collected. Unchanged observations do not create new revisions.

Record identity

package:7837871b1b202349fc0a05d572bbed5f454e3d494ef86aa9b34831d51ed25b41