Skip to content

Kimi API 工具调用(Tool Use)兼容 OpenAI function_calling 格式,工具通过 JSON Schema 描述参数,模型自动决定调用时机。本文是工具调用的 API 参数参考,实战流程参考 工具调用完整指南

Kimi API 工具调用(Tool Use)参考

tools 字段格式

json
{
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "获取指定城市的当前天气",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string",
              "description": "城市名称,如"北京""
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"],
              "description": "温度单位"
            }
          },
          "required": ["city"]
        }
      }
    }
  ]
}
字段类型必填说明
typestring"function""builtin_function"(内置工具如 $web_search
function.namestring工具名称,只能含字母、数字、下划线,最长 64 字符
function.descriptionstring推荐帮助模型决定何时调用该工具
function.parametersobject推荐基于 JSON Schema 的参数定义

tool_choice 参数

行为
"auto"(默认)模型自动决定是否调用工具
"none"禁止调用任何工具
{"type": "function", "function": {"name": "xxx"}}强制调用指定工具

thinking 模式限制:启用 thinking 时,tool_choice 只支持 "auto""none",不支持强制指定工具。


工具调用响应处理

python
from openai import OpenAI
import json

client = OpenAI(
    api_key="$MOONSHOT_API_KEY",
    base_url="https://api.moonshot.cn/v1",
)

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="kimi-k2.6",
    messages=messages,
    tools=tools,
)

choice = response.choices[0]
if choice.finish_reason == "tool_calls":
    messages.append(choice.message)
    
    for tool_call in choice.message.tool_calls:
        args = json.loads(tool_call.function.arguments)
        result = {"temperature": "22°C", "condition": "晴天"}
        
        messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": json.dumps(result, ensure_ascii=False),
        })

    # 再次请求获取最终回答
    final_response = client.chat.completions.create(
        model="kimi-k2.6",
        messages=messages,
        tools=tools,
    )
    print(final_response.choices[0].message.content)

限制

  • 最多同时定义 128 个工具
  • thinking 模式下 tool_choice 只支持 auto / none
  • 每轮工具调用后必须回复所有 tool_calls(不能只回复部分)
  • thinking 模式下每轮必须保留 reasoning_content 传入下一轮

常见问题

Q: 工具定义放在 tools 还是 system prompt 里有什么区别?

A: 通过 tools 字段定义的工具由模型原生处理,格式严格、解析可靠;在 system prompt 中描述工具是软约束,解析质量取决于 prompt 质量。正式场景应使用 tools 字段。

Q: 工具调用后模型一定会使用工具结果吗?

A: 是的,在工具结果被添加到 messages 后,模型会基于结果生成回答。如果工具返回错误或空结果,模型会根据上下文决定如何处理(通常会说明无法获取数据)。

Q: 和 OpenAI function_calling 的差异?

A: 接口格式完全一致,可以直接复用 OpenAI 的工具定义代码。主要差异在于 thinking 模式时的 tool_choice 限制,以及 $web_search 等 Kimi 独有的 builtin_function 类型工具。