我以chatgpt和python为例实现一个对话过程中条用functioncall的过程,其他兼容openai的国内大模型也可以使用


代码如下:
from openai import OpenAI
# 初始化 OpenAI 客户端
client = OpenAI(api_key="",base_url="https://api.openai.com/v1")
# 定义可用的工具(Function Call)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称,例如:北京"
}
},
"required": ["location"]
}
}
},
{
"type": "function",
"function": {
"name": "calculate_math",
"description": "计算数学表达式",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "数学表达式,例如:2 + 3 * 4"
}
},
"required": ["expression"]
}
}
}
]
# 模拟工具调用
def call_tool(function_name, arguments):
if function_name == "get_weather":
location = arguments["location"]
# 这里可以调用实际的天气 API
return f"{location}的天气是晴天,25℃。"
elif function_name == "calculate_math":
expression = arguments["expression"]
# 这里可以调用计算逻辑
return f"计算结果:{eval(expression)}"
else:
return "未知工具"
# 主对话函数
def chat_with_assistant():
messages = [{"role": "system", "content": "你是一个智能助手,可以帮助用户查询天气或计算数学表达式。"}]
while True:
# 获取用户输入
user_input = input("用户: ")
if user_input.lower() in ["退出", "再见"]:
print("助手: 再见!")
break
# 将用户输入添加到消息中
messages.append({"role": "user", "content": user_input})
# 调用 OpenAI API
response = client.chat.completions.create(
model="gpt-3.5-turbo", # 使用 GPT-3.5 模型
messages=messages,
tools=tools,
tool_choice="auto" # 自动选择是否调用工具
)
# 获取助手的回复
assistant_message = response.choices[0].message
messages.append({"role": assistant_message.role, "content": assistant_message.content})
# 检查是否需要调用工具
if assistant_message.tool_calls:
for tool_call in assistant_message.tool_calls:
function_name = tool_call.function.name
arguments = eval(tool_call.function.arguments)
# 调用工具并获取结果
tool_result = call_tool(function_name, arguments)
# 将工具结果添加到消息中,并包含 tool_call_id
messages.append({
"role": "tool",
"name": function_name,
"content": tool_result,
"tool_call_id": tool_call.id # 添加 tool_call_id
})
# 将工具结果返回给用户
print(f"助手: {tool_result}")
else:
# 直接返回助手的回复
print(f"助手: {assistant_message.content}")
# 启动对话
if __name__ == "__main__":
chat_with_assistant() 网友回复


