您的位置:首页 > 房产 > 家装 > 免费贴图素材网站_真正免费的网站建站平台一_关键词组合工具_地推接单在哪个平台找

免费贴图素材网站_真正免费的网站建站平台一_关键词组合工具_地推接单在哪个平台找

2025/4/26 23:39:28 来源:https://blog.csdn.net/weixin_43160662/article/details/147341815  浏览:    关键词:免费贴图素材网站_真正免费的网站建站平台一_关键词组合工具_地推接单在哪个平台找
免费贴图素材网站_真正免费的网站建站平台一_关键词组合工具_地推接单在哪个平台找

🧍 用户:

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com