一、第三方库
pip install openai
二、示例代码
import json
import random
from openai import OpenAI
from datetime import datetime
class ToolsUsage:
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "获取指定地点的天气信息",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "地点名称"}
},
"required": ["location"]
}
}
},
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "当你想知道现在的时间时非常有用。",
"parameters": {},
},
},
]
@staticmethod
def get_current_weather(location):
weather_conditions = ["晴天", "多云", "雨天"]
random_weather = random.choice(weather_conditions)
return f"{location}今天是{random_weather}。"
@staticmethod
def get_current_time():
current_datetime = datetime.now()
formatted_time = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
return f"当前时间:{formatted_time}。"
@staticmethod
def execute_tools(func_name, func_args):
func_dic = {
"get_current_weather": ToolsUsage.get_current_weather,
"get_current_time": ToolsUsage.get_current_time,
}
return func_dic[func_name](**func_args)
class ChatAgent:
def __init__(self, api_key: str, url: str, model_name: str):
self.client = OpenAI(api_key=api_key, base_url=url)
self.model_name = model_name
def request_chat(self, messages: list):
response = self.client.chat.completions.create(
model=self.model_name,
messages=messages,
tools=ToolsUsage.tools,
extra_body={"enable_thinking": False},
tool_choice="auto",
)
return response
def execute_chat(self):
print("\n")
messages = [
{
"content": input(
"请输入问题:"
),
"role": "user",
}
]
print("-*" * 60)
i = 1
first_response = self.request_chat(messages)
assistant_output = first_response.choices[0].message
print(f"\n第{i}轮大模型输出信息:{assistant_output}\n")
if not assistant_output.tool_calls:
print(f"无需调用工具,直接回复:{assistant_output.content}")
return
tool_calls_result = assistant_output.tool_calls
while tool_calls_result:
for tool_call in assistant_output.tool_calls:
tool_info = {
"content": "",
"role": "tool",
"tool_call_id": assistant_output.tool_calls[0].id,
}
func_name = tool_call.function.name
func_args = json.loads(tool_call.function.arguments)
tools_result = ToolsUsage.execute_tools(func_name, func_args)
print(f"当前调用工具:{func_name},参数:{func_args},输出信息:{tools_result}\n")
tool_info["content"] = tools_result
messages.append(tool_info)
print("-*" * 60)
second_response = self.request_chat(messages)
assistant_output = second_response.choices[0].message
i += 1
print(f"第{i}轮大模型输出信息:{assistant_output}\n")
if not assistant_output.tool_calls:
tool_calls_result = None
print(f"最终答案:\n {assistant_output.content}")
if __name__ == "__main__":
api_key = 'xxxxxx'
base_url = "http://xxxxxxxx/v1"
model = "qwen3"
chat_service = ChatAgent(api_key, base_url, model)
chat_service.execute_chat()