智枢网关NEXUSGATE
功能特性

函数调用(Function Calling)

让模型调用你定义的工具,获取外部数据或执行操作

函数调用让模型能够根据对话内容,决定是否调用你预先定义的工具,并生成结构化的调用参数。你的程序执行工具后,把结果回传给模型,由模型给出最终回答。

适用模型

在模型详情页的"模型能力"中查看是否支持 工具调用,例如 gpt-5.5、claude-sonnet-5、qwen3.7-plus。

示例

完整流程分两轮:第一轮模型返回 tool_calls,第二轮把工具结果以 role: "tool" 回传。

import json
from openai import OpenAI

client = OpenAI(api_key="YOUR_API_KEY", base_url="https://netnexus.top/api/v1")

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "查询指定城市的实时天气",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string", "description": "城市名,如 北京"}},
                "required": ["city"],
            },
        },
    }
]
messages = [{"role": "user", "content": "北京今天天气怎么样?"}]

first = client.chat.completions.create(model="gpt-5.5", messages=messages, tools=tools)
msg = first.choices[0].message
messages.append(msg)

for call in msg.tool_calls or []:
    args = json.loads(call.function.arguments)
    result = {"city": args["city"], "weather": "晴", "temperature": "26°C"}  # 这里调用你自己的天气服务
    messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result, ensure_ascii=False)})

final = client.chat.completions.create(model="gpt-5.5", messages=messages, tools=tools)
print(final.choices[0].message.content)

注意事项

  • 工具的 description 和参数说明写得越清楚,模型越能准确判断何时调用。
  • 模型生成的参数需要在你的程序中校验后再执行,尤其是涉及写操作的工具。
  • 通过 tool_choice 可控制调用策略:auto(默认,由模型决定)、none(不调用)等,具体支持以模型为准。

本页目录

联系商务

为您的企业定制 AI 接入方案

微信同号,在微信中搜索手机号即可添加