from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.ppinfra.com/openai",
api_key="<Your API Key>",
)
model = "deepseek/deepseek-v3"
# 示例函数,用于模拟获取天气数据。
def get_weather(location):
"""获取指定地点的当前天气"""
print("调用 get_weather 函数,位置: ", location)
# 在实际应用中,您需要在这里调用外部天气 API。
# 这是一个简化示例,返回硬编码数据。
return json.dumps({"位置": location, "温度": "20 摄氏度"})
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取一个地点的天气,用户需要首先提供地点",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市信息, 例如:上海",
}
},
"required": ["location"]
},
}
},
]
messages = [
{
"role": "user",
"content": "上海的天气怎么样?"
}
]
# 发送请求并打印响应
response = client.chat.completions.create(
model=model,
messages=messages,
tools=tools,
)
# 请在生产环境中检查响应是否包含工具调用
tool_call = response.choices[0].message.tool_calls[0]
print(tool_call.model_dump())
# 确保工具调用已从上一步定义
if tool_call:
# 扩展对话历史记录,添加助手工具调用消息
messages.append(response.choices[0].message)
function_name = tool_call.function.name
if function_name == "get_weather":
function_args = json.loads(tool_call.function.arguments)
# 执行函数并获取响应
function_response = get_weather(
location=function_args.get("location"))
# 将函数响应添加到消息中
messages.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"content": function_response,
}
)
# 从模型获取最终响应,包含函数结果
answer_response = client.chat.completions.create(
model=model,
messages=messages,
# 注意:不要在此处包含 tools 参数
)
print(answer_response.choices[0].message)