Skip to main content

Crate zai_rs

Crate zai_rs 

Source
Expand description

§ZAI-RS: Zhipu AI Rust SDK

zai-rs is a type-safe Rust SDK for the Zhipu AI (BigModel) API. Strongly-typed clients and models span chat completions, image generation, speech recognition, text embeddings, knowledge-base management, and more.

§Capabilities

CapabilityDescriptionModule
Chat completionsSync / async text, vision, and voicemodel
Image generationText-to-imagemodel::gen_image
Video generationAsync text-to-videomodel::gen_video_async
Text-to-speechAudio synthesismodel::text_to_audio
Speech-to-textAudio transcriptionmodel::audio_to_text
Voice cloningVoice clone, list, deletemodel::voice_clone
Text embeddingsEmbeddings, reranking, tokenizationmodel::text_embedded
Content moderationSafety analysismodel::moderation
OCRHandwriting recognitionmodel::ocr
File managementUpload, list, content, deletefile
Batch processingCreate, list, retrieve, cancelbatches
Knowledge baseCRUD, document upload, retrievalknowledge
Tool callingFunction calling, web search, file parsingtool
MCPUnified search, reader, repository, and vision capabilitiesmcp
AgentAgent creation & managementagent
Tool execution frameworkDynamic registration, execution, cachingtoolkits
Real-timeWebSocket audio/video (GLM-Realtime)realtime
Coding Plan usageGLM Coding Plan quota / 余量查询usage

§Module Structure

  • client — HTTP client, connection pool, retry strategy, error types
  • model — Data models, request/response types, model definitions, SSE parsing
  • file — File management (upload, list, content, delete)
  • batches — Batch processing (create, list, retrieve, cancel)
  • knowledge — Knowledge-base management (CRUD, document upload, retrieval)
  • tool — Tool implementations (web search, file parsing)
  • mcp — Unified MCP capabilities with automatic backend and transport selection (feature mcp)
  • agent — Agent API (creation, chat, history)
  • toolkits — Tool execution framework (registration, execution, caching, RMCP bridge)
  • realtime — Real-time audio/video communication (WebSocket, experimental)
  • usage — Coding Plan usage / quota query (GLM Coding Plan 余量查询)

§Quick Start

use zai_rs::{client::ZaiClient, model::*};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let model = GLM4_5_flash {};
    let client = ZaiClient::from_env()?;
    let request = ChatCompletion::new(model, TextMessage::user("Hello"));
    let _resp = request.send_via(&client).await?;
    Ok(())
}

§Configuration

ZaiClient owns credentials, validated endpoint families, connection pooling, timeouts, and retry policy. Clone the client to share the same transport safely across requests.

use zai_rs::client::{ApiFamily, ZaiClient};

let client = ZaiClient::builder("abc123.abcdefghijklmnopqrstuvwxyz")
    .endpoint(
        ApiFamily::CodingPaasV4,
        "https://open.bigmodel.cn/api/coding/paas/v4",
    )
    .build()?;

assert_eq!(
    client.endpoints().base(ApiFamily::CodingPaasV4).as_str(),
    "https://open.bigmodel.cn/api/coding/paas/v4"
);

§Feature Flags

FeatureDefaultDescription
(default)enabledCore API functionality
realtimedisabledReal-time audio/video over WebSocket (GLM-Realtime)
mcpdisabledUnified high-level MCP capability client
rmcp-kitsdisabledEnable RMCP protocol bridge for MCP tool calling
toolkitsdisabledJSON-Schema validation for the tool-execution framework

Enable in Cargo.toml:

[dependencies]
zai-rs = { version = "0.6", features = ["mcp"] }

§Error Handling

All API calls return ZaiResult<T>, unified under the ZaiError enum:

Error variants distinguish HTTP, authentication, account, API, rate-limit, content-policy, file, network, JSON, realtime, and unknown failures. Use ZaiError::category when recovery logic only needs a coarse classification.

§Design Principles

  • Compile-time type safety — trait bounds and type-state patterns ensure model/message compatibility at compile time
  • Zero-cost abstractions — marker traits and type-state patterns impose no runtime overhead
  • Consistent API style — request builders carry typed payloads and all network operations are dispatched with send_via(&ZaiClient)

Re-exports§

pub use client::ZaiClient;
pub use client::error::*;

Modules§

agent
Agent v1 wire contracts
batches
Batch Processing Module
client
HTTP client infrastructure: the shared ZaiClient, validated endpoints, transport policies and error types.
file
File Management Module
knowledge
Knowledge Base Module
mcpmcp
Unified MCP capability client. Unified API for MCP capabilities.
model
Model Module
prelude
Convenience imports for the most common client and chat APIs.
realtimerealtime
WebSocket realtime (GLM-Realtime) client — audio/video over a WebSocket. Gated behind the realtime Cargo feature (off by default).
services
Typed service facades for application, assistant, image, and document tools. Request and response types for service-oriented Z.AI endpoints.
tool
Tool Module
toolkits
Tool definition, execution, caching, and LLM tool-call parsing utilities. Supports both static tool definitions and dynamic registration at runtime.
usage
Coding Plan Usage / Quota Query