函数调用
Claude 函数调用可以让模型根据用户问题自动选择工具,并返回 tool_use 内容块。你可以根据模型给出的工具名和参数,在自己的业务系统中执行真实函数,再把结果返回给模型生成最终回答。
请求地址
https://api.maomaotoken.com/v1/messagesPython 示例代码
下面示例定义了一个 get_weather 天气查询工具,让 Claude 判断是否需要调用它。
"""
MaomaoToken Claude 函数调用示例
功能:
- 演示 Claude 原生工具调用格式
- 示例工具:天气查询
- 包含基础错误处理和响应格式化
"""
import json
import os
import requests
# ==================== 配置参数 ====================
api_key = os.getenv("MAOMAO_API_KEY", "sk-**********************************")
url = "https://api.maomaotoken.com/v1/messages"
# ==================== 请求头 ====================
headers = {
"content-type": "application/json",
"x-api-key": api_key
}
# ==================== 请求数据 ====================
data = {
"model": "claude-sonnet-4-6",
"messages": [
{
"role": "user",
"content": "今天北京的天气怎么样?"
}
],
"tools": [
{
"name": "get_weather",
"description": "获取指定位置的当前天气",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称,如:北京"
}
},
"required": ["location"]
}
}
]
}
def main():
print("开始执行 Claude 函数调用测试...")
print("=" * 50)
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
print("请求成功")
print(f"状态码: {response.status_code}")
print("响应内容:")
print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except requests.exceptions.RequestException as e:
print(f"请求错误: {e}")
except ValueError as e:
print(f"JSON 解析错误: {e}")
except Exception as e:
print(f"未预期的错误: {e}")
if __name__ == "__main__":
main()返回示例
模型判断需要调用工具时,响应中会包含 tool_use:
{
"id": "msg_example",
"type": "message",
"role": "assistant",
"model": "claude-sonnet-4-6",
"content": [
{
"type": "text",
"text": "好的,让我来帮您查询北京今天的天气情况。"
},
{
"id": "toolu_example",
"type": "tool_use",
"name": "get_weather",
"input": {
"location": "北京"
}
}
],
"stop_reason": "tool_use",
"usage": {
"input_tokens": 590,
"output_tokens": 77
}
}解析工具调用
result = response.json()
for block in result.get("content", []):
if block.get("type") == "tool_use":
tool_use_id = block.get("id")
tool_name = block.get("name")
tool_input = block.get("input", {})
print("工具 ID:", tool_use_id)
print("工具名称:", tool_name)
print("工具参数:", tool_input)后续流程
真实业务中,函数调用通常分为两步:
- Claude 返回
tool_use,告诉你要调用哪个工具以及参数。 - 你的服务端执行真实工具,再用
tool_result把结果发回 Claude。
tool_result 示例:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_example",
"content": "北京今天晴,气温 25°C,空气质量良好。"
}
]
}使用说明
| 项目 | 说明 |
|---|---|
| API Key | 建议通过 MAOMAO_API_KEY 环境变量配置。 |
| 请求格式 | 使用 JSON 格式,包含 model、messages 和 tools。 |
| 工具定义 | 每个工具需要 name、description 和 input_schema。 |
| 工具返回 | 模型会通过 tool_use 返回工具名和参数。 |
注意事项
- 请将示例中的 API Key 替换为你的真实 MaomaoToken API Key。
- 工具参数需要符合 JSON Schema。
- 生产环境建议添加超时、重试和错误处理。
- 涉及支付、删除、下单等敏感操作时,建议增加用户确认和权限校验。
- Claude 返回
tool_use不代表工具已经执行,真实执行逻辑需要由你的业务系统完成。