FC 函数调用
函数调用(Function Calling)让模型在需要时请求执行你定义的函数,并基于函数结果继续回答。
4ALL API 上 GPT、Claude、Gemini 系列都支持标准的 OpenAI tools 协议,写一套代码即可跨模型使用。
基本流程
- 请求中用
tools声明函数签名; - 模型返回
finish_reason: "tool_calls"与函数名、JSON 参数; - 你执行函数,把结果作为
role: "tool"消息回传; - 模型基于结果给出最终回答。
示例
tools = [{ "type": "function", "function": { "name": "get_weather", "description": "查询指定城市当前天气", "parameters": { "type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"], }, },}]
resp = client.chat.completions.create( model="gpt-5.5", messages=messages, tools=tools)call = resp.choices[0].message.tool_calls[0]# 执行函数后回传:messages.append(resp.choices[0].message)messages.append({ "role": "tool", "tool_call_id": call.id, "content": '{"temp": 31, "condition": "sunny"}',})final = client.chat.completions.create(model="gpt-5.5", messages=messages, tools=tools)注意事项
- 参数是模型生成的 JSON 字符串,务必校验后再执行,不要直接拼进命令或 SQL;
- 模型可能一次返回多个
tool_calls,逐个执行并按tool_call_id对应回传; tool_choice: "required"可强制调用,"none"可禁用;- 流式模式下函数参数按增量下发,需拼接完整后再解析,见流式输出。