工具调用
工具调用是一种让大模型与外部系统交互的机制,使模型能够调用外部工具来扩展自身能力,突破纯文本生成的局限。
1. 支持的模型
- GLM-5.1
- GLM-5
- GLM-4.7
- MiniMax-M2.5
- MiniMax-M2.1
2. 使用方法
2.1 通过 OpenAI 库请求
from openai import OpenAI
import json
client = OpenAI(base_url="https://api.magikcloud.cn/v1/chat/completions", api_key="${API_KEY}") # 替换为你的 API Key
# 定义工具:天气查询
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}}
}
}]
2.2 通过 REST API 添加 tools 请求参数
{
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}}
}
}
]
}
3. 工具调用示例
from openai import OpenAI
import json
client = OpenAI(base_url="https://api.magikcloud.cn/v1/chat/completions", api_key="${API_KEY}") # 替换为你的 API Key
# 定义工具
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}}
}
}]
messages = [{"role": "user", "content": "北京天气怎么样?"}]
# 第一次调用,模型返回工具调用请求
resp = client.chat.completions.create(
model="${ENDPOINT}", # 替换为你的接入点ID
messages=messages,
tools=tools,
tool_choice="auto"
)
# 获取工具调用
tool_call = resp.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
# 模拟工具执行
weather_result = f"{args['city']} 晴天 25°C"
# 第二次调用,返回结果给模型
messages.append(resp.choices[0].message)
messages.append({"role": "tool", "tool_call_id": tool_call.id, "content": weather_result})
final = client.chat.completions.create(
model="${ENDPOINT}", # 替换为你的接入点ID
messages=messages
)
print(final.choices[0].message.content)