Python SDK Deep Dive: Async, Streaming, and Error Handling
A comprehensive guide to the Rax AI Python SDK features including async operations, streaming responses, error handling, and production best practices.
Python SDK Deep Dive: Async, Streaming, and Error Handling
The official rax-ai Python SDK makes it incredibly easy to integrate Rax AI into your Python applications. In this deep-dive, we'll explore advanced features like async operations, streaming, error handling, and production best practices.
Installation
pip install rax-ai
Or add to your requirements.txt:
rax-ai>=1.0.0
Basic Usage
Start simple:
from rax_ai import RaxAI
client = RaxAI(api_key="your_rax_api_key")
response = client.chat(
model="rax-4.0",
messages=[{"role": "user", "content": "Hello, world!"}]
)
print(response.choices[0].message.content)
Async Operations
For production applications, async is essential:
import asyncio
from rax_ai import RaxAI
async def main():
client = RaxAI(api_key="your_rax_api_key")
response = await client.chat(
model="rax-4.0",
messages=[{"role": "user", "content": "Hello asynchronously!"}]
)
print(response.choices[0].message.content)
asyncio.run(main())
Concurrent Requests
Process multiple requests simultaneously:
async def process_multiple_prompts(prompts):
client = RaxAI(api_key="your_rax_api_key")
tasks = [
client.chat(
model="rax-4.0",
messages=[{"role": "user", "content": prompt}]
)
for prompt in prompts
]
responses = await asyncio.gather(*tasks)
return [r.choices[0].message.content for r in responses]
# Usage
prompts = ["Explain quantum computing", "Write a Python function", "Summarize this article"]
results = await process_multiple_prompts(prompts)
Streaming Responses
For chat-like interfaces, streaming is crucial:
import rax_ai
client = rax_ai.RaxAI(api_key="your_key")
# Streaming with callback
def on_token(token):
print(token, end="", flush=True)
response = client.chat(
model="rax-4.0",
messages=[{"role": "user", "content": "Write a poem"}],
stream=True,
on_token=on_token
)
# Or using async generator
async for chunk in client.chat_async(
model="rax-4.0",
messages=[{"role": "user", "content": "Tell me a story"}],
stream=True
):
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
Error Handling
Always handle errors gracefully:
from rax_ai import RaxAI
from rax_ai.exceptions import (
RaxAIError,
AuthenticationError,
RateLimitError,
BadRequestError
)
client = RaxAI(api_key="your_key")
try:
response = client.chat(
model="rax-4.0",
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
except AuthenticationError as e:
print(f"Invalid API key: {e}")
# Prompt user to re-authenticate
except RateLimitError as e:
print(f"Rate limit exceeded: {e}")
# Wait and retry
import time
time.sleep(60)
except BadRequestError as e:
print(f"Invalid request: {e}")
# Fix the request parameters
except RaxAIError as e:
print(f"Unexpected error: {e}")
# Log and investigate
Retry Logic with Exponential Backoff
import time
import random
from rax_ai import RaxAI
from rax_ai.exceptions import RateLimitError, RaxAIError
def make_request_with_retry(client, max_retries=5):
for attempt in range(max_retries):
try:
return client.chat(
model="rax-4.0",
messages=[{"role": "user", "content": "Hello!"}]
)
except RateLimitError:
wait = (2 ** attempt) + random.uniform(0, 1)
time.sleep(wait)
except RaxAIError as e:
if attempt == max_retries - 1:
raise
time.sleep(1)
Conversation Context Management
For multi-turn conversations:
from rax_ai import RaxAI
client = RaxAI(api_key="your_key")
# Store conversation history
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is machine learning?"}
]
# Get response
response = client.chat(
model="rax-4.0",
messages=messages
)
# Add assistant response to history
messages.append({
"role": "assistant",
"content": response.choices[0].message.content
})
# Continue conversation
messages.append({"role": "user", "content": "Can you give me an example?"})
response2 = client.chat(
model="rax-4.0",
messages=messages
)
Memory Management for Long Conversations
MAX_HISTORY_LENGTH = 15 # Keep last 15 messages
def trim_history(messages):
"""Keep conversation within token limits"""
if len(messages) > MAX_HISTORY_LENGTH:
# Keep system message + most recent messages
return [messages[0]] + messages[-(MAX_HISTORY_LENGTH-1):]
return messages
# Before each request
messages = trim_history(messages)
Configuration and Options
Model Selection
# Rax 4.0 - Fast, efficient for general tasks
response = client.chat(
model="rax-4.0",
messages=[...]
)
# Rax 4.5 - 262K context for complex tasks
response = client.chat(
model="rax-4.5",
messages=[...],
max_tokens=4096 # Need more tokens for long context
)
Generation Parameters
response = client.chat(
model="rax-4.0",
messages=[{"role": "user", "content": "Generate ideas"}],
temperature=0.8, # More creative
top_p=0.95, # Nucleus sampling
max_tokens=500, # Limit response length
frequency_penalty=0.5, # Reduce repetition
presence_penalty=0.3 # Encourage new topics
)
Production Best Practices
1. Environment Variables
import os
from rax_ai import RaxAI
client = RaxAI(
api_key=os.environ.get("RAX_API_KEY"),
endpoint=os.environ.get("RAX_ENDPOINT", "https://www.ai.raxcore.dev/api/v1")
)
2. Connection Pooling
from rax_ai import RaxAI, AsyncRaxAI
# For async applications
client = AsyncRaxAI(
api_key="key",
pool_size=10 # Reuse connections
)
3. Logging and Monitoring
import logging
import time
from rax_ai import RaxAI
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class MonitoredRaxAI(RaxAI):
def chat(self, **kwargs):
start = time.time()
try:
response = super().chat(**kwargs)
duration = time.time() - start
logger.info(f"Rax request completed in {duration:.2f}s")
return response
except Exception as e:
duration = time.time() - start
logger.error(f"Rax request failed after {duration:.2f}s: {e}")
raise
4. Request Caching
from functools import lru_cache
import hashlib
import json
class CachedRaxAI(RaxAI):
@lru_cache(maxsize=1000)
def _cached_hash(self, model, messages, params):
key_data = json.dumps({
"model": model,
"messages": messages,
"params": params
}, sort_keys=True)
return hashlib.md5(key_data.encode()).hexdigest()
def chat(self, model, messages, **params):
cache_key = self._cached_hash(model, tuple(messages), json.dumps(params, sort_keys=True))
# Check cache...
# If not in cache, call super().chat() and store result
Migration from OpenAI
If you're coming from OpenAI, the transition is seamless:
# OpenAI
from openai import OpenAI
client = OpenAI(api_key="sk-your-key")
# Rax AI (drop-in replacement)
from rax_ai import RaxAI
client = RaxAI(api_key="rax-your-key", endpoint="https://www.ai.raxcore.dev/api/v1")
# Same API, just change the key and optionally the endpoint
response = client.chat.completions.create(
model="rax-4.0", # or rax-4.5
messages=[{"role": "user", "content": "Hello!"}]
)
Conclusion
The rax-ai Python SDK is designed for production use with comprehensive async support, efficient streaming, and robust error handling. Whether you're building a simple chatbot or a complex agentic system, the SDK provides the tools you need.
For more examples and the latest documentation, visit docs.raxcore.dev.
Keywords: Python LLM SDK, async AI, streaming Python, error handling, production Python AI, keywords: ['Python AI SDK', 'async LLM', 'streaming responses', 'error handling', 'migration from OpenAI']
Ready to Build with Sub-50ms Latency AI?
Get started with Rax AI today. Free API key, native SDKs for Python, JS, and Flutter, and enterprise support.