
本指南将指导您如何使用 Python 和 Claude 实现函数调用,并提供示例和最佳实践。通过函数调用,Claude 可以以结构化的方式与外部函数和工具交互。
先决条件
开始之前,您需要:
基本设置
立即学习“Python免费学习笔记(深入)”;
<code class="python">from anthropic import Anthropic import json # 初始化客户端 anthropic = Anthropic(api_key='your-api-key')</code>
定义函数
以下代码定义了一个名为 get_weather 的函数,该函数获取特定位置的当前天气信息:
<code class="python">function_schema = {
"name": "get_weather",
"description": "获取特定位置的当前天气信息",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称或坐标"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度单位"
}
},
"required": ["location"]
}
}</code>进行函数调用
以下代码演示了如何进行函数调用:
<code class="python">def get_weather(location, unit="celsius"):
# 这是一个模拟实现,您可以调用您的 API
return {
"location": location,
"temperature": 22 if unit == "celsius" else 72,
"conditions": "晴朗"
}
def process_function_call(message):
try:
# 解析函数调用参数
params = json.loads(message.content)
# 调用相应的函数
if message.name == "get_weather":
result = get_weather(**params)
return json.dumps(result)
else:
raise ValueError(f"未知函数:{message.name}")
except Exception as e:
return json.dumps({"error": str(e)})
# 使用函数调用的示例对话
messages = [
{
"role": "user",
"content": "巴黎的天气怎么样?"
}
]
while True:
response = anthropic.messages.create(
model="claude-3-5-haiku-latest",
messages=messages,
tools=[function_schema]
)
# 检查 Claude 是否要调用函数
if response.tool_calls:
for tool_call in response.tool_calls:
# 执行函数
result = process_function_call(tool_call)
# 将函数结果添加到对话中
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"name": tool_call.name,
"content": result
})
else:
# 普通响应 - 打印并中断
print(response.content)
break
</code>最佳实践
结论
使用 Claude 进行函数调用可以在语言模型和外部工具之间实现强大的集成。通过遵循这些最佳实践并实现适当的错误处理,您可以创建强大且可靠的函数调用实现。
以上就是python中的LLM函数逐步指南的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号