zai-rs 0.6.0

Type-safe async Rust SDK for Zhipu AI (BigModel) APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Typed response models for assistant invocation and discovery endpoints.

use serde::{Deserialize, Serialize};

use crate::{
    ZaiResult,
    client::error::{ZaiError, codes},
};

fn empty_response(operation: &str) -> ZaiError {
    ZaiError::ApiError {
        code: codes::SDK_VALIDATION,
        message: format!("{operation} response contained no documented fields"),
    }
}

/// Text content inside a multimodal assistant response.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssistantResponseContentPart {
    /// Content type. The current response schema permits only `text`.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub type_: Option<AssistantResponseContentType>,
    /// Text content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
}

/// Content type used by a multimodal assistant response part.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AssistantResponseContentType {
    /// A text response part.
    #[serde(rename = "text")]
    Text,
}

/// Text or multimodal content returned by an assistant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AssistantResponseContent {
    /// Plain text content.
    Text(String),
    /// Multimodal response parts.
    Parts(Vec<AssistantResponseContentPart>),
}

/// Audio content returned by a voice-capable assistant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssistantResponseAudio {
    /// Audio identifier used for follow-up turns.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Base64-encoded audio data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<String>,
    /// Audio expiry timestamp as returned by the API.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
}

/// Function call returned by an assistant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssistantResponseFunctionCall {
    /// Function name.
    pub name: String,
    /// JSON-formatted function arguments.
    pub arguments: String,
}

/// MCP call type returned by an assistant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AssistantMcpCallType {
    /// List the server's available tools.
    #[serde(rename = "mcp_list_tools")]
    ListTools,
    /// Invoke one MCP tool.
    #[serde(rename = "mcp_call")]
    Call,
}

/// JSON-schema type used by an MCP input schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AssistantMcpSchemaType {
    /// JSON object schema.
    #[serde(rename = "object")]
    Object,
}

/// Input schema advertised by an MCP tool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssistantMcpInputSchema {
    /// Schema type (`object`).
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub type_: Option<AssistantMcpSchemaType>,
    /// Open map of property definitions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<serde_json::Map<String, serde_json::Value>>,
    /// Required property names.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,
    /// Whether undeclared properties are accepted.
    #[serde(
        rename = "additionalProperties",
        skip_serializing_if = "Option::is_none"
    )]
    pub additional_properties: Option<bool>,
}

/// Tool descriptor returned by an MCP list-tools call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssistantMcpTool {
    /// Tool name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Tool description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Open annotation object.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<serde_json::Map<String, serde_json::Value>>,
    /// Tool input schema.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_schema: Option<AssistantMcpInputSchema>,
}

/// MCP payload attached to an assistant tool call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssistantMcpCall {
    /// MCP call identifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// MCP operation type.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub type_: Option<AssistantMcpCallType>,
    /// MCP server label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub server_label: Option<String>,
    /// Error returned by the MCP server.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Tools returned by a list-tools operation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<AssistantMcpTool>>,
    /// JSON-formatted call arguments.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<String>,
    /// Called tool name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Open object returned by the MCP tool.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<serde_json::Map<String, serde_json::Value>>,
}

/// Tool call returned in an assistant response message.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssistantResponseToolCall {
    /// Function-call payload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function: Option<AssistantResponseFunctionCall>,
    /// MCP-call payload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mcp: Option<AssistantMcpCall>,
    /// Tool-call identifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Tool type such as `function` or `mcp`.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub type_: Option<String>,
}

/// Message returned in an assistant invocation choice.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssistantResponseMessage {
    /// Response role.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    /// Text or multimodal response content. JSON `null` maps to `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<AssistantResponseContent>,
    /// Model reasoning content, when returned.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_content: Option<String>,
    /// Voice-model audio payload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audio: Option<AssistantResponseAudio>,
    /// Function or MCP tool calls.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<AssistantResponseToolCall>>,
}

/// One assistant invocation choice.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssistantInvokeChoice {
    /// Choice index.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index: Option<i64>,
    /// Assistant message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<AssistantResponseMessage>,
    /// Completion reason.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finish_reason: Option<String>,
}

/// Token usage returned by an assistant invocation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssistantUsage {
    /// Prompt token count.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt_tokens: Option<i64>,
    /// Completion token count.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completion_tokens: Option<i64>,
    /// Total token count.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_tokens: Option<i64>,
}

/// Response from invoking an assistant.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssistantInvokeResponse {
    /// Invocation identifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Request identifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
    /// Creation timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created: Option<i64>,
    /// Model used by the assistant.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// Assistant choices.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub choices: Option<Vec<AssistantInvokeChoice>>,
    /// Token usage.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<AssistantUsage>,
}

impl AssistantInvokeResponse {
    /// Enforce the operation contract's non-empty success-response invariant.
    pub fn validate(&self) -> ZaiResult<()> {
        if self.id.is_some()
            || self.request_id.is_some()
            || self.created.is_some()
            || self.model.is_some()
            || self.choices.is_some()
            || self.usage.is_some()
        {
            Ok(())
        } else {
            Err(empty_response("assistant invoke"))
        }
    }
}

/// One key/value tag attached to an assistant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssistantTag {
    /// Tag key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
    /// Human-readable tag label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

/// Assistant record returned by the list endpoint.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssistantInfo {
    /// Assistant identifier.
    pub assistant_id: String,
    /// Assistant name.
    pub name: String,
    /// Avatar URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub avatar: Option<String>,
    /// Assistant description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Supported tool names.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<String>>,
    /// Assistant tags.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<AssistantTag>>,
    /// Assistant status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    /// Open starter-prompt objects.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub starter_prompts: Option<Vec<serde_json::Map<String, serde_json::Value>>>,
    /// Creation time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,
    /// Last update time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<String>,
}

/// Response containing assistants available to the current account.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssistantListResponse {
    /// Whether the operation succeeded.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub success: Option<bool>,
    /// Business status code.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<i64>,
    /// Business status message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub msg: Option<String>,
    /// Matching assistants.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Vec<AssistantInfo>>,
}

impl AssistantListResponse {
    /// Enforce the operation contract's non-empty success-response invariant.
    pub fn validate(&self) -> ZaiResult<()> {
        if self.success.is_some()
            || self.code.is_some()
            || self.msg.is_some()
            || self.data.is_some()
        {
            Ok(())
        } else {
            Err(empty_response("assistant list"))
        }
    }
}

/// Token usage recorded for one assistant conversation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssistantConversationUsage {
    /// Prompt token count.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt_tokens: Option<i64>,
    /// Completion token count.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completion_tokens: Option<i64>,
    /// Total token count.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_tokens: Option<i64>,
}

/// One assistant conversation record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssistantConversation {
    /// Conversation identifier.
    pub id: String,
    /// Assistant identifier.
    pub assistant_id: String,
    /// Creation time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub create_time: Option<String>,
    /// Last update time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub update_time: Option<String>,
    /// Conversation token usage.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<AssistantConversationUsage>,
}

/// Paginated assistant-conversation payload.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssistantConversationPage {
    /// Assistant identifier.
    pub assistant_id: String,
    /// Conversations on this page.
    pub conversation_list: Vec<AssistantConversation>,
    /// Whether another page is available.
    pub has_more: bool,
}

/// Response containing an assistant's conversations.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssistantConversationListResponse {
    /// Whether the operation succeeded.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub success: Option<bool>,
    /// Business status code.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<i64>,
    /// Business status message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub msg: Option<String>,
    /// Paginated conversation data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<AssistantConversationPage>,
}

impl AssistantConversationListResponse {
    /// Enforce the operation contract's non-empty success-response invariant.
    pub fn validate(&self) -> ZaiResult<()> {
        if self.success.is_some()
            || self.code.is_some()
            || self.msg.is_some()
            || self.data.is_some()
        {
            Ok(())
        } else {
            Err(empty_response("assistant conversation list"))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn list_items_preserve_required_fields() {
        let response: AssistantListResponse = serde_json::from_value(serde_json::json!({
            "success": true,
            "code": 200,
            "msg": "ok",
            "data": [{"assistant_id": "assistant-1", "name": "Helper"}]
        }))
        .unwrap();
        assert_eq!(
            response.data.as_ref().unwrap()[0].assistant_id,
            "assistant-1"
        );
        assert!(response.validate().is_ok());

        let missing_name = serde_json::from_value::<AssistantListResponse>(serde_json::json!({
            "data": [{"assistant_id": "assistant-1"}]
        }));
        assert!(missing_name.is_err());
    }

    #[test]
    fn empty_top_level_responses_violate_the_operations_contract() {
        assert!(
            serde_json::from_value::<AssistantInvokeResponse>(serde_json::json!({}))
                .unwrap()
                .validate()
                .is_err()
        );
        assert!(
            serde_json::from_value::<AssistantListResponse>(serde_json::json!({}))
                .unwrap()
                .validate()
                .is_err()
        );
        assert!(
            serde_json::from_value::<AssistantConversationListResponse>(serde_json::json!({}))
                .unwrap()
                .validate()
                .is_err()
        );
    }
}