跳到正文
老马Chat laomachat.com

Function Calling

模型只返回函数调用;函数始终由你的程序执行。

Grok 4.20 Multi-Agent 的客户端工具调用还受上游 Beta 权限限制。非流式请求缺少工具权限时返回 HTTP 400,错误码为 model_tool_access_required。流式请求可能先返回 HTTP 200,再通过流内错误事件报告失败;客户端须检查错误事件和最终状态,不能仅凭 HTTP 200 判断调用成功。反复重试不能获得权限。

仅设置 tool_choice=none 不保证避开工具权限检查;如需纯文本调用,请移除 tools 及相关工具调用参数,或选择具备相应权限的模型。

function_calling.pypython
import json
import os
from getpass import getpass
from openai import OpenAI

api_key = os.environ.get("LAOMACHAT_API_KEY") or getpass("LaomaChat API Key: ")
client = OpenAI(api_key=api_key, base_url="https://api.laomachat.com/v1", timeout=300.0, max_retries=0)

def get_weather(city: str) -> dict:
    # 这里替换为你自己的业务函数;函数只在客户端执行。
    return {"city": city, "temperature_c": 18, "condition": "sunny"}

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
            "additionalProperties": False,
        },
        "strict": True,
    },
}]

messages = [{"role": "user", "content": "温哥华今天天气怎么样?"}]
first = client.chat.completions.create(
    model="claude-sonnet-4.6",
    messages=messages,
    tools=tools,
    tool_choice="required",
)
assistant = first.choices[0].message
messages.append({
    "role": "assistant",
    "content": assistant.content,
    "tool_calls": [
        {
            "id": call.id,
            "type": "function",
            "function": {
                "name": call.function.name,
                "arguments": call.function.arguments,
            },
        }
        for call in assistant.tool_calls or []
    ],
})

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

final = client.chat.completions.create(
    model="claude-sonnet-4.6",
    messages=messages,
    tools=tools,
)
print(final.choices[0].message.content)
工具由客户端执行

Chat Completions 使用 type=function;Messages 使用 Anthropic 客户端工具定义及 tool_use / tool_result。Responses 支持客户端 function,GPT 原生 Responses 另支持 custom 工具及一层 namespace。Chat 另兼容下方参数参考所列的 Anthropic 风格工具转换;这不表示不同协议的工具结构可以任意混用。

网关不执行工具。Web Search、File Search、MCP、Shell、Computer、Code Interpreter 等托管服务端工具不在支持范围内;客户端自己执行的函数或本地工具不属于这些托管能力。