Files
AI0814_jiaoan_public/w1_d3/6_toolcalls4.py
T
2026-09-23 21:27:55 +08:00

86 lines
2.6 KiB
Python

from openai import OpenAI
import os
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(
api_key=os.environ.get("DEEPSEEK_API_KEY"),
base_url="https://api.deepseek.com",
)
# 1. 定义一个获取天气的工具
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "城市名,如杭州"},
},
"required": ["location"],
},
},
}
]
# 2. 用户提问
messages = [{"role": "user", "content": "你好,杭州和深圳和北京的天气怎么样"}]
# 第一次调用模型:模型会返回 tool_calls
response = client.chat.completions.create(
model="deepseek-v4-pro", # 换成你实际可用的模型名,如 deepseek-v4-pro
messages=messages,
tools=tools, # 传入工具列表
)
# 获取模型的回复(通常包含 tool_calls)
assistant_msg = response.choices[0].message
print(assistant_msg)
print(assistant_msg.model_dump_json(indent=2))
print(assistant_msg.content)
print("模型第一次回复:", assistant_msg.content)
def get_weather(location: str) -> str:
return f"{location}的天气为 8℃"
tools_map={'get_weather':get_weather}
messages.append(assistant_msg)
if assistant_msg.tool_calls:
# for i in range(len(assistant_msg.tool_calls)):
# name=assistant_msg.tool_calls[i].function.name
# print(name)
# import json
# r=json.loads(assistant_msg.tool_calls[i].function.arguments)
# print(r)
# arg=r.get('location')
# print(arg)
# tool_id=assistant_msg.tool_calls[i].id
# print(tool_id)
# tools_result = tools_map.get(name)(**r)
# messages.append({'role': "tool", "tool_call_id": tool_id, 'content': tools_result})
for tool_call in assistant_msg.tool_calls:
name=tool_call.function.name
print(name)
import json
r=json.loads(tool_call.function.arguments)
print(r)
arg=r.get('location')
print(arg)
tool_id=tool_call.id
print(tool_id)
tools_result = tools_map.get(name)(**r)
messages.append({'role': "tool", "tool_call_id": tool_id, 'content': tools_result})
response = client.chat.completions.create(
model="deepseek-v4-pro", # 换成你实际可用的模型名,如 deepseek-v4-pro
messages=messages,
tools=tools, # 传入工具列表
)
print("模型第二次回复:", response.choices[0].message.content)