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
//! Minimal example: streaming tool calls (tool_stream)
//!
//! This example shows how to enable tool_stream with GLM-4.6 and print
//! incremental tool_call payloads while streaming.
//!
//! Supported models: GLM-5.1, GLM-5, GLM-5-Turbo, GLM-4.7, GLM-4.6
//!
//! Run:
//! cargo run --example tool_stream_min
use serde_json::json;
use zai_rs::model::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1) Read API key
let key = std::env::var("ZHIPU_API_KEY").expect("Set ZHIPU_API_KEY in your environment");
// 2) Define a minimal function tool schema (no real execution here; just to
// trigger tool calls)
let add_tool = Tools::Function {
function: Function::new(
"add",
"Add two numbers",
json!({
"type": "object",
"properties": {
"a": {"type": "number", "description": "left operand"},
"b": {"type": "number", "description": "right operand"}
},
"required": ["a", "b"],
"additionalProperties": false
}),
),
};
// 3) Build a streaming chat request with tool_stream enabled (GLM-4.6 only)
let model = GLM4_6 {};
let mut client = ChatCompletion::new(
model,
TextMessage::user("请使用函数 add 计算 7 和 5 的和,然后给出最终答案。"),
key,
)
.add_tools(vec![add_tool])
.with_coding_plan()
.enable_stream()
.with_tool_stream(true);
client
.stream_for_each(move |chunk: ChatStreamResponse| async move {
if let Some(tool_calls) = chunk
.choices
.first()
.and_then(|choice| choice.delta.as_ref())
.and_then(|delta| delta.tool_calls.as_ref())
{
println!("{:#?}", tool_calls);
}
Ok(())
})
.await?;
Ok(())
}