import json
from openai import OpenAI
client = OpenAI(api_key="sk-你的密钥", base_url="https://moxus.ai/v1")
def get_weather(city: str) -> dict:
# 实际应调用天气 API
return {"temp": "25℃", "condition": "晴"}
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询指定城市的当前天气",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"],
},
},
}
]
messages = [{"role": "user", "content": "北京今天天气怎么样?"}]
# 第一轮:模型判断是否调用工具
resp = client.chat.completions.create(
model="gpt-4o", messages=messages, tools=tools, tool_choice="auto"
)
msg = resp.choices[0].message
if msg.tool_calls:
messages.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = get_weather(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False),
})
# 第二轮:回传结果,获取最终响应
final = client.chat.completions.create(model="gpt-4o", messages=messages, tools=tools)
print(final.choices[0].message.content)
else:
print(msg.content)