Module :: api_openai
Comprehensive, type-safe Rust client for OpenAI's API with enterprise reliability features.
🎯 Architecture: Stateless HTTP Client
This API crate is designed as a stateless HTTP client with zero persistence requirements. It provides:
- Direct HTTP calls to the OpenAI API
- In-memory operation state only (resets on restart)
- No external storage dependencies (databases, files, caches)
- No configuration persistence beyond environment variables
This ensures lightweight, containerized deployments and eliminates operational complexity.
🏛️ Governing Principle: "Thin Client, Rich API"
Expose all server-side functionality transparently while maintaining zero client-side intelligence or automatic behaviors.
Key principles:
- API Transparency: One-to-one mapping with OpenAI API endpoints
- Zero Client Intelligence: No automatic behaviors or magic thresholds
- Explicit Control: Developer decides when, how, and why operations occur
- Information vs Action: Clear separation between data retrieval and state changes
Scope
In Scope
- Chat completions (conversational AI)
- Responses API (create, retrieve, update, delete, stream)
- Realtime API (WebSocket communication)
- Audio (text-to-speech, speech-to-text)
- Images (generation, manipulation)
- Embeddings (text vectorization)
- Files (upload, management)
- Fine-tuning (custom model training)
- Assistants (AI assistant management)
- Vector stores (document storage)
- Models (listing, information)
- Moderations (content safety)
- Enterprise reliability (retry, circuit breaker, rate limiting, failover, health checks)
- Custom base URLs (Azure OpenAI, compatible APIs)
Out of Scope
- Model hosting or training infrastructure
- Persistent state management
- High-level abstractions beyond API mapping
- Business logic or application features
Features
- Comprehensive API Coverage: Full implementation of OpenAI's REST API (all major endpoints)
- Type-Safe: Strong typing for all requests and responses with compile-time validation
- Async/Await: Built on
tokiofor high-performance async operations - Streaming Support: Real-time streaming via Server-Sent Events and WebSocket
- Custom Base URLs: Support for Azure OpenAI, OpenAI-compatible APIs, and corporate proxies
- Enterprise Reliability: Retry logic, circuit breaker, rate limiting, failover, health checks
- Sync API Variants: Blocking interface for non-async contexts
- Secure Secret Management: Comprehensive fallback chain with workspace_tools integration
- Error Handling: Robust error handling using error_tools with detailed error types
Supported APIs
- Responses API: Create, retrieve, update, delete, and stream responses
- Realtime API: WebSocket-based real-time communication
- Chat Completions: Conversational AI interactions
- Audio: Text-to-speech and speech-to-text
- Images: Image generation and manipulation
- Files: File upload and management
- Fine-tuning: Custom model training
- Assistants: AI assistant management
- Vector Stores: Document storage and retrieval
- Embeddings: Text vectorization
- Models: Model information and capabilities
- Moderations: Content safety and moderation
Quick Start
Basic Usage (Official OpenAI API)
use ;
async
Custom Base URL (Azure OpenAI / Compatible APIs)
use ;
async
Examples
See the examples/ directory for comprehensive examples of all API endpoints:
Responses API
responses_create.rs- Basic response creation (planned)responses_create_stream.rs- Streaming responses (planned)openai_responses_create_with_tools.rs- Function callingopenai_responses_create_image_input.rs- Multimodal inputopenai_responses_get.rs- Retrieve responsesopenai_responses_update.rs- Update responsesopenai_responses_delete.rs- Delete responsesopenai_responses_cancel.rs- Cancel responses
Realtime API
openai_realtime_response_create.rs- Real-time responsesopenai_realtime_input_audio_buffer_append.rs- Audio streamingopenai_realtime_session_update.rs- Session management
Run any example with:
Testing
The crate includes comprehensive tests for all API endpoints with 100% pass rate:
# Run all tests (683 tests)
# Run with strict warnings
RUSTFLAGS="-D warnings"
# Run clippy
# Full verification (ctest3)
RUSTFLAGS="-D warnings" && \
RUSTDOCFLAGS="-D warnings" && \
Test Statistics:
- Total: 683 tests (100% passing)
- Integration tests: Real API validation with mandatory failing behavior
- Unit tests: Comprehensive coverage of all modules
- Doc tests: 7 documentation examples tested
Note: Integration tests require a valid OpenAI API key. Tests fail loudly if credentials are unavailable (no silent fallbacks).
Authentication
The crate supports multiple authentication methods via comprehensive fallback chain:
1. Workspace Secrets (Recommended)
# Create workspace secrets file
2. Environment Variable
3. Programmatic
use Secret;
let secret = load_with_fallbacks?; // Tries all methods
// Or explicitly:
let secret = load_from_env?;
let secret = new?; // With validation
Fallback Chain Order:
- Workspace secrets file (
../../secret/-secrets.sh) - Environment variable (
OPENAI_API_KEY) - Alternative secret files (
secrets.sh,.env) - Programmatic setting
Security Features:
- API key format validation (must start with
sk-) - Secure in-memory storage using
secrecycrate - Audit trail for secret exposure tracking
- No logging of actual secret values
Error Handling
The library provides comprehensive error handling:
use OpenAIError;
match client.responses.create.await
Architecture
The crate follows a layered architecture using the mod_interface pattern:
- Client Layer: High-level API client (
Client) - API Layer: Individual API implementations (e.g.,
Responses,Chat) - Components Layer: Request/response types and shared components
- Environment Layer: Configuration and authentication
- Error Layer: Comprehensive error handling
Contributing
- All examples must use snake_case naming
- Include comprehensive documentation and examples
- Add tests for new functionality
- Follow the existing code patterns and architecture
License
See the license file for details.
Responsibility
This section documents all files and directories in the crate root, ensuring Complete Entity Coverage per organizational_principles.rulebook.md.
| Path | Purpose |
|---|---|
src/ |
Source code implementation - client, APIs, components, error handling |
tests/ |
Comprehensive test suite with 287 tests, zero mocking policy |
examples/ |
API usage examples demonstrating all major endpoints |
docs/ |
Technical documentation organized in design collections |
scripts/ |
Build automation and development scripts |
Cargo.toml |
Crate metadata, dependencies, and feature configuration |
readme.md |
Crate overview, quick start, API documentation, and this Responsibility Table |
license |
MIT license text |
clippy.toml |
Clippy linter configuration |
Directory Responsibilities
Each directory contains its own readme.md with detailed Responsibility Table:
- src/: Module-level documentation (components/, enterprise/, environment/, realtime/)
- tests/: Testing policies, test organization, and test suite documentation
- examples/: Example index, usage patterns, and API tutorials
- docs/: Design collections with master files for each collection type
- scripts/: Script documentation and usage instructions