mirror of
http://47.106.207.27:3000/Jeremy_liu/AI0814_jiaoan_public.git
synced 2026-09-27 06:14:14 +08:00
87 lines
2.5 KiB
Python
87 lines
2.5 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)
|
|
|
|
|
|
if assistant_msg.tool_calls:
|
|
name=assistant_msg.tool_calls[0].function.name
|
|
print(name)
|
|
import json
|
|
r=json.loads(assistant_msg.tool_calls[0].function.arguments)
|
|
print(r)
|
|
arg=r.get('location')
|
|
print(arg)
|
|
tool_id=assistant_msg.tool_calls[0].id
|
|
print(tool_id)
|
|
|
|
|
|
name2=assistant_msg.tool_calls[1].function.name
|
|
print(name2)
|
|
import json
|
|
r2=json.loads(assistant_msg.tool_calls[1].function.arguments)
|
|
print(r2)
|
|
arg2=r2.get('location')
|
|
print(arg2)
|
|
tool_id2=assistant_msg.tool_calls[1].id
|
|
print(tool_id2)
|
|
|
|
def get_weather(location: str) -> str:
|
|
return f"{location}的天气为 880℃"
|
|
|
|
tools_map={'get_weather':get_weather}
|
|
tools_result=tools_map.get(name)(**r)
|
|
tools_result2=tools_map.get(name2)(**r2)
|
|
print(tools_result)
|
|
messages.append(assistant_msg)
|
|
messages.append({'role':"tool","tool_call_id": tool_id,'content':tools_result})
|
|
messages.append({'role':"tool","tool_call_id": tool_id2,'content':tools_result2})
|
|
|
|
response = client.chat.completions.create(
|
|
model="deepseek-v4-pro", # 换成你实际可用的模型名,如 deepseek-v4-pro
|
|
messages=messages,
|
|
tools=tools, # 传入工具列表
|
|
)
|
|
print("模型第二次回复:", response.choices[0].message.content)
|