Skip to main content

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//! ```text
50//! use zai_rs::{client::ZaiClient, model::*};
51//!
52//! #[tokio::main]
53//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
54//!     let model = GLM4_5_flash {};
55//!     let client = ZaiClient::from_env()?;
56//!     let request = ChatCompletion::new(model, TextMessage::user("Hello"));
57//!     let _resp = request.send_via(&client).await?;
58//!     Ok(())
59//! }
60//! ```
61//!
62//! # Streaming Requests
63//!
64//! ```text
65//! use zai_rs::{client::ZaiClient, model::*};
66//!
67//! #[tokio::main]
68//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
69//!     let model = GLM4_5_flash {};
70//!     let client = ZaiClient::from_env()?;
71//!     let request = ChatCompletion::new(model, TextMessage::user("Hello"));
72//!     let _response = request.send_via(&client).await?;
73//!     Ok(())
74//! }
75//! ```
76//!
77//! # Configuration
78//!
79//! `ZaiConfig` is the central place for credentials, endpoint families, and
80//! HTTP transport settings. It mirrors the API families exposed by
81//! [`client::EndpointConfig`], including the dedicated Coding Plan
82//! endpoint required by official Zhipu AI documentation.
83//!
84//! ```text
85//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
86//! use zai_rs::ZaiConfig;
87//!
88//! let config = ZaiConfig::builder()
89//!     .api_key("abc123.abcdefghijklmnopqrstuvwxyz")
90//!     .paas_v4_base("https://open.bigmodel.cn/api/paas/v4")
91//!     .coding_paas_v4_base("https://open.bigmodel.cn/api/coding/paas/v4")
92//!     .build()?;
93//!
94//! assert_eq!(
95//!     config.coding_paas_v4_url("chat/completions"),
96//!     "https://open.bigmodel.cn/api/coding/paas/v4/chat/completions"
97//! );
98//! # Ok(())
99//! # }
100//! ```
101//!
102//! # Feature Flags
103//!
104//! | Feature | Default | Description |
105//! |---------|---------|-------------|
106//! | (default) | enabled | Core API functionality |
107//! | `realtime` | disabled | Real-time audio/video over WebSocket (GLM-Realtime) |
108//! | `rmcp-kits` | disabled | Enable RMCP protocol bridge for MCP tool calling |
109//! | `tool-validation` | disabled | Runtime validation of tool-call arguments against their JSON Schema |
110//!
111//! Enable in `Cargo.toml`:
112//! ```toml
113//! [dependencies]
114//! zai-rs = { version = "0.4", features = ["rmcp-kits"] }
115//! ```
116//!
117//! # Error Handling
118//!
119//! All API calls return `ZaiResult<T>`,
120//! unified under the [`ZaiError`] enum:
121//!
122//! - `ApiError` — Business-level API error (with code and message)
123//! - `NetworkError` — Network / timeout error
124//! - `JsonError` — JSON serialization / deserialization error
125//! - `RateLimitError` — Rate-limit or quota exceeded
126//! - `ContentPolicyError` — API policy or unsafe-content block
127//! - `AuthError` — Authentication / authorization error
128//!
129//! # Design Principles
130//!
131//! - **Compile-time type safety** — trait bounds and type-state patterns ensure
132//!   model/message compatibility at compile time
133//! - **Zero-cost abstractions** — marker traits and type-state patterns impose
134//!   no runtime overhead
135//! - **Consistent API style** — request builders carry typed payloads and all
136//!   network operations are dispatched with `send_via(&ZaiClient)`
137
138// On docs.rs (which builds with `--cfg docsrs`, see `[package.metadata.docs.rs]`
139// in Cargo.toml), enable the nightly `doc_cfg` feature so feature-gated items
140// are badged in the rendered documentation. The `cfg_attr` is inert on stable
141// local builds, where `docsrs` is never set.
142#![cfg_attr(docsrs, feature(doc_cfg))]
143
144pub mod agent;
145pub mod batches;
146pub mod client;
147pub use client::{ZaiClient, error::*};
148pub mod file;
149pub mod knowledge;
150
151pub mod model;
152/// WebSocket realtime (GLM-Realtime) client — audio/video over a WebSocket.
153/// Gated behind the `realtime` Cargo feature (off by default).
154#[cfg(feature = "realtime")]
155pub mod realtime;
156pub mod services;
157pub mod tool;
158pub mod toolkits;
159pub mod usage;
160
161pub mod prelude;