--- title: "工具、结构化输出与流式响应" description: "分别验证 XiuRouter 的工具调用、JSON Schema 结构化输出和 Chat Completions 流式响应。" image: "https://docs.xiu.ai/og.png" --- > XiuAI 文档索引 > 完整文档索引:https://docs.xiu.ai/llms.txt > 阅读前先通过索引确认当前可用页面。 # 工具、结构化输出与流式响应 工具调用、结构化输出和流式响应是三项独立能力。先用同一模型跑通普通文本,再逐项验证,不要用一次成功推断其余能力也可用。 ## 工具调用 下面的请求只让模型选择工具,不会真的执行函数: ```bash curl https://router-api.xiu.ai/v1/chat/completions \ -H "Authorization: Bearer $XIUROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "YOUR_MODEL_ID", "messages": [ { "role": "user", "content": "台北现在几点?请使用工具。" } ], "tools": [ { "type": "function", "function": { "name": "get_time", "description": "读取指定时区的当前时间", "parameters": { "type": "object", "properties": { "utc_offset": { "type": "string" } }, "required": ["utc_offset"], "additionalProperties": false } } } ], "tool_choice": "auto" }' ``` 成功时,模型会在 `choices[0].message.tool_calls` 中返回工具名和参数。你的应用仍需: 1. 校验工具名和参数。 2. 在受控环境执行工具。 3. 把结果作为 `role: "tool"` 消息发回。 4. 读取模型的最终回答。 普通文本成功但没有 `tool_calls` 时,先确认所选模型和当前服务分组支持工具调用,不要在客户端伪造工具结果。 ## 结构化输出 Chat Completions 请求可以携带 `response_format`。下面示例要求返回固定 JSON 结构: ```bash curl https://router-api.xiu.ai/v1/chat/completions \ -H "Authorization: Bearer $XIUROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "YOUR_MODEL_ID", "messages": [ { "role": "user", "content": "把北京归类为一个城市。" } ], "response_format": { "type": "json_schema", "json_schema": { "name": "city", "strict": true, "schema": { "type": "object", "properties": { "name": {"type": "string"}, "country": {"type": "string"} }, "required": ["name", "country"], "additionalProperties": false } } } }' ``` 网关会解析 `response_format`,但目标模型可能只支持 `json_object`、不支持严格 Schema,或完全不支持结构化输出。生产代码仍要解析并校验返回值,不能因为请求带了 Schema 就跳过验证。 ## 流式响应 使用 `curl -N` 避免本地缓冲: ```bash curl -N https://router-api.xiu.ai/v1/chat/completions \ -H "Authorization: Bearer $XIUROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "YOUR_MODEL_ID", "messages": [ { "role": "user", "content": "用三句话说明什么是 API 网关。" } ], "stream": true, "stream_options": { "include_usage": true } }' ``` Chat Completions 流通常以 SSE `data:` 事件返回,并以结束事件收口。Responses API 使用另一组事件类型;客户端要按实际协议解析,不要把两种流格式混在一起。 ## 验证 - 工具:收到结构正确的 `tool_calls`,并完成一次只读工具往返。 - 结构化输出:返回值通过你的 JSON Schema 校验。 - 流式:收到多个事件、完整结束信号,并在“使用记录”中看到“流式”标记和最终费用。 ## 常见失败 | 现象 | 处理 | | --- | --- | | 返回普通文本而不是工具调用 | 更换已验证工具能力的模型,或把 `tool_choice` 改为指定工具测试 | | `response_format` 被拒绝 | 降级为 `json_object` 或普通文本后自行校验 | | 流在中途断开 | 确认使用 `router-api.xiu.ai`;保留请求 ID 并先查使用记录 | | 流结束但没有用量事件 | 上游可能不支持 `include_usage`;以使用记录为最终核对入口 | | 工具参数不是合法 JSON | 拒绝执行,记录原始参数并让模型重新生成 | ## 来源与核对日期 本文按 XiuRouter 当前 Chat Completions 请求结构、流式处理代码和控制台使用记录核对,日期为 2026-08-19。本轮没有使用真实 Key 对每个模型执行工具或结构化输出测试。 源文件:https://docs.xiu.ai/router/tools-streaming/index.mdx