跳到主要内容

工具调用

工具调用(Tool Calling)是一种让大模型与外部系统交互的机制,使模型能够调用外部工具,将能力从纯文本生成扩展到使用外部能力。

1. 支持的模型​

GLM

  • GLM-5.1
  • GLM-5
  • GLM-4.7

Minimax

  • MiniMax-M2.5
  • MiniMax-M2.1

2. 使用方式​

2.1 通过 OpenAI 库请求​

from openai import OpenAI
import json

client = OpenAI(
base_url="https://api.jalapeno-cloud.ai/v1/chat/completions",
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.jalapeno-cloud.ai/v1/chat/completions",
api_key="${API_KEY}"
)

tools = [{
"type": "function",
"function": {
"name": "get_weather",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}}
}
}]

messages = [{"role": "user", "content": "What's the weather like in Beijing?"}]

# First call, model returns tool call request
resp = client.chat.completions.create(
model="${MODEL_NAME}",
messages=messages,
tools=tools,
tool_choice="auto"
)

# Get tool call
tool_call = resp.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)

# Simulate tool execution
weather_result = f"{args['city']} sunny 25°C"

# Second call, send result back to model
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="${MODEL_NAME}",
messages=messages
)

print(final.choices[0].message.content)

响应​

<think>Okay, I've got the weather information for Beijing. Now I need to respond to the user in a friendly way.
</think>
Today's weather in Beijing is **sunny** with a temperature of **25°C**. The weather is nice, perfect for outdoor activities! Remember to protect yourself from the sun and stay hydrated.