当前位置: 首页 > news >正文

Function Calling的时序图(含示例)

🧍 用户:

发起请求,输入 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)

http://www.mrgr.cn/news/98958.html

相关文章:

  • Windows 11设置开机自动运行 .jar 文件
  • 前端服务器部署报错记录
  • 从 Transformer 到文本生成 (From Transformer to Text Generation)
  • 3、排序算法1---按考研大纲做的
  • Model Context Protocol (MCP) 开放协议对医疗多模态数据整合的分析路径【附代码】
  • 【失败】Gnome将默认终端设置为 Kitty
  • 【从零实现高并发内存池】申请、释放内存过程联调测试 与 大于256KB内存申请全攻略
  • 2D物体检测学习
  • C++ `shared_ptr` 多线程使用
  • 深入理解C++中string的深浅拷贝
  • day1-小白学习JAVA---JDK安装和环境变量配置(mac版)
  • 认知觉醒是什么? 如何做到 ? ( 持续更新ing )
  • cpolar 内网穿透 实现公网可以访问本机
  • [编程基础] Java · 学习手册
  • MATLAB 控制系统设计与仿真 - 35
  • 下拉框select标签类型
  • 基于linux 设置无线网卡Monitor模式 sniffer抓包
  • Git-使用教程(新手向)
  • 向量数据库前沿:Faiss 向量数据库的配置与使用(文中有彩蛋)
  • 高频面试题:Android MVP/MVVM/MVI这几种架构在实际生产中,各自的优缺点和适用场景是什么