Kimi K2 工具调用怎么写?用 OpenAI 兼容格式让模型调用函数

Kimi K2 工具调用怎么写?用 OpenAI 兼容格式让模型调用函数
本文目录(8 节)

Kimi K2 工具调用沿用 OpenAI 兼容的 tools 写法:你在请求里传函数描述,模型决定要不要调用;它返回 finish_reason="tool_calls" 时,你执行函数,把结果以 role="tool" 追加回 messages,再请求一次,直到 finish_reason 不再是 tool_calls。

本文依据官方资料整理,本站未实测。文中代码出自官方仓库文档,未在本站环境运行验证。

读完这篇,你应该能照着官方示例写出一个完整的调用循环,知道流式场景该怎么拼接参数,也清楚服务端没有解析器时的退路,以及几处官方材料自己就不一致的地方该怎么处理。

先弄清楚流程:谁在做什么

官方工具调用指南把一次工具调用拆成四步:

  1. 你把函数描述传给 Kimi K2。
  2. 模型决定调用函数,把调用所需信息返回给你。
  3. 由你执行函数,收集结果,再传回模型。
  4. 模型基于结果继续生成,直到认为信息足够,给出最终回答。

要点:模型不会替你执行函数,它只负责“决定调用谁、传什么参数”。执行和回填是你的代码的职责。这也意味着函数的安全边界由你把控:模型给出的参数只是它生成的文本,落到数据库、文件系统或外部接口之前,应当先做校验。

另外,官方指南提到,要启用工具调用,自己部署服务时可能需要在启动时设置工具调用解析器(tool call parser)相关选项,细节见其部署指南。如果你用的是官方 API,官方仓库 README 写明可在 https://platform.moonshot.ai 使用 Kimi K2 的 API,并提供 OpenAI/Anthropic 兼容接口。

README 同时说明,推荐的推理引擎包括 vLLM、SGLang、KTransformers 和 TensorRT-LLM,部署示例见其模型部署指南。模型权重以 block-fp8 格式存放在 Hugging Face。这些属于自部署读者关心的内容,只用 API 的读者可以跳过。

第一步:写 tools 描述

以官方示例的天气函数为例。先写函数本体,再写结构化描述,最后建一个“名字到函数”的映射表,方便后面按名字调用:

def get_weather(city):
    return {"weather": "Sunny"}

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get weather information. Call this tool when the user needs to get weather information",
        "parameters": {
            "type": "object",
            "required": ["city"],
            "properties": {
                "city": {
                    "type": "string",
                    "description": "City name",
                }
            }
        }
    }
}]

tool_map = {"get_weather": get_weather}

几个写法上的判断:

  • description 要写清楚“什么时候该调用”。官方示例里就写了“当用户需要天气信息时调用”,模型靠这句话判断时机。
  • parameters 是 JSON Schema 结构,required 列出必填字段,每个参数写 type 和 description。
  • name 必须和 tool_map 的键一致,否则后面查表会出错。
  • 函数数量多时,每个函数的描述要互相区分开,避免模型分不清该调哪一个。这是写法建议,官方摘录没有展开讨论。

第二步:发请求并循环处理 tool_calls

官方示例使用 openai.OpenAI 客户端,模型名为 moonshotai/Kimi-K2-Instruct,tool_choice 设为 "auto",让模型自己决定是否调用:

import json
from openai import OpenAI

model_name = 'moonshotai/Kimi-K2-Instruct'
client = OpenAI(base_url=endpoint, api_key='xxx')

messages = [
    {"role": "user", "content": "What's the weather like in Beijing today? Let's check using the tool."}
]
finish_reason = None
while finish_reason is None or finish_reason == "tool_calls":
    completion = client.chat.completions.create(
        model=model_name,
        messages=messages,
        temperature=0.3,
        tools=tools,
        tool_choice="auto",
    )
    choice = completion.choices[0]
    finish_reason = choice.finish_reason
    if finish_reason == "tool_calls":
        messages.append(choice.message)
        for tool_call in choice.message.tool_calls:
            tool_call_name = tool_call.function.name
            tool_call_arguments = json.loads(tool_call.function.arguments)
            tool_function = tool_map[tool_call_name]
            tool_result = tool_function(tool_call_arguments)
            print("tool_result", tool_result)
            messages.append({
                "role": "tool",
                "tool_call_id": tool_call.id,
                "name": tool_call_name,
                "content": json.dumps(tool_result),
            })
print(choice.message.content)

这里的 endpoint 在摘录里没有给出具体值,需要换成你自己的服务地址;api_key='xxx' 也只是官方示例里的写法,请换成你实际使用的密钥,并且不要把真实密钥写进代码仓库。base_url 怎么填可以参考站内的大模型 API base_url 对照表,用 Node.js 的读者可看Kimi API Node.js 第一次调用。

回填结果的四个关键点

  • 先 messages.append(choice.message),把模型这条带 tool_calls 的消息原样放回历史,再追加工具结果。
  • 工具结果的 role 必须是 "tool"。
  • tool_call_id 要与模型返回的 tool_call.id 对应;一次返回多个调用时,每个都要各自回填。
  • content 是字符串,所以官方用 json.dumps(tool_result) 序列化。

温度怎么设

两处官方材料的数字不一致:README 的对话示例用 temperature=0.6,并注明 Kimi-K2-Instruct 的推荐温度是 0.6;工具调用指南的示例里用的是 0.3。摘录没有解释差异,建议先按 README 的推荐值起步,再根据你的任务稳定性调整,具体以官方页面为准。

另外,README 还提到 Anthropic 兼容接口会按 real_temperature = request_temperature * 0.6 映射温度,如果你走那条接口,要把这个换算考虑进去。

第三步:流式输出下的工具调用

流式时,工具调用信息被拆成多个 chunk,需要你按 index 拼起来,拼完整才能 json.loads。官方做法是维护一个 tool_calls 列表,把 id、function.name、function.arguments 分别累加:

messages = [
    {"role": "user", "content": "What's the weather like in Beijing today? Let's check using the tool."}
]
finish_reason = None
msg = ''
while finish_reason is None or finish_reason == "tool_calls":
    completion = client.chat.completions.create(
        model=model_name,
        messages=messages,
        temperature=0.3,
        tools=tools,
        tool_choice="auto",
        stream=True
    )
    tool_calls = []
    for chunk in completion:
        delta = chunk.choices[0].delta
        if delta.content:
            msg += delta.content
        if delta.tool_calls:
            for tool_call_chunk in delta.tool_calls:
                if tool_call_chunk.index is not None:
                    while len(tool_calls) <= tool_call_chunk.index:
                        tool_calls.append({
                            "id": "",
                            "type": "function",
                            "function": {"name": "", "arguments": ""}
                        })
                    tc = tool_calls[tool_call_chunk.index]
                    if tool_call_chunk.id:
                        tc["id"] += tool_call_chunk.id
                    if tool_call_chunk.function.name:
                        tc["function"]["name"] += tool_call_chunk.function.name
                    if tool_call_chunk.function.arguments:
                        tc["function"]["arguments"] += tool_call_chunk.function.arguments
        finish_reason = chunk.choices[0].finish_reason
        if finish_reason == "tool_calls":
            for tool_call in tool_calls:
                tool_call_name = tool_call['function']['name']
                tool_call_arguments = json.loads(tool_call['function']['arguments'])
                tool_function = tool_map[tool_call_name]
                tool_result = tool_function(tool_call_arguments)
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call['id'],
                    "name": tool_call_name,
                    "content": json.dumps(tool_result),
                })
            # The text generated by the tool call is not the final version, reset msg
            msg = ''
print(msg)

注意最后那句:工具调用阶段产生的文本不是最终答案,官方在触发调用后把 msg 清空。

还有一处细节值得留意:官方这段流式示例在触发工具调用时,只追加了 role="tool" 的结果消息,没有像非流式那样先追加带 tool_calls 的 assistant 消息。摘录没有说明原因。如果你在实际接入时遇到服务端对消息顺序报错,可以参考非流式写法,把拼好的 assistant 消息(含 tool_calls)先放进历史,再追加工具结果,具体要求以所用服务的官方文档为准。

第四步:服务不带解析器时,手动解析

如果你用的服务没有提供工具调用解析器,官方给了手动解析的办法:直接请求 /completions 接口,用分词器的 apply_chat_template 把 tools 渲染进提示词,再从原始输出里提取调用。

模型输出的标记规则(出自官方指南):

标记作用
工具调用区块的开始与结束标记
包住整个工具调用区块
单个调用的开始与结束标记
包住单个工具调用
参数开始标记
分隔工具 ID 与参数

这些标记的具体字面写法见官方指南原文和下面代码里的正则表达式,它们都是带竖线的特殊标记。工具 ID 的格式是 functions.{func_name}:{idx},函数名就从这里解析。官方给的简单实现如下:

def extract_tool_call_info(tool_call_rsp: str):
    if '<|tool_calls_section_begin|>' not in tool_call_rsp:
        return []
    import re
    pattern = r"<\|tool_calls_section_begin\|>(.*?)<\|tool_calls_section_end\|>"
    tool_calls_sections = re.findall(pattern, tool_call_rsp, re.DOTALL)

    func_call_pattern = r"<\|tool_call_begin\|>\s*(?P<tool_call_id>[\w\.]+:\d+)\s*<\|tool_call_argument_begin\|>\s*(?P<function_arguments>.*?)\s*<\|tool_call_end\|>"
    tool_calls = []
    for match in re.findall(func_call_pattern, tool_calls_sections[0], re.DOTALL):
        function_id, function_args = match
        # function_id: functions.get_weather:0
        function_name = function_id.split('.')[1].split(':')[0]
        tool_calls.append({
            "id": function_id,
            "type": "function",
            "function": {"name": function_name, "arguments": function_args}
        })
    return tool_calls

官方称这只是“简单实现”。它只取了第一个区块 tool_calls_sections[0],且函数名用 split('.')[1] 取值,遇到函数名本身含点号的情况可能不适用,生产环境建议自己加测试。手动方式还需要 transformers 的 AutoTokenizer,并以 trust_remote_code=True 加载分词器,这一项会执行远程代码,请先确认来源可信。

手动模式的循环逻辑和前面一致:请求、提取调用、执行、把 role="tool" 的结果追加进 messages、再次渲染提示词请求,直到输出里不再包含工具调用,才把原始输出当作最终回答。官方示例里 max_tokens 设为 512,你可以按任务调整,摘录没有给出推荐值。

常见问题与踩坑

  • 循环停不下来或提前结束:官方在代码注释里提醒,工具调用结束时的 finish_reason 在不同推理引擎上可能不同,判断条件需要按你用的引擎调整。另外建议自己加一个最大轮数限制,避免模型反复调用造成死循环,这是工程上的保险做法,官方摘录没有提及。
  • 参数 JSON 解析失败:流式场景下 arguments 是分片到达的,必须拼完整再 json.loads,不要在每个 chunk 上解析。
  • 函数传参方式:官方指南示例写的是 tool_function(tool_call_arguments)(传入整个字典),而 README 的版本写的是 tool_function(**tool_call_arguments)(解包为关键字参数)。如果你的函数签名是 get_weather(city),用解包方式更直观,注意两者要和函数定义配套,否则会出现参数类型错误。
  • 自己部署却没有工具调用:多半是没配解析器。回到官方部署指南核对启动选项,或改用上面的手动解析。
  • README 注明的前提:它的端到端流程要求推理引擎支持 Kimi-K2 原生的工具解析逻辑。
  • 模型选择:README 说明 Kimi-K2-Instruct 是后训练模型,适合通用对话和 Agent 场景,且是不带长思考的“反射型”模型;Base 版更适合研究者微调。做工具调用请用 Instruct。
  • 上下文长度:README 的模型概要写明上下文长度为 128K。工具描述和多轮结果都会占用上下文,描述写得过长或结果回填过大时要留意。

FAQ

Kimi K2 支持 OpenAI SDK 吗?

官方 README 表示其 API 提供 OpenAI/Anthropic 兼容接口,工具调用示例用的就是 openai.OpenAI 客户端。

tool_choice 该怎么填?

官方示例用 "auto",由模型自己决定是否调用以及怎么调用。其他取值摘录未涉及,以官方页面为准。

工具结果怎么传回去?

追加一条 role="tool" 的消息,带上 tool_call_id、name 和字符串化的 content,然后再次请求。

一次返回多个工具调用怎么办?

遍历 tool_calls,逐个执行并各自回填一条 tool 消息,再发下一轮请求。

接 Cursor、Cline 之类工具时需要自己写这些吗?

一般不用,这些客户端自己处理工具循环,你只需填兼容地址和模型名,可参考站内的Cline 接 Kimi 设置步骤,或Cursor 自定义 OpenAI 兼容地址的填写步骤。

资料来源

核对日期:2026 年 11 月 26 日。价格、限额、模型名在各平台的具体写法,官方摘录未给出具体数字,以官方页面为准。