🧍 用户:
发起请求,输入 prompt(比如:“请告诉我北京的天气”)。
🟪 应用:
将用户输入的 prompt 和函数定义(包括函数名、参数结构等)一起发给 OpenAI。
接收 OpenAI 返回的「函数调用参数」。
根据这些参数,调用本地或后端实现的实际函数(比如:天气 API)。
获取函数返回的结果。
🟩 OpenAI:
接收到 prompt + function 定义后,判断是否应该调用某个函数。
如果模型决定调用函数,就返回相应函数名和参数。
应用调用完函数并把结果发回来后,OpenAI 生成自然语言的回答。
时序图:
示例:
# === 标准库 ===
import json
import math
# === 第三方库 ===
from openai import OpenAI
from dotenv import load_dotenv, find_dotenv
# === 环境变量初始化 ===
_ = load_dotenv(find_dotenv())
# === OpenAI 客户端 ===
client = OpenAI()
# === 工具函数:格式化打印 JSON ===
def print_json(data):
"""
打印参数。如果参数是结构化(如 dict 或 list),则格式化打印;
否则直接输出。
"""
if hasattr(data, 'model_dump_json'):
data = json.loads(data.model_dump_json())
if isinstance(data, list):
for item in data:
print_json(item)
elif isinstance(data, dict):
print(json.dumps(data, indent=4, ensure_ascii=False))
else:
print(data)
# === 核心功能函数:与大模型对话 ===
def get_completion(messages, model="gpt-4o-mini"):
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=0.7,
tools=[{
"type": "function",
"function": {
"name": "sum",
"description": "加法器,计算一组数的和",
"parameters": {
"type": "object",
"properties": {
"numbers": {
"type": "array",
"items": {"type": "number"}
}
}
}
}
}],
)
return response.choices[0].message
# === 主逻辑 ===
prompt = "Tell me the sum of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10."
messages = [
{"role": "system", "content": "你是一个数学家"},
{"role": "user", "content": prompt}
]
response = get_completion(messages)
messages.append(response)
if response.tool_calls:
tool_call = response.tool_calls[0]
if tool_call.function.name == "sum":
args = json.loads(tool_call.function.arguments)
result = sum(args["numbers"])
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": "sum",
"content": str(result)
})
response = get_completion(messages)
messages.append(response)
print("=====最终 GPT 回复=====")
print(response.content)
print("=====对话历史=====")
print_json(messages)