Function Calling的机制 (含示例)
原理图:
示例:
# === 标准库 ===
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)