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 for the Zhipu AI (BigModel) API.
4//! 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 text, vision, and 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//! | MCP | Unified search, reader, repository, and vision capabilities | [`mcp`] |
26//! | Agent | Agent creation & management | [`agent`] |
27//! | Tool execution framework | Dynamic registration, execution, caching | [`toolkits`] |
28//! | Real-time | WebSocket audio/video (GLM-Realtime) | [`realtime`] |
29//! | Coding Plan usage | GLM Coding Plan quota / 余量查询 | [`usage`] |
30//!
31//! # Module Structure
32//!
33//! - [`client`] — HTTP client, connection pool, retry strategy, error types
34//! - [`model`] — Data models, request/response types, model definitions, SSE
35//!   parsing
36//! - [`mod@file`] — File management (upload, list, content, delete)
37//! - [`batches`] — Batch processing (create, list, retrieve, cancel)
38//! - [`knowledge`] — Knowledge-base management (CRUD, document upload,
39//!   retrieval)
40//! - [`tool`] — Tool implementations (web search, file parsing)
41//! - [`mcp`] — Unified MCP capabilities with automatic backend and transport
42//!   selection (feature `mcp`)
43//! - [`agent`] — Agent API (creation, chat, history)
44//! - [`toolkits`] — Tool execution framework (registration, execution, caching,
45//!   RMCP bridge)
46//! - [`realtime`] — Real-time audio/video communication (WebSocket,
47//!   experimental)
48//! - [`usage`] — Coding Plan usage / quota query (GLM Coding Plan 余量查询)
49//!
50//! # Quick Start
51//!
52//! ```rust,no_run
53//! use zai_rs::{client::ZaiClient, model::*};
54//!
55//! #[tokio::main]
56//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
57//!     let model = GLM4_5_flash {};
58//!     let client = ZaiClient::from_env()?;
59//!     let request = ChatCompletion::new(model, TextMessage::user("Hello"));
60//!     let _resp = request.send_via(&client).await?;
61//!     Ok(())
62//! }
63//! ```
64//!
65//! # Configuration
66//!
67//! [`ZaiClient`] owns credentials, validated endpoint families, connection
68//! pooling, timeouts, and retry policy. Clone the client to share the same
69//! transport safely across requests.
70//!
71//! ```rust,no_run
72//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
73//! use zai_rs::client::{ApiFamily, ZaiClient};
74//!
75//! let client = ZaiClient::builder("abc123.abcdefghijklmnopqrstuvwxyz")
76//!     .endpoint(
77//!         ApiFamily::CodingPaasV4,
78//!         "https://open.bigmodel.cn/api/coding/paas/v4",
79//!     )
80//!     .build()?;
81//!
82//! assert_eq!(
83//!     client.endpoints().base(ApiFamily::CodingPaasV4).as_str(),
84//!     "https://open.bigmodel.cn/api/coding/paas/v4"
85//! );
86//! # Ok(())
87//! # }
88//! ```
89//!
90//! # Feature Flags
91//!
92//! | Feature | Default | Description |
93//! |---------|---------|-------------|
94//! | (default) | enabled | Core API functionality |
95//! | `realtime` | disabled | Real-time audio/video over WebSocket (GLM-Realtime) |
96//! | `mcp` | disabled | Unified high-level MCP capability client |
97//! | `rmcp-kits` | disabled | Enable RMCP protocol bridge for MCP tool calling |
98//! | `toolkits` | disabled | JSON-Schema validation for the tool-execution framework |
99//!
100//! Enable in `Cargo.toml`:
101//! ```toml
102//! [dependencies]
103//! zai-rs = { version = "0.6", features = ["mcp"] }
104//! ```
105//!
106//! # Error Handling
107//!
108//! All API calls return `ZaiResult<T>`,
109//! unified under the [`ZaiError`] enum:
110//!
111//! Error variants distinguish HTTP, authentication, account, API, rate-limit,
112//! content-policy, file, network, JSON, realtime, and unknown failures. Use
113//! [`ZaiError::category`](client::ZaiError::category) when recovery logic only
114//! needs a coarse classification.
115//!
116//! # Design Principles
117//!
118//! - **Compile-time type safety** — trait bounds and type-state patterns ensure
119//!   model/message compatibility at compile time
120//! - **Zero-cost abstractions** — marker traits and type-state patterns impose
121//!   no runtime overhead
122//! - **Consistent API style** — request builders carry typed payloads and all
123//!   network operations are dispatched with `send_via(&ZaiClient)`
124
125// On docs.rs (which builds with `--cfg docsrs`, see `[package.metadata.docs.rs]`
126// in Cargo.toml), enable the nightly `doc_cfg` feature so feature-gated items
127// are badged in the rendered documentation. The `cfg_attr` is inert on stable
128// local builds, where `docsrs` is never set.
129#![cfg_attr(docsrs, feature(doc_cfg))]
130// Public API documentation is part of the compatibility surface. Keep missing
131// docs visible in normal development and fatal under the workspace CI gate.
132#![warn(missing_docs)]
133
134pub mod agent;
135pub mod batches;
136pub mod client;
137pub use client::{ZaiClient, error::*};
138pub mod file;
139pub mod knowledge;
140
141/// Unified MCP capability client.
142#[cfg(feature = "mcp")]
143pub mod mcp;
144
145pub mod model;
146/// WebSocket realtime (GLM-Realtime) client — audio/video over a WebSocket.
147/// Gated behind the `realtime` Cargo feature (off by default).
148#[cfg(feature = "realtime")]
149pub mod realtime;
150mod serde_helpers;
151/// Typed service facades for application, assistant, image, and document tools.
152pub mod services;
153pub mod tool;
154pub mod toolkits;
155pub mod usage;
156
157pub mod prelude;