跳到正文
函数调用

函数调用

在请求中描述你的函数,模型会回复它想要发起的调用。由你的代码运行它们并把结果发回:API 返回工具调用,自己不运行任何工具。

POST https://api.shannon-ai.com/v1/chat/completions

本页的示例使用 /v1/chat/completions。同样的循环也适用于 /v1/responses 和 /v1/messages;各格式写法不同的地方,下文各节会分别给出这三种写法。

import json
from openai import OpenAI

client = OpenAI(api_key="YOUR_API_KEY", base_url="https://api.shannon-ai.com/v1")

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name, for example Paris"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            },
            "required": ["city"],
        },
    },
}]

def get_weather(city, unit="celsius"):
    # Your code: ask a weather service here.
    return {"city": city, "temperature": 18, "unit": unit, "conditions": "cloudy"}

messages = [{"role": "user", "content": "What is the weather in Paris right now?"}]
answer = None

for _ in range(5):  # the API sets no limit on rounds: set your own
    response = client.chat.completions.create(
        model="Kimi-K3-3BIT-REAP",
        messages=messages,
        tools=tools,
    )
    choice = response.choices[0]
    if choice.finish_reason != "tool_calls":
        answer = choice.message.content
        break

    messages.append(choice.message)  # the assistant turn with its tool_calls
    for call in choice.message.tool_calls:
        args = json.loads(call.function.arguments)  # arguments is a JSON string
        result = get_weather(**args)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })

print(answer)

第一个回复并不回答问题,而是请求一次调用:

200 JSON
{
  "id": "chatcmpl-5b0c1d8e7f6a4b3c9d2e1f0a8b7c6d5e",
  "object": "chat.completion",
  "created": 1791590400,
  "model": "Kimi-K3-3BIT-REAP",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "reasoning_content": "The user asks for the current weather in Paris. I should call get_weather.",
        "tool_calls": [
          {
            "id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"city\":\"Paris\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 312,
    "completion_tokens": 58,
    "total_tokens": 370,
    "prompt_tokens_details": {"cached_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 31}
  }
}

在你发送结果之后,下一个回复是普通答案:message.content 包含文本,finish_reason 为 stop。

循环,逐步说明

步骤 执行者 发生什么
1 你 发送 messages 以及 tools(模型可以请求的函数列表)。
2 模型 回复带有 tool_calls 和 finish_reason: "tool_calls"。每个调用都指明一个函数并给出其参数。
3 你 解析每个调用的 arguments,并运行你的函数。
4 你 把 assistant 消息和每个调用对应的一条 tool 消息追加到 messages,然后用相同的 tools 再次发送请求。
5 模型 模型用文本作答并带 finish_reason: "stop",或请求更多调用。若是后者,请回到步骤 3。

一个请求就是模型的一轮。API 在请求之间不保存对话,也不规定轮数:由你的代码保存 messages 并决定何时停止。

定义工具

tools 是数组,每个函数一个条目。目录中的每个模型都接受它;GET /v1/models 对每个 id 都报告 capabilities.tools: true。

字段 类型 说明
type string 始终为 function。
function.name string 模型请求该函数时使用的名称。必填。
function.description string 该函数的作用,用通俗语言描述。
function.parameters object 参数,格式为顶层带 type: "object" 的 JSON Schema。见下文的 Schema 关键字。

每个端点对工具有自己的写法。请发送与你所调用端点相符的那一种:

{
  "type": "function",
  "function": {
    "name": "get_weather",
    "description": "Get the current weather for a city.",
    "parameters": {
      "type": "object",
      "properties": {
        "city": {
          "type": "string",
          "description": "City name, for example Paris"
        },
        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
      },
      "required": ["city"]
    }
  }
}

tool_choice

tool_choice 说明模型是可以还是必须调用工具。它只与 tools 一起读取。

值 说明 适用模型
"auto" 由模型决定是用文本作答还是调用工具。这是默认值。 所有模型
"required" 回复至少调用一个工具。 托管开源权重模型
{"type": "function", "function": {"name": "get_weather"}} 回复调用该函数。名称必须是 tools 中的函数之一。对其他函数的调用不会出现在回复中。 托管开源权重模型

Shannon 模型(shannon-*)在每个请求中自行决定,就像 auto 一样。

使用 required 或指定函数时,请先读取 finish_reason,再读取 tool_calls。当模型没有产生调用时,回复是文本答案,且 finish_reason: "stop"。

含义 /v1/chat/completions /v1/responses /v1/messages
由模型决定 "auto" "auto" {"type": "auto"}
至少调用一个工具 "required" "required" {"type": "any"}
调用一个指定的函数 {"type": "function", "function": {"name": "get_weather"}} {"type": "function", "name": "get_weather"} {"type": "tool", "name": "get_weather"}

为兼容而接受:tool_choice: "none" 和 parallel_tool_calls。如果某一轮不需要工具调用,请在不带 tools 的情况下发送请求。

回复中的工具调用

字段 类型 说明
finish_reason string 当回复至少带有一个调用时为 tool_calls。
message.tool_calls array 每个调用一个条目。仅当模型请求调用时才会出现该字段。
tool_calls[].id string call_ 后接 32 位十六进制字符。请将其作为 tool_call_id 与结果一起发回。
tool_calls[].type string 始终为 function。
tool_calls[].function.name string 要运行的函数。
tool_calls[].function.arguments string 参数,格式为 JSON 字符串,没有参数时为 "{}"。使用前请先解析。
message.content string | null 当回复只包含调用时为 null。托管开源权重模型可以在调用之外同时返回文本;Shannon 模型则返回 null。

各格式中的同一个调用。在 /v1/responses 上,它是 output 中的 function_call 项,arguments 为 JSON 字符串。在 /v1/messages 上,它是 tool_use 内容块,其 input 是 JSON 对象,id 以 toolu_ 开头,且 stop_reason 为 tool_use。

{
  "finish_reason": "tool_calls",
  "message": {
    "role": "assistant",
    "content": null,
    "tool_calls": [
      {
        "id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
        "type": "function",
        "function": {
          "name": "get_weather",
          "arguments": "{\"city\":\"Paris\"}"
        }
      }
    ]
  }
}

一轮中的多个调用

一个回复可以带有多个调用。请运行全部调用,并在下一个请求中为每个调用发送一个结果,各带自己的 tool_call_id。

托管开源权重模型对每个不同的调用只返回一次:名称和参数都相同的两个调用会合并为一个。

流式工具调用

使用 stream: true 时,调用会一次整体到达:数据块包含完整的 arguments 字符串,因此没有需要拼接的片段。index 从 0 开始对该轮的调用计数。

data:一个数据块,已格式化
{
  "id": "chatcmpl-5b0c1d8e7f6a4b3c9d2e1f0a8b7c6d5e",
  "object": "chat.completion.chunk",
  "created": 1791590400,
  "model": "Kimi-K3-3BIT-REAP",
  "choices": [
    {
      "index": 0,
      "delta": {
        "tool_calls": [
          {
            "index": 0,
            "id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"city\":\"Paris\"}"
            }
          }
        ]
      },
      "finish_reason": null
    }
  ]
}
端点 到达的内容
/v1/chat/completions 每个调用一个 chat.completion.chunk,调用位于 delta.tool_calls[0]。最后一个数据块带有 finish_reason: "tool_calls" 和 usage。
/v1/responses 每个调用:response.output_item.added(arguments 为空的 function_call 项)、response.function_call_arguments.delta(完整字符串)、response.function_call_arguments.done、response.output_item.done。
/v1/messages 每个调用:content_block_start(input 为空的 tool_use 块)、一个 content_block_delta(其 input_json_delta.partial_json 是完整的参数文本)、content_block_stop。随后 message_delta 带有 stop_reason: "tool_use"。

在 shannon-1.6-lite、shannon-1.6-pro、shannon-2-lite、shannon-2-pro 和 shannon-coder-1 上,带有 tools 的流式请求会在该轮结束时,以一个 content delta 送出答案文本。 流式

发回结果

第二个请求重复对话,并添加两样东西:请求调用的 assistant 轮次,以及每个调用对应的一个结果。

{
  "messages": [
    {"role": "user", "content": "What is the weather in Paris right now?"},
    {
      "role": "assistant",
      "content": null,
      "tool_calls": [
        {
          "id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
          "type": "function",
          "function": {
            "name": "get_weather",
            "arguments": "{\"city\":\"Paris\"}"
          }
        }
      ]
    },
    {
      "role": "tool",
      "tool_call_id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
      "content": "{\"city\":\"Paris\",\"temperature\":18,\"unit\":\"celsius\",\"conditions\":\"cloudy\"}"
    }
  ]
}
  • 请在结果之前,把 assistant 轮次按收到的原样发回。每个结果通过 id 与其调用匹配:/v1/chat/completions 上是 tool_call_id,/v1/responses 上是 call_id,/v1/messages 上是 tool_use_id。
  • 结果是文本。请把对象序列化为 JSON 字符串,放入 content(在 /v1/responses 上是 output)。在 /v1/messages 上,tool_result 块的 content 是字符串或文本块列表。
  • 在 assistant 轮次中,function.arguments 保持为 JSON 字符串,与收到时完全一致。
  • 对话可以以工具结果结尾。无需新的用户消息:模型会从结果继续。
  • 当你的函数失败时,请把失败信息作为结果文本发送。模型随后可以报告它,或请求另一次调用。

Schema 关键字

parameters(在 /v1/messages 上是 input_schema)是 JSON Schema。Shannon 3 系列(shannon-3、shannon-3-pro、shannon-3.1、shannon-3.1-pro)和托管开源权重模型会按你发送的原样接收它。

shannon-1.6-lite、shannon-1.6-pro、shannon-2-lite、shannon-2-pro 和 shannon-coder-1 在全部三个端点上接收的是这个子集:

处理方式 关键字
按发送的原样读取 下面各行未提及的所有关键字,例如 type、properties、required、items、enum、description、minimum、maximum、anyOf 和 allOf,适用于 schema 的每一层。
format 对取值 int32、int64、float、double、byte、date、date-time 和 enum 予以读取。
oneOf 按 anyOf 读取。
不属于这些模型收到的 schema $schema, $id, $ref, $defs, $comment, definitions, additionalProperties, unevaluatedProperties, patternProperties, propertyNames, examples, default, title, const, not, if, then, else, contains, minContains, maxContains, dependentRequired, dependentSchemas, dependencies, readOnly, writeOnly, deprecated, contentEncoding, contentMediaType, contentSchema, multipleOf, uniqueItems;当为数字时的 exclusiveMinimum 和 exclusiveMaximum;以及 format 的其他取值。

行为与限制

  • API 不设工具数量上限,也不设轮数上限。
  • 请求体最大可达 32 MiB,且对话连同其结果必须能放进模型的上下文窗口。
  • 当请求带有 tools 时,shannon-1.6-lite、shannon-1.6-pro、shannon-2-lite 和 shannon-2-pro 的默认 temperature 为 0.2。发送 temperature 可设置其他值。
  • 每一轮都是一个独立的请求:它会像其他请求一样从你的余额中扣费,并计入限流保护。 限制与余额

错误

工具调用是状态码为 200 的正常回复。以下错误涉及请求本身:

状态码 类型 消息 何时
400 invalid_request_error unknown model: <id> model 不是已发布列表中的 id。
422 invalid_request_error Failed to deserialize the JSON body into the target type: … tools 不是数组,或其他字段的 JSON 类型有误。
413 invalid_request_error Failed to buffer the request body: … 请求体大于 32 MiB。该错误带有 code: "request_too_large"。

参数由模型写出。运行函数之前,请像检查任何外部输入一样,对照你的 schema 检查这些参数。

认证、余额和服务器错误与其他任何请求相同。 错误处理