Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
ai-lib-rust
Protocol runtime for AI-Protocol — high-performance Rust reference implementation (v1.2.0).
ai-lib-rust is the umbrella crate most applications depend on. It re-exports ai-lib-core (execution) and ai-lib-contact (policy) so existing ai_lib_rust::… import paths stay stable.
How it works
Default chat path: AiClient loads a provider manifest → builds a Pipeline from manifest operators → sends HTTP via HttpTransport. Streaming frames are normalized to StreamingEvent.
This is protocol-driven for chat, but not “zero provider code”: the repo also ships provider-specific decoders/mappers, optional ProviderDriver implementations (advanced / WASM / tests), and standalone HTTP clients for embeddings, STT, TTS, and rerank.
| Layer | Crate | Responsibility |
|---|---|---|
| Execution (E) | ai-lib-core |
AiClient, pipeline, protocol, transport, types, structured, optional capability modules |
| Policy (P) | ai-lib-contact |
context (layered assemble), resilience, cache, routing, plugins, guardrails, batch, telemetry, tokens |
| Facade | ai-lib-rust |
Re-exports + examples, integration tests, CLI bins |
Published on crates.io: ai-lib-core, ai-lib-contact, ai-lib-rust (all 1.2.0). ai-lib-wasm is built for wasm32-wasip1 and is not published.
Pin: Prefer crates.io 1.2.0 (tag
v1.2.0). CI pinsai-protocolv1.1.0. See CHANGELOG.
Quick start
[]
= "1.2.0"
= { = "1", = ["full"] }
use ;
async
Same example: cargo run --example basic_usage (requires DEEPSEEK_API_KEY).
Streaming
use ;
use StreamExt;
async
Share across tasks
AiClient is not Clone (API key / ToS boundary). Use Arc<AiClient>:
use AiClient;
use Arc;
let client = new;
Public API (crate root)
Always available (non-WASM):
- Client:
AiClient,AiClientBuilder,ChatBatchRequest,CancelHandle,CallStats,ClientMetrics,EndpointExt - Types:
Message,MessageRole,StreamingEvent,ToolCall,ExecutionMetadata,ExecutionResult,ExecutionUsage - Errors:
Result,Error,ErrorContext,StandardErrorCode - Feedback:
FeedbackEvent,FeedbackSink - Structured output:
structuredmodule (JsonModeConfig,OutputValidator, …) - Text-tool / TTC:
StandardTextToolParser,ToolCallingPolicy,TextToolConfig, … - Policy (always re-exported):
cache,context,plugins,resilience
ai_lib_rust::context (policy layer, always on) includes layered context assembly: MessageChunk, ContextLayer, MessageAssembler::assemble_layered, AssemblePool (async façade with concurrency / timeout), and AssembleError::HardBudgetViolation when System+Active exceed the token budget.
Feature-gated re-exports from ai-lib-contact: batch, guardrails, interceptors, routing (routing_mvp), telemetry, tokens.
Feature-gated modules in ai-lib-core: embeddings, mcp, computer_use, multimodal, stt, tts, rerank.
What features actually do
| Feature | What you get | Notes |
|---|---|---|
keyring (default) |
OS keyring credential fallback | Disable with default-features = false for slim/CI builds |
embeddings |
EmbeddingClient |
Protocolized builders: from_model / from_manifest (no vendor URL default) |
stt / tts / reranking |
SttClient, TtsClient, RerankerClient |
Standalone service clients; rerank supports from_model / from_manifest |
mcp |
McpToolBridge |
Wire-format conversion / filtering; no built-in MCP transport client |
computer_use |
ComputerAction, SafetyPolicy |
Schema + validation; no action execution runtime |
multimodal |
MultimodalCapabilities |
Modality detection / format checks |
reasoning |
Registry flag only | Reasoning deltas work in core pipeline without enabling this |
batch |
BatchExecutor (contact) |
AiClient::chat_batch / chat_batch_smart are always available |
telemetry |
InMemoryFeedbackSink, report_feedback, … |
Core exports FeedbackEvent / FeedbackSink without this feature |
routing_mvp |
CustomModelManager, ModelArray, … |
Pure routing helpers |
full |
All features above |
Enable features in Cargo.toml:
= { = "1.2.0", = ["embeddings", "telemetry"] }
Advanced: ProviderDriver
ai_lib_rust::drivers exposes ProviderDriver, create_driver, and OpenAI / Anthropic / Gemini drivers. AiClient does not use this path for chat; it uses Pipeline::from_manifest. Drivers are for WASM targets, compliance tests, and custom integrations.
Resilience
- Built into
AiClient:max_inflightbackpressure (AiClientBuilder::max_inflightorAI_LIB_MAX_INFLIGHT). - Opt-in policy layer:
ai_lib_rust::resilience(retry, rate limiter, circuit breaker) — wire beside the client; not auto-enabled onAiClient::new. - Batch concurrency:
AI_LIB_BATCH_CONCURRENCY. - HTTP proxy: reqwest system proxy (
HTTP_PROXY/HTTPS_PROXY/NO_PROXY) on the direct route; setAI_PROXY_URLfor an explicit failover candidate route.
Protocol manifests
Resolution order for provider manifests:
ProtocolLoader::with_base_path(...)AI_PROTOCOL_DIR/AI_PROTOCOL_PATH(local dir or GitHub raw URL)- Dev paths:
ai-protocol/,../ai-protocol/, … - Fallback: GitHub raw
ailib-official/ai-protocol(main)
Per base path: dist/v2/providers/<id>.json → v2/providers/<id>.yaml → dist/v1/providers/<id>.json → v1/providers/<id>.yaml.
Identity / aliases: load_provider resolves marketplace aliases via dist/provider-identity.json (multi-family map), e.g. google → gemini, kimi → moonshot. Validation errors are not masked by alias lookup.
Wire model id: chat requests resolve the OpenAI-compatible model field via the v1 model registry (resolve_wire_model_id), with NIM-aware fallback for nvidia/<name> ids.
Endpoints: operation "chat" falls back to endpoints.chat_openai when the canonical chat key is absent (DeepSeek dual-API manifests).
Model modalities (Experimental): when metadata.models.<id> is present, those modality facts are preferred over provider-level ads (ALR-ME-001).
Manifest cache: in-memory only. with_hot_reload(true) stores a flag but does not watch files — call ProtocolLoader::clear_cache() or rebuild the client after manifest changes.
API keys
- Builder override (if set)
- Manifest-declared env vars (
auth.token_env/auth.key_env) - Conventional
<PROVIDER_ID>_API_KEYenv var - OS keyring (optional,
keyringfeature, desktop)
Recommended for CI/containers: env vars; use default-features = false to drop keyring.
Standard error codes (V2)
| Code | Name | Retryable | Fallbackable |
|---|---|---|---|
| E1001 | invalid_request |
No | No |
| E1002 | authentication |
No | Yes |
| E1003 | permission_denied |
No | No |
| E1004 | not_found |
No | No |
| E1005 | request_too_large |
No | No |
| E2001 | rate_limited |
Yes | Yes |
| E2002 | quota_exhausted |
No | Yes |
| E3001 | server_error |
Yes | Yes |
| E3002 | overloaded |
Yes | Yes |
| E3003 | timeout |
Yes | Yes |
| E4001 | conflict |
Yes | No |
| E4002 | cancelled |
No | No |
| E9999 | unknown |
No | No |
Testing
# Unit + integration (facade crate)
# Cross-runtime YAML compliance
COMPLIANCE_DIR=../ai-protocol/tests/compliance
# All optional features
Mock server integration (requires ai-protocol-mock):
MOCK_HTTP_URL=http://localhost:4010
Examples
| Example | Features |
|---|---|
basic_usage |
— |
deepseek_chat_stream |
streaming collect |
custom_protocol |
manifest paths |
resilience_patterns |
policy layer |
batch_processing |
batch |
embeddings_similarity |
embeddings |
guardrails_usage |
guardrails |
multi_provider |
routing_mvp |
tavily_tool_calling |
tools |
| … | see crates/ai-lib-rust/Cargo.toml [[example]] and examples/ |
CLI bins: cargo run --bin validate_protocols, cargo run --bin ai-protocol-cli.
WASM
# → target/wasm32-wasip1/release/ai_lib_wasm.wasm
Related
- AI-Protocol — specification & manifests
- ai-lib-python — Python runtime
- docs/ARCHITECTURE.md — workspace layout
License
Dual-licensed under Apache-2.0 or MIT.