OriginTensorDOCS
返回主站 创建 API Key
开发指南 · API v1

工具调用

定义工具、执行模型返回的调用、回传结果,并正确拼接流式 tool_calls 碎片。

OpenAI 兼容Anthropic 原生更新于 2026-12-05
管理 API Key

Agent loop

工具调用的完整循环

01

声明工具

把工具名称、描述与 JSON Schema 放入 tools。

02

模型请求调用

响应 finish_reason 为 tool_calls,message 中包含调用列表。

03

执行并回传

在应用侧执行工具,把结果以 role: tool 消息回传。

Define

定义工具

Tool definition
{
  "model": "glm-5.3",
  "messages": [
    {"role": "user", "content": "北京现在的天气怎么样?"}
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "查询指定城市的当前天气",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {"type": "string", "description": "城市名称"}
          },
          "required": ["city"],
          "additionalProperties": false
        }
      }
    }
  ],
  "tool_choice": "auto"
}

Non-streaming

非流式工具循环

Complete tool loop
import json
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["ORIGINTENSOR_API_KEY"],
    base_url="https://api.origintensor.com/v1",
    timeout=60.0,
)

def get_weather(city):
    # 示例实现;生产环境替换为真实天气服务。
    return {"city": city, "weather": "晴", "temperature_c": 22}

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "查询指定城市的当前天气",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]

messages = [{"role": "user", "content": "北京现在的天气怎么样?"}]
response = client.chat.completions.create(
    model="glm-5.3",
    messages=messages,
    tools=tools,
)

message = response.choices[0].message
messages.append(message.model_dump(exclude_none=True))

for call in message.tool_calls or []:
    args = json.loads(call.function.arguments)
    result = get_weather(**args)
    messages.append({
        "role": "tool",
        "tool_call_id": call.id,
        "content": json.dumps(result, ensure_ascii=False),
    })

final = client.chat.completions.create(
    model="glm-5.3",
    messages=messages,
    tools=tools,
)
print(final.choices[0].message.content)

Streaming

拼接流式工具调用

Accumulate tool call fragments
calls = {}

with client.chat.completions.create(
    model="glm-5.3",
    messages=[{"role": "user", "content": "北京现在的天气怎么样?"}],
    tools=tools,
    stream=True,
) as stream:
    for chunk in stream:
        for choice in chunk.choices or []:
            for part in choice.delta.tool_calls or []:
                item = calls.setdefault(part.index, {
                    "id": "", "name": "", "arguments": ""
                })
                if part.id:
                    item["id"] = part.id
                if part.function and part.function.name:
                    item["name"] = part.function.name
                if part.function and part.function.arguments:
                    item["arguments"] += part.function.arguments

for index in sorted(calls):
    call = calls[index]
    args = json.loads(call["arguments"])
    print(call["id"], call["name"], args)

不要对每个 fragment 调用 json.loads。参数可能被拆成多个 chunk,必须等流结束后再解析。

Anthropic

Messages 工具调用

Anthropic 工具调用以 tool_use 内容块出现。执行结果应作为下一条 user 消息中的 tool_result 内容块回传,并使用相同的 tool_use_id。

Anthropic tool_result
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_...",
      "content": "{\"city\":\"北京\",\"weather\":\"晴\",\"temperature_c\":22}"
    }
  ]
}

Safety

工具执行安全

  • 模型输出是建议,不是授权。执行写操作、支付、删除或外部请求前必须做参数校验与权限检查。
  • 为工具设置超时、重试上限、并发限制和审计日志。
  • 不要把 API Key 或内部管理凭据作为工具参数暴露给模型。
  • 对并行工具调用检查资源冲突与幂等性。
输入 API 名称、参数、错误码或场景,例如「stream」「429」「Anthropic」「缓存」。