Python SDK
The official Python SDK for PolarGrid with async and sync clients.Installation
pip install polargrid-sdk
Quick Start
Async Client (Recommended)
import asyncio
from polargrid import PolarGrid
async def main():
# Auto-select best region by latency
client = await PolarGrid.create(api_key="pg_your_api_key")
print(f"Connected to: {client.get_region_name()}") # e.g., "Vancouver"
response = await client.chat_completion({
"model": "llama-3.1-8b",
"messages": [
{"role": "user", "content": "Hello!"}
]
})
print(response.choices[0].message.content)
asyncio.run(main())
Sync Client
from polargrid import PolarGridSync
client = PolarGridSync(api_key="pg_your_api_key", region="toronto")
response = client.chat_completion({
"model": "llama-3.1-8b",
"messages": [{"role": "user", "content": "Hello!"}]
})
print(response.choices[0].message.content)
Configuration
# Async client with auto-routing (recommended)
client = await PolarGrid.create(
api_key="pg_your_api_key", # or set POLARGRID_API_KEY env var
debug=True,
)
# Sync constructor with explicit region
client = PolarGrid(
api_key="pg_your_api_key",
# Region: 'toronto', 'vancouver', 'montreal' (or yto-01, yvr-02, yul-01)
region="vancouver",
# Request timeout in seconds (default: 30.0)
timeout=30.0,
# Max retry attempts (default: 3)
max_retries=3,
# Enable debug logging
debug=True,
# Use mock data for development
use_mock_data=False,
)
Auto-Routing
# Tests latency to all regions and picks fastest
client = await PolarGrid.create(api_key="pg_...", debug=True)
# [PolarGrid] Auto-routing: latency results: yto-01=32ms, yvr-02=45ms, yul-01=82ms
# [PolarGrid] Auto-routing: selected Toronto (yto-01) with 32ms latency
print(client.get_region_id()) # 'yto-01'
print(client.get_region_name()) # 'Toronto'
Streaming
async for chunk in client.chat_completion_stream({
"model": "llama-3.1-8b",
"messages": [{"role": "user", "content": "Tell me a story"}],
}):
content = chunk.choices[0].delta.content
if content:
print(content, end="", flush=True)
Mock Mode
client = PolarGrid(
use_mock_data=True, # No API calls
debug=True,
)
# All methods return realistic mock data
response = await client.chat_completion({
"model": "llama-3.1-8b",
"messages": [{"role": "user", "content": "Hello!"}]
})
Type Hints
The SDK uses Pydantic models with full type hints:from polargrid.types import (
ChatCompletionRequest,
ChatCompletionResponse,
Message,
)
# Request with typed model
request = ChatCompletionRequest(
model="llama-3.1-8b",
messages=[Message(role="user", content="Hello!")],
max_tokens=100,
)
# Or use dict (auto-converted)
response = await client.chat_completion({
"model": "llama-3.1-8b",
"messages": [{"role": "user", "content": "Hello!"}],
})
Environment Variables
export POLARGRID_API_KEY=pg_your_api_key
export POLARGRID_BASE_URL=https://api.yto-01.edge.polargrid.ai # Optional
Next Steps
Full Reference
Complete API reference
Voice Guide
Text-to-speech and speech-to-text
