Python Integration Guide
Add AI safety guardrails to your Python applications using the official SDK or direct API calls. Includes FastAPI, Flask, and Django integrations.
Prerequisites
- Python 3.8 or higher
- A Tork API key (get one here)
- pip or poetry for package management
Installation
Install the SDK or dependencies for direct API calls.
Never commit your API key. Add .env to .gitignore and use python-dotenv to load it.
SDK Usage (Recommended)
The official SDK provides a clean, Pythonic interface.
Direct API Calls
Use requests or httpx if you prefer not to use the SDK.
Error Handling & Retry Logic
Handle API errors gracefully with exponential backoff.
HTTP Status Codes
| 200 | Success | Process response |
| 400 | Bad request | Fix request body, don't retry |
| 401 | Unauthorized | Check API key, don't retry |
| 429 | Rate limited | Wait and retry (check Retry-After) |
| 500+ | Server error | Retry with exponential backoff |
Framework Integrations
Ready-to-use examples for popular Python web frameworks
Batch Processing
Evaluate multiple items efficiently with controlled concurrency.
Context Managers
Use context managers for clean resource management.
Best Practices
Use the SDK for production
The official SDK handles retries, connection pooling, and error handling automatically.
Prefer async for high throughput
Use AsyncTorkClient or httpx for applications handling many concurrent requests.
Implement proper error handling
Catch specific exceptions and decide whether to fail open or closed based on your requirements.
Use middleware for web frameworks
Middleware provides consistent protection across all endpoints without code duplication.
Cache evaluation results
For repeated content, consider caching results (with appropriate TTL) to reduce API calls.
Log request IDs
Always log the request_id from responses for debugging and support inquiries.
Full Type Hints Support
The tork-governance SDK includes complete type hints and is compatible with mypy and pyright. All response objects are fully typed for excellent IDE autocomplete support.
Next Steps
Explore more endpoints for jailbreak detection, RAG validation, and multi-agent orchestration.