zai_rs/lib.rs
1//! # ZAI-RS: Zhipu AI Rust SDK
2//!
3//! `zai-rs` is a type-safe Rust SDK providing full coverage of the Zhipu AI
4//! (BigModel) API. Strongly-typed clients and models span chat completions,
5//! image generation, speech recognition, text embeddings, knowledge-base
6//! management, and more.
7//!
8//! # Capabilities
9//!
10//! | Capability | Description | Module |
11//! |------------|-------------|--------|
12//! | Chat completions | Sync / async / streaming text, vision, voice | [`model`] |
13//! | Image generation | Text-to-image | [`model::gen_image`] |
14//! | Video generation | Async text-to-video | [`model::gen_video_async`] |
15//! | Text-to-speech | Audio synthesis | [`model::text_to_audio`] |
16//! | Speech-to-text | Audio transcription | [`model::audio_to_text`] |
17//! | Voice cloning | Voice clone, list, delete | [`model::voice_clone`] |
18//! | Text embeddings | Embeddings, reranking, tokenization | [`model::text_embedded`] |
19//! | Content moderation | Safety analysis | [`model::moderation`] |
20//! | OCR | Handwriting recognition | [`model::ocr`] |
21//! | File management | Upload, list, content, delete | [`mod@file`] |
22//! | Batch processing | Create, list, retrieve, cancel | [`batches`] |
23//! | Knowledge base | CRUD, document upload, retrieval | [`knowledge`] |
24//! | Tool calling | Function calling, web search, file parsing | [`tool`] |
25//! | Agent | Agent creation & management | [`agent`] |
26//! | Tool execution framework | Dynamic registration, execution, caching | [`toolkits`] |
27//! | Real-time | WebSocket audio/video (GLM-Realtime) | [`realtime`] |
28//! | Coding Plan usage | GLM Coding Plan quota / 余量查询 | [`usage`] |
29//!
30//! # Module Structure
31//!
32//! - [`client`] — HTTP client, connection pool, retry strategy, error types
33//! - [`model`] — Data models, request/response types, model definitions, SSE
34//! parsing
35//! - [`mod@file`] — File management (upload, list, content, delete)
36//! - [`batches`] — Batch processing (create, list, retrieve, cancel)
37//! - [`knowledge`] — Knowledge-base management (CRUD, document upload,
38//! retrieval)
39//! - [`tool`] — Tool implementations (web search, file parsing)
40//! - [`agent`] — Agent API (creation, chat, history)
41//! - [`toolkits`] — Tool execution framework (registration, execution, caching,
42//! RMCP bridge)
43//! - [`realtime`] — Real-time audio/video communication (WebSocket,
44//! experimental)
45//! - [`usage`] — Coding Plan usage / quota query (GLM Coding Plan 余量查询)
46//!
47//! # Quick Start
48//!
49//! ```rust,no_run
50//! use zai_rs::{client::http::*, model::*};
51//!
52//! #[tokio::main]
53//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
54//! let model = GLM4_5_flash {};
55//! let key = std::env::var("ZHIPU_API_KEY").unwrap();
56//! let client = ChatCompletion::new(model, TextMessage::user("Hello"), key);
57//! let _resp = client.post().await?;
58//! Ok(())
59//! }
60//! ```
61//!
62//! # Streaming Responses
63//!
64//! ```rust,no_run
65//! use zai_rs::{client::http::*, model::*};
66//!
67//! #[tokio::main]
68//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
69//! let model = GLM4_5_flash {};
70//! let key = std::env::var("ZHIPU_API_KEY").unwrap();
71//! let mut client =
72//! ChatCompletion::new(model, TextMessage::user("Hello"), key).enable_stream();
73//! client
74//! .stream_sse_for_each(|data| {
75//! print!("{}", String::from_utf8_lossy(data));
76//! })
77//! .await?;
78//! Ok(())
79//! }
80//! ```
81//!
82//! # Feature Flags
83//!
84//! | Feature | Default | Description |
85//! |---------|---------|-------------|
86//! | (default) | enabled | Core API functionality |
87//! | `rmcp-kits` | disabled | Enable RMCP protocol bridge for MCP tool calling |
88//! | `web-example` | disabled | Enable axum/tower dependencies for web examples |
89//!
90//! Enable in `Cargo.toml`:
91//! ```toml
92//! [dependencies]
93//! zai-rs = { version = "0.2", features = ["rmcp-kits"] }
94//! ```
95//!
96//! # Error Handling
97//!
98//! All API calls return [`ZaiResult`](client::error::ZaiResult)`<T>`,
99//! unified under the [`ZaiError`](client::error::ZaiError) enum:
100//!
101//! - `ApiError` — Business-level API error (with code and message)
102//! - `NetworkError` — Network / timeout error
103//! - `JsonError` — JSON serialization / deserialization error
104//! - `RateLimitError` — Rate-limit or quota exceeded
105//! - `AuthError` — Authentication / authorization error
106//!
107//! # Design Principles
108//!
109//! - **Compile-time type safety** — trait bounds and type-state patterns ensure
110//! model/message compatibility at compile time
111//! - **Zero-cost abstractions** — marker traits and type-state patterns impose
112//! no runtime overhead
113//! - **Consistent API style** — all API clients follow a uniform builder
114//! pattern and implement the `HttpClient` trait
115
116pub mod agent;
117pub mod batches;
118pub mod client;
119pub use client::{config::ZaiConfig, error::*};
120pub mod file;
121pub mod knowledge;
122
123pub mod model;
124pub mod realtime;
125pub mod tool;
126pub mod toolkits;
127pub mod usage;
128pub use usage::{
129 CodingPlanQuotaKind, CodingPlanQuotaLimit, CodingPlanQuotaSummary, CodingPlanUsageData,
130 CodingPlanUsageDetail, CodingPlanUsageRequest, CodingPlanUsageResponse, CodingPlanUsageSummary,
131 query as query_coding_plan_usage, query_summary as query_coding_plan_usage_summary,
132};