> ## Documentation Index
> Fetch the complete documentation index at: https://apione.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 结构化输出与工具调用

> 按模型能力使用 JSON 输出和工具调用，并验证业务结果。

Chat 接口提供 `response_format`、`tools` 和 `tool_choice` 字段。先确认目标模型支持需要的能力，再在应用中解析和校验结果。

## JSON 输出

以下示例要求使用支持 JSON 模式的模型。先按 [SDK 接入](https://apione.ai/docs/guides/sdks.md) 安装依赖，设置 `APIONE_API_KEY` 和 `APIONE_MODEL`，再保存为 `json_output.py` 并运行 `python json_output.py`。

```python theme={null}
import json
import os
from openai import OpenAI

with OpenAI(
    base_url="https://api.apione.ai/v1",
    api_key=os.environ["APIONE_API_KEY"],
) as client:
    response = client.chat.completions.create(
        model=os.environ["APIONE_MODEL"],
        messages=[
            {"role": "system", "content": '仅返回 JSON，包含 category 字符串，取值为 feature、bug 或 other。'},
            {"role": "user", "content": "为帮助中心增加搜索。"},
        ],
        response_format={"type": "json_object"},
    )

choice = response.choices[0]
if choice.finish_reason != "stop" or not choice.message.content:
    raise ValueError("输出不完整或没有 JSON 正文")
data = json.loads(choice.message.content)
if (
    not isinstance(data, dict)
    or not isinstance(data.get("category"), str)
    or data["category"] not in {"feature", "bug", "other"}
):
    raise ValueError("category 字段不符合业务要求")
print(data)
```

`json_object` 请求 JSON 输出，应用仍需检查结束原因、解析结果、校验字段和取值范围。仅在提示词中写“返回 JSON”，不能代替 Schema 约束。

## JSON Schema

`response_format` 也可以携带 `json_schema`。支持的 Schema 子集和严格模式依模型而异，先查看目标模型参数，再决定约束方式。不要假设换模型后原 Schema 仍能使用。

## 工具调用流程

1. 在 `tools` 中声明允许调用的函数及参数；需要指定选择方式时使用 `tool_choice`，并确认模型支持。
2. 读取 `choices[].message.tool_calls`，其中可能有多个调用，普通正文可能为空。
3. 保留这一轮 assistant 消息。应用校验工具名、解析参数，并检查用户权限；外部写操作按业务规则确认后执行。
4. 将每个工具的结果作为 `role: "tool"` 的消息回传，用 `tool_call_id` 对应原调用的 `id`。
5. 带上更新后的消息历史再次请求模型，读取最终回答；应用应限制工具循环次数。

APIONE 返回工具调用请求，函数由应用执行。不要将未经校验的模型生成 URL、SQL 或命令直接交给执行器。

## 兼容问题

出现 `unsupported_parameter` 时，先删除可选参数，验证[最小对话请求](https://apione.ai/docs/models/chat.md)，再逐个恢复。切换模型时重新确认 JSON、工具和[流式能力](https://apione.ai/docs/models/streaming.md)。完整字段见 [APIONE Chat 参考](https://apione.ai/zh/api-docs/reference/ref-chat)。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.