Function Calling
大模型无法访问实时数据和外部系统。Function Calling 允许模型调用外部工具(API、数据库、自定义函数等),获取信息或执行操作,突破模型自身能力的限制。
工作原理
Function Calling 通过应用程序与大模型之间的多步骤交互实现:
-
发起第一次模型调用:应用程序向大模型发送用户问题和可用工具清单。
-
接收模型的工具调用指令(工具名称与入参):若模型判断需要调用外部工具,返回 JSON 格式的指令,指定函数名称与入参。若模型判断无需调用工具,会返回自然语言格式的回复。
-
在应用端运行工具:应用程序执行指定工具,获取输出结果。
-
发起第二次模型调用:将工具输出结果添加到消息数组(
messages),再次调用模型。 -
接收来自模型的最终响应:模型综合工具输出与用户问题,生成自然语言回复。
工作流程示意图:
支持的模型
- Unisound 系列:
Unisound U2 - DeepSeek 系列:
DeepSeek-V4-Flash,DeepSeek-V4-Pro - Kimi 系列:
kimi-k2.5,kimi-k2.6 - GLM 系列:
glm-5.2,glm-5.1,glm-5 - MiniMax 系列:
MiniMax-M2.5 - Qwen(通义千问)系列:
qwen3.7-plus,qwen3.7-max-2026-06-08,qwen3.6-plus,qwen3.6-flash,qwen3.6-35b-a3b
调用示例
如果你的项目已经接入 OpenAI SDK,把 base_url 和 model 换成下方的值即可直接复用,无需迁移到新 SDK。
python
# 首次使用前请先安装 OpenAI SDK:`pip install openai`
from openai import OpenAI
import json
import random
# 初始化客户端
client = OpenAI(
base_url="https://maas-api.unisound.com/v1",
api_key="<API_KEY>",
)
# 模拟用户问题
USER_QUESTION = "北京天气咋样"
# 定义工具列表
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "当你想查询指定城市的天气时非常有用。",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市或县区,比如北京市、杭州市、余杭区等。",
}
},
"required": ["location"],
},
},
},
]
# 模拟天气查询工具
def get_current_weather(arguments):
weather_conditions = ["晴天", "多云", "雨天"]
random_weather = random.choice(weather_conditions)
location = arguments["location"]
return f"{location}今天是{random_weather}。"
# 封装模型响应函数
def get_response(messages):
completion = client.chat.completions.create(
model="qwen3.6-plus",
extra_body={"enable_thinking": False},
messages=messages,
tools=tools,
)
return completion
messages = [{"role": "user", "content": USER_QUESTION}]
response = get_response(messages)
assistant_output = response.choices[0].message
if assistant_output.content is None:
assistant_output.content = ""
messages.append(assistant_output)
# 如果不需要调用工具,直接输出内容
if assistant_output.tool_calls is None:
print(f"无需调用天气查询工具,直接回复:{assistant_output.content}")
else:
# 进入工具调用循环
while assistant_output.tool_calls is not None:
tool_call = assistant_output.tool_calls[0]
tool_call_id = tool_call.id
func_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
print(f"正在调用工具 [{func_name}],参数:{arguments}")
# 执行工具
tool_result = get_current_weather(arguments)
# 构造工具返回信息
tool_message = {
"role": "tool",
"tool_call_id": tool_call_id,
"content": tool_result,
}
print(f"工具返回:{tool_message['content']}")
messages.append(tool_message)
# 再次调用模型,获取总结后的自然语言回复
response = get_response(messages)
assistant_output = response.choices[0].message
if assistant_output.content is None:
assistant_output.content = ""
messages.append(assistant_output)
print(f"助手最终回复:{assistant_output.content}")
返回结果
正在调用工具 [get_current_weather],参数:{'location': '北京'}
工具返回:北京今天是多云。
助手最终回复:北京今天是多云的天气。
