Kimi API 多个 tool_calls 怎么回填?并行工具调用顺序核对

Kimi API 多个 tool_calls 怎么回填?并行工具调用顺序核对
本文目录(9 节)

Kimi API 多个 tool_calls 的回填,核心只有两条:把模型返回的完整 assistant message 原样放回 messages,再为每一个 tool_call 单独追加一条带 tool_call_id 的 role: "tool" 消息。顺序错乱几乎都出在”只回传 content”或”id 对不上”这两件事上,和工具在本地是串行还是并发执行关系不大。本文依据官方资料整理,本站未实测。

结论先行:三个动作,一个核对点

官方文档在工具调用的最小示例里给了一个明确写法:首轮用 tool_choice="required" 强制至少调用一个工具,执行每个调用后回传完整 assistant message,并用对应的 tool_call_id 逐条追加工具结果(见 Kimi K3.1 Pro 快速开始)。把它拆开就是三个动作:

  1. 原样回传 assistant message。 官方在”重要限制”里明确写着:多轮对话和工具调用必须原样回传完整 assistant message,不要只保留 content。
  2. 每个 tool_call 对应一条 tool 消息。 每条 {"role": "tool", "tool_call_id": ..., "content": ...},而不是把两个结果拼成一段文本塞回去。
  3. id 用响应给的,不要自己造。 tool_calls[i].id 是回填的唯一匹配键。

一个核对点:回填的 tool_call_id 集合,必须和 assistant message 里 tool_calls 的 id 集合完全相等。 少一条、多一条、拼错一个字符,下一轮模型拿到的数据关系就是错的。

响应结构:tool_calls 是数组,arguments 是字符串

按官方 Chat Completions API 的响应格式,工具调用挂在 choices[0].message.tool_calls 下,它是一个数组,每个元素包含 id、type、function.name、function.arguments。下面这段是结构示意,字段名和模型名取自官方响应格式,id 与参数值为示意内容:

{
  "id": "chatcmpl-6adb0d416a4a9c1d0fe639e3",
  "object": "chat.completion",
  "model": "kimi-k3.1-pro",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "",
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"city\": \"北京\"}"
            }
          },
          {
            "id": "call_def456",
            "type": "function",
            "function": {
              "name": "get_exchange_rate",
              "arguments": "{\"base\": \"CNY\", \"quote\": \"USD\"}"
            }
          }
        ]
      }
    }
  ]
}

两个容易忽略的点:

function.arguments 是字符串,不是对象。必须 json.loads 之后再用,否则会出现”看起来有两个参数、实际取不到值”的情况。

响应里还有 finish_reason 字段,官方非流式响应示例中它的值为 stop;工具调用场景下的取值官方摘录未给出,本文不依赖它的取值做分支判断,需要的话以官方页面为准。

另外,message 里还可能带有 reasoning_content。官方在结构化输出的说明里明确要求:只解析 content,不解析 reasoning_content。

五步走:从首轮到最终回答

第一步:定义 tools

每个工具要有完整的 name、description、parameters。官方请求示例里 function 还支持 strict: true,用于约束参数结构。如果只想让模型”必须调一个工具”,用法见 Kimi API tool_choice 三种写法;基础的 tools 定义和回传流程,可以先看 Kimi API function calling 怎么用。

第二步:首轮用 tool_choice=”required”

官方最小天气示例的首轮请求就是 tool_choice="required",作用是强制至少调用一个工具,避免模型直接聊天不调工具。

第三步:遍历 tool_calls,逐个执行

for tool_call in assistant_message.tool_calls or [] 逐条处理。本地执行顺序不影响回填正确性,但建议把结果先存进一个以 tool_call.id 为键的字典,回填时再按原顺序取,这样并发执行也不会串号。

第四步:用 tool_call_id 逐条回填

每条工具结果单独 append:

{"role": "tool", "tool_call_id": "call_abc123", "content": "{\"city\": \"北京\", \"weather\": \"晴\", \"temperature_c\": 24}"}

content 建议是 JSON 字符串,并加 ensure_ascii=False,中文不会变成转义序列,排查时肉眼可读。

第五步:第二次请求,拿最终回答

把历史(用户消息 + 完整 assistant message + 若干 tool 消息)一起发回去,模型据此生成最终答案。多轮场景的整体骨架见 Kimi API Agent 多轮 function calling 教程。

完整代码:一次返回两个调用

下面的脚本改自官方快速开始的最小 Agent Loop,把单工具扩成双工具,其余结构保持官方写法。代码出自官方文档示例,未在本站环境运行验证,run_tool 返回的是本地模拟数据,接真实数据源时替换即可。

import json
import os
from typing import Any

from openai import OpenAI

client = OpenAI(
    api_key=os.environ["MOONSHOT_API_KEY"],
    base_url="https://api.moonshot.cn/v1",
)

tools: list[dict[str, Any]] = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "查询指定城市的当前天气,参数为城市中文名",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "城市名,例如 北京"}
                },
                "required": ["city"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_exchange_rate",
            "description": "查询两种货币之间的当前汇率",
            "parameters": {
                "type": "object",
                "properties": {
                    "base": {"type": "string", "description": "基础货币代码,例如 CNY"},
                    "quote": {"type": "string", "description": "目标货币代码,例如 USD"},
                },
                "required": ["base", "quote"],
            },
        },
    },
]


def run_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
    # 本地模拟实现:真实项目里替换成自己的接口调用
    if name == "get_weather":
        return {"city": arguments["city"], "weather": "晴", "temperature_c": 24}
    if name == "get_exchange_rate":
        return {"base": arguments["base"], "quote": arguments["quote"], "rate": 7.12}
    raise ValueError(f"未知工具:{name}")


messages: list[Any] = [
    {
        "role": "user",
        "content": "北京今天天气怎么样?顺便告诉我 1 人民币大概能换多少美元。",
    }
]

first = client.chat.completions.create(
    model="kimi-k3.1-pro",
    messages=messages,
    tools=tools,
    tool_choice="required",
)

assistant_message = first.choices[0].message
messages.append(assistant_message)  # 关键:完整 assistant message 原样入历史

pending: list[tuple[str, dict[str, Any]]] = []
for tool_call in assistant_message.tool_calls or []:
    arguments = json.loads(tool_call.function.arguments)  # arguments 是字符串
    pending.append((tool_call.id, run_tool(tool_call.function.name, arguments)))

for tool_call_id, result in pending:
    messages.append(
        {
            "role": "tool",
            "tool_call_id": tool_call_id,
            "content": json.dumps(result, ensure_ascii=False),
        }
    )

final = client.chat.completions.create(
    model="kimi-k3.1-pro",
    messages=messages,
    tools=tools,
)
print(final.choices[0].message.content)

如果响应里只回来一个 tool_call,这段代码同样能跑,pending 长度为 1,回填一条即可,不需要写两套分支。

回填前跑一遍核对:id 集合必须相等

在发第二次请求之前,加一段几行的校验,比事后猜”为什么回答引用错了城市”便宜得多。官方摘录未规定 tool 消息必须与 tool_calls 数组顺序一致,tool_call_id 才是匹配键;下面只校验集合相等,并按原始顺序打印对照,方便人工核对。

def check_tool_pairs(assistant_message, tool_messages) -> None:
    expected = [tc.id for tc in (assistant_message.tool_calls or [])]
    got = [m.get("tool_call_id") for m in tool_messages]
    if sorted(expected) != sorted(got):
        raise RuntimeError(f"tool_call_id 不匹配:expected={expected} got={got}")
    for tc_id in expected:
        print("已回填", tc_id)
核对点容易写错的做法官方文档支持的做法
assistant message 入历史
只把 content 提出来当新消息发
原样把完整 assistant message 加入下一次请求
工具结果条数
两个结果拼成一段文本放一条消息
每个调用一条 role 为 tool 的消息
tool_call_id 来源
自己生成,或复制时串行
用响应中对应 tool_calls 元素的 id
arguments 处理
直接当 dict 取值
先 json.loads,它是字符串
tool 消息顺序
按本地执行完成顺序回填
顺序官方摘录未作规定,建议按返回顺序回填以便比对
首轮是否强制调用
不传 tool_choice,模型直接聊天
首轮用 tool_choice 为 required

并发执行时怎么保证不串号

官方文档没有规定工具必须串行执行,也没给出并发相关约束。工程上稳妥的做法是:并发跑,但结果用 tool_call.id 作键存起来,最后统一按 tool_calls 的原始顺序回填。

from concurrent.futures import ThreadPoolExecutor

results: dict[str, dict[str, Any]] = {}

def job(tc) -> tuple[str, dict[str, Any]]:
    args = json.loads(tc.function.arguments)
    return tc.id, run_tool(tc.function.name, args)

calls = list(assistant_message.tool_calls or [])
with ThreadPoolExecutor(max_workers=len(calls) or 1) as pool:
    for tc_id, value in pool.map(job, calls):
        results[tc_id] = value

for tc in calls:  # 回填顺序 = tool_calls 原始顺序
    messages.append(
        {
            "role": "tool",
            "tool_call_id": tc.id,
            "content": json.dumps(results[tc.id], ensure_ascii=False),
        }
    )

这是一段工程建议,不是官方规定的写法。判断标准只有一个:回填完成后,role: "tool" 消息的 id 集合与 tool_calls 完全一致。

常见问题与踩坑

只回传 content 导致第二轮”失忆”。 这是最常见的一种。模型看不到自己刚才发起过哪些调用、返回过什么,于是要么重复提问,要么凭空编答案。官方在”重要限制”条目里明确要求原样回传完整 assistant message。

tool_call_id 拼错或漏填。 回填时缺 tool_call_id、或者把两个 id 对调,模型会把 A 城市的数据当成 B 城市的结果写进最终回答。这种错误在输出里往往看不出来,因为句子本身是通顺的。

arguments 解析失败。 先打印原始字符串确认,再决定是补 tools 里的 description、还是启用 strict。参数为空的排查思路可以参考 千问 API function call arguments 为空怎么排查,思路是通用的:先看工具描述,再谈强制约束。

历史里混入多条 user 消息。 回填工具结果时不要再补一条”这是工具返回的数据”,那就是把结构化回填降级成了自然语言拼接,模型对不上 id。

流式场景。 官方流式响应示例展示的是 reasoning_content 和 content 两类增量的输出方式,以及最后 choices 为空数组、总用量位于顶层 usage 的统计块,没有展开 tool_calls 的增量拼接细节。要做流式工具调用,先对照官方流式输出章节确认字段拼接规则,再动手。

最终回答被截断。 如果最终内容不完整,先看 finish_reason,再检查 max_completion_tokens。官方”重要限制”写明:max_completion_tokens 默认 131072,最大可设置为 1048576。超出这个范围会报错还是静默截断,以官方页面为准。

多传了采样参数。 官方把 temperature=1.0、top_p=0.95、n=1、presence_penalty=0、frequency_penalty=0 列为固定值,并建议不要显式传入。自己传一套不一样的数值,行为不由你控制。

成本和上下文。 官方说明 K3.1 Pro 上下文长度为 1M token,计费不按上下文长度分段,所有用量按量付费,计费项包括缓存写入(区分 TTL 5min / TTL 1h 两档)、输入(区分缓存命中与未命中)和输出,具体单价以官方定价页为准。多工具调用的每一轮都会把完整历史再发一次,工具返回内容越长,重复计费的部分越大,长列表类结果建议裁剪字段再回填。缓存按组织(org)隔离,命中部分只收缓存读取费用,同一前缀在有效期内命中会按原 TTL 刷新。

FAQ

模型一次最多返回几个 tool_calls?

官方摘录没有给出数量上限,以官方页面为准。工程上不要假设”只会回一个”,代码里统一按数组处理,长度 1 和长度 5 走同一条路径。

两个工具调用可以并发执行吗?

官方文档未限制执行方式。并发执行本身没问题,风险在回填环节:结果必须按 tool_call_id 归位,不能按”谁先跑完谁先写”。用 id 作字典键是最省事的做法。

tool_call_id 需要自己生成吗?

不需要。用响应里 tool_calls 数组元素自带的 id,原值复制到对应 role: "tool" 消息的 tool_call_id 字段。自己生成的 id 模型不认识。

工具执行失败了,还能回填吗?

可以回填一条 role: "tool" 消息,在 content 里写明失败原因和已尝试的参数,让模型决定换参数重试还是直接向用户说明。官方摘录未规定失败结果的具体格式,字段结构保持和成功时一致即可,关键是 tool_call_id 不能丢。

为什么第二轮模型说”没有拿到数据”?

按概率排:一是 assistant message 没原样入历史;二是 tool 消息缺 tool_call_id;三是 id 复制时对错了;四是把结构化结果改写成了自然语言。按这个顺序各查一遍,通常能找到。

资料来源

  • Chat Completions API – Kimi API 开放平台(响应格式、tool_calls 结构、arguments 为字符串、finish_reason、流式输出字段、缓存与用量字段,核对日期:2026 年 11 月 23 日)
  • Kimi K3.1 Pro – Kimi API 开放平台(最小 Agent Loop、tool_choice 为 required、tool_call_id 回填写法、原样回传完整 assistant message、max_completion_tokens 与固定采样参数、1M 上下文与计费说明,核对日期:2026 年 11 月 23 日)