大模型工程师基础之学会使用openai
欢迎关注:857技术社区
大模型工程师的第一课,学会使用 OpenAI 的 API 是个很棒的起点。不论你是为了微调模型、接入大模型能力,还是开发智能体系统,这一步都像是大门的钥匙。
下面是“第一课”的核心内容结构,适合新手入门,同时具备一定的工程化视角:
🚀 第一步:注册并获取 API Key
- 访问
https://platform.openai.com
- 注册账号并完成邮箱验证
- 进入控制台,获取你的
API Key
- 建议把 Key 写入环境变量中,例如
.env
文件中:
OPENAI_API_KEY=your_api_key_here
📦 第二步:安装 SDK
pip install openai
🧪 第三步:Hello, ChatGPT!
import openai
import osopenai.api_key = os.getenv("OPENAI_API_KEY") # 从环境变量中读取response = openai.ChatCompletion.create(model="gpt-4", # 也可以用 "gpt-3.5-turbo"messages=[{"role": "system", "content": "你是一个助理"},{"role": "user", "content": "帮我写一个Python版的快速排序"},]
)print(response['choices'][0]['message']['content'])
🛠 第四步:理解几个关键概念
名称 | 说明 |
---|---|
model | 使用的模型,比如 gpt-4 , gpt-3.5-turbo |
messages | 聊天历史列表,用来实现多轮对话 |
temperature | 控制随机性(越高越creative) |
max_tokens | 限制返回的token长度 |
tools | 用于调用函数、插件、agent 的接口(进阶) |
🧠 第五步:用大模型做更多事情(可选进阶)
- ✅ 文本总结
- ✅ 信息抽取(如提取人名、地名、时间)
- ✅ 代码生成和解释
- ✅ 多轮对话与上下文管理
- ✅ 结构化输出(比如
function_call
)
📌 工程师Tips
- 日志管理:记录请求与响应日志,方便debug
- token管理:注意 OpenAI 会按 token 收费,记得用
tiktoken
或openai_tokenizer
做预算控制 - 缓存机制:重复请求可以缓存,降低成本
- 接口调用失败要重试:如网络波动、rate limit 等常见异常
当我们简单地使用openai的接口之后我们接下来开始学习openai的不同的打开方式。
第一种打开方式
💻 第一课:使用 OpenAI 打开大模型世界的大门 —— Text Generation & Prompting
🎯 课程目标
- 初步掌握使用 OpenAI API 生成文本
- 学会用不同方式传入 Prompt 和 Instruction
- 初识 Prompt Engineering(提示词工程)
一、快速入门:用一行 prompt 生成文本 ✨
✅ 使用 OpenAI 的 Responses API(新推荐接口)
from openai import OpenAI
client = OpenAI()response = client.responses.create(model="gpt-4.1",input="Write a one-sentence bedtime story about a unicorn."
)
print(response.output_text)
结果可能是这样:
"Under the soft glow of the moon, Luna the unicorn danced through fields of twinkling stardust..."
二、Text Generation 的多种打开方式 🚪
1. 📥 使用简单 prompt(传统输入)
适合快速试验模型能力:
input="Explain why the sky is blue."
2. 🧭 使用 Instructions 参数(高优先级指令)
这种方式可对模型行为进行全局控制,例如要求“用海盗口吻说话”:
instructions="Talk like a pirate.",
input="Are semicolons optional in JavaScript?"
3. 🧑🤝🧑 使用角色消息结构 input(多轮对话推荐)
类似 ChatGPT 的多角色对话形式,适合复杂交互:
input=[{"role": "developer", "content": "Talk like a pirate."},{"role": "user", "content": "Are semicolons optional in JavaScript?"}
]
三、输出结果结构详解 🧱
OpenAI 的响应结构可能包括:
output: [{"type": "message","role": "assistant","content": [{"type": "output_text","text": "...","annotations": []}]}
]
注意:不要默认内容只在 output[0].content[0].text
中!
四、模型选择建议 🤖
模型类型 | 适用场景 |
---|---|
gpt-4.1 | 推荐默认选项,能力强、成本适中 |
reasoning models | 复杂推理任务、数据分析、计划生成 |
mini/nano models | 快速、低成本任务,如分类、摘要 |
五、提示词工程(Prompt Engineering)技巧 🌱
- 使用明确的角色与任务定义
- 编写 few-shot 示例(如“输入-输出”对)
- 控制输出格式,如 JSON、markdown、代码等
- 固定使用特定模型 snapshot,保障一致性:
model="gpt-4.1-2025-04-14"
📘 延伸阅读推荐
- 官方文档主页:
https://platform.openai.com/docs
- Structured Outputs:
https://platform.openai.com/docs/guides/structured-outputs
返回结构化 JSON 数据 - Prompt Engineering 指南:
https://platform.openai.com/docs/guides/prompting
你这段内容很适合作为 OpenAI 多模态接口教学的第二部分内容,下面我来帮你梳理一下结构和重点,并可以为你补齐结尾那段 Python 示例代码。
🖼 第二课:使用 OpenAI 读懂世界的图像 —— Vision 模型与图像输入
✅ Vision 是什么?
Vision 是 GPT-4 系列模型的新能力,它支持“图像作为输入”,不仅能看图,还能理解图,生成文字回应。它支持两种方式输入图像:
- 通过网络图片 URL 提供图像
- 通过本地图片转为 Base64 编码
🧪 图像输入方式一:传入图片 URL
from openai import OpenAIclient = OpenAI()response = client.responses.create(model="gpt-4.1-mini",input=[{"role": "user","content": [{"type": "input_text", "text": "what's in this image?"},{"type": "input_image","image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"}]}]
)print(response.output_text)
🔐 图像输入方式二:使用 Base64 编码传入本地图片
import base64
from openai import OpenAIclient = OpenAI()def encode_image(image_path):with open(image_path, "rb") as image_file:return base64.b64encode(image_file.read()).decode("utf-8")base64_image = encode_image("path_to_your_image.jpg")response = client.responses.create(model="gpt-4.1-mini",input=[{"role": "user","content": [{"type": "input_text", "text": "what's in this image?"},{"type": "input_image","image_url": f"data:image/jpeg;base64,{base64_image}","detail": "high" # 可选 detail: "low" | "high" | "auto"}]}]
)print(response.output_text)
🧭 细节控制:detail
参数
"low"
:快速处理(约 85 tokens),适合大致判断图像内容"high"
:更精准(每块图像约 170 tokens),适合看细节"auto"
:自动选择处理级别
🖼📸 多图对比分析
你也可以同时输入多张图片进行对比、比对、归纳等操作:
from openai import OpenAIclient = OpenAI()response = client.responses.create(model="gpt-4.1-mini",input=[{"role": "user","content": [{"type": "input_text", "text": "What are in these images? Is there any difference between them?"},{"type": "input_image","image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"},{"type": "input_image","image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"}]}]
)print(response.output_text)
📏 图像要求汇总
格式支持 | 大小限制 |
---|---|
PNG, JPEG, WEBP, GIF(非动图) | 单图 ≤ 20MB;单请求最多 500 张图,总计 ≤ 50MB |
其他要求:
- 不能含有文字、Logo、水印
- 不能为 NSFW(不适合工作内容)
- 图像清晰、人眼可理解
🎤 第三课重点:Audio and Speech 功能概览
✅ 支持的音频任务类型:
功能 | 描述 | 推荐 API |
---|---|---|
🎙️ 语音代理(Voice Agents) | 交互式语音应用,支持语音输入输出 | Realtime API(低延迟)或Chat Completions API(可配合 Agents SDK) |
📝 语音转文字(Speech to Text) | 准确将语音转文字 | audio/transcriptions 端点(如 whisper-1 , gpt-4o-transcribe ) |
🗣️ 文本转语音(Text to Speech) | 将文字变为自然语音 | audio/speech 端点(如 tts-1 , gpt-4o-mini-tts ) |
🔁 音频流(Streaming Audio) | 实时语音交互和转写 | Realtime API |
🔌 API 选择建议:
API | 输入输出 | 支持流式 | 用途 |
---|---|---|---|
Realtime API | 语音 + 文本输入输出 | ✅ | 实时语音代理、低延迟 |
Chat Completions API | 文本 + 音频输出 | ✅(输出) | 非实时语音对话,支持函数调用 |
Transcription API | 音频 → 文本 | ✅ | 专注于语音识别 |
Speech API | 文本 → 音频 | ✅ | 专注于语音合成 |
🧠 构建 Voice Agent 的两种方式:
-
Speech-to-Speech 模型(实时)
使用Realtime API
,延迟低,自然度高。 -
链式方式(Speech-to-Text + LLM + Text-to-Speech)
延迟稍高,但模块可控,适合已有文本代理系统改造为语音代理。
🧪 示例代码:用 GPT-4o 生成语音回答
✅ Python 版本
import base64
from openai import OpenAIclient = OpenAI()completion = client.chat.completions.create(model="gpt-4o-audio-preview",modalities=["text", "audio"],audio={"voice": "alloy", "format": "wav"},messages=[{"role": "user","content": "Is a golden retriever a good family dog?"}]
)# 保存语音文件
audio_data = base64.b64decode(completion.choices[0].message.audio.data)
with open("dog.wav", "wb") as f:f.write(audio_data)
🧭 使用场景推荐指南
场景 | 推荐 API |
---|---|
实时语音对话 | Realtime API |
构建有函数调用的语音代理 | Chat Completions API |
单一任务(如转写或合成) | Transcription 或 Speech API |
🎤 第四课重点:Structured Outputs 功能概览
确保模型响应始终遵循指定的 JSON Schema。
✅ 功能简介
Structured Outputs 是一种功能,可确保模型生成符合您提供的 JSON Schema https://json-schema.org/overview/what-is-jsonschema
的响应,避免遗漏必需键或生成无效枚举值。
主要优势:
- 可靠的类型安全:无需验证或重试格式错误的响应。
- 明确的拒绝:基于安全的模型拒绝可通过程序检测。
- 简化的提示:无需强硬措辞的提示即可实现一致格式。
🔌 支持的模型
Structured Outputs 适用于最新大型语言模型,从 gpt-4o
开始。旧模型(如 gpt-4-turbo
及更早版本)可使用JSON 模式#json-mode
。
🧠 Structured Outputs 的两种使用方式
-
通过函数调用:
- 适用场景:连接模型与应用中的工具、函数或数据。
- 示例:查询数据库以构建 AI 助手,或与 UI 交互。
-
通过
text.format
:- 适用场景:为模型响应指定结构化 schema,适合直接呈现给用户。
- 示例:数学辅导应用中,使用特定 JSON Schema 生成 UI 显示模型输出的不同部分。
使用场景 | 推荐方式 |
---|---|
连接工具/函数 | 函数调用 |
结构化用户响应 | text.format |
🆚 Structured Outputs vs JSON 模式
特性 | Structured Outputs | JSON 模式 |
---|---|---|
输出有效 JSON | ✅ | ✅ |
遵循 Schema | ✅(支持指定 Schema) | ❌ |
兼容模型 | gpt-4o-mini , gpt-4o-2024-08-06 及更新版本 | gpt-3.5-turbo , gpt-4-* , gpt-4o-* |
启用方式 | text: { format: { type: "json_schema", "strict": true, "schema": ... } } | text: { format: { type: "json_object" } } |
推荐:尽可能使用 Structured Outputs 而非 JSON 模式。
🧪 示例代码
1. 思维链(Chain of Thought)
引导用户逐步解决数学问题。
✅ Python 版本
import json
from openai import OpenAIclient = OpenAI()response = client.responses.create(model="gpt-4o-2024-08-06",input=[{"role": "system", "content": "You are a helpful math tutor. Guide the user through the solution step by step."},{"role": "user", "content": "How can I solve 8x + 7 = -23"}],text={"format": {"type": "json_schema","name": "math_reasoning","schema": {"type": "object","properties": {"steps": {"type": "array","items": {"type": "object","properties": {"explanation": {"type": "string"},"output": {"type": "string"}},"required": ["explanation", "output"],"additionalProperties": False}},"final_answer": {"type": "string"}},"required": ["steps", "final_answer"],"additionalProperties": False},"strict": True}}
)math_reasoning = json.loads(response.output_text)
print(math_reasoning)
示例响应
{"steps": [{"explanation": "Start with the equation 8x + 7 = -23.", "output": "8x + 7 = -23"},{"explanation": "Subtract 7 from both sides to isolate the term with the variable.", "output": "8x = -30"},{"explanation": "Divide both sides by 8 to solve for x.", "output": "x = -30 / 8"},{"explanation": "Simplify the fraction.", "output": "x = -15 / 4"}],"final_answer": "x = -15 / 4"
}
2. 结构化数据提取
从非结构化文本(如研究论文)中提取数据。
✅ Python 版本
import json
from openai import OpenAIclient = OpenAI()response = client.responses.create(model="gpt-4o-2024-08-06",input=[{"role": "system", "content": "You are an expert at structured data extraction. Extract key information from the research paper text."},{"role": "user", "content": "Title: Quantum Algorithms in Navigation... Authors: Dr. Stella Voyager, Dr. Nova Star..."}],text={"format": {"type": "json_schema","name": "research_paper_extraction","schema": {"type": "object","properties": {"title": {"type": "string"},"authors": {"type": "array", "items": {"type": "string"}},"abstract": {"type": "string"},"keywords": {"type": "array", "items": {"type": "string"}}},"required": ["title", "authors", "abstract", "keywords"],"additionalProperties": False},"strict": True}}
)research_paper = json.loads(response.output_text)
print(research_paper)
示例响应
{"title": "Quantum Algorithms in Navigation","authors": ["Dr. Stella Voyager", "Dr. Nova Star"],"abstract": "This paper explores quantum algorithms for navigation systems...","keywords": ["quantum algorithms", "navigation", "space travel"]
}
3. UI 生成
通过递归数据结构生成有效 HTML。
✅ Python 版本
import json
from openai import OpenAIclient = OpenAI()response = client.responses.create(model="gpt-4o-2024-08-06",input=[{"role": "system", "content": "You are a UI generator AI. Convert the user input into a UI."},{"role": "user", "content": "Make a User Profile Form"}],text={"format": {"type": "json_schema","name": "ui","schema": {"type": "object","properties": {"type": {"type": "string", "enum": ["div", "button", "header", "section", "field", "form"]},"label": {"type": "string"},"children": {"type": "array", "items": {"$ref": "#"}},"attributes": {"type": "array","items": {"type": "object","properties": {"name": {"type": "string"},"value": {"type": "string"}},"required": ["name", "value"],"additionalProperties": False}}},"required": ["type", "label", "children", "attributes"],"additionalProperties": False},"strict": True}}
)ui = json.loads(response.output_text)
print(ui)
示例响应
{"type": "form","label": "User Profile Form","children": [{"type": "field","label": "First Name","children": [],"attributes": [{"name": "type", "value": "text"},{"name": "name", "value": "firstName"}]},{"type": "button","label": "Submit","children": [],"attributes": [{"name": "type", "value": "submit"}]}],"attributes": [{"name": "method", "value": "post"}]
}
4. 内容审核
对输入进行多类别分类,适用于内容审核。
✅ Python 版本
import json
from openai import OpenAIclient = OpenAI()response = client.responses.create(model="gpt-4o-2024-08-06",input=[{"role": "system", "content": "Determine if the user input violates specific guidelines and explain if they do."},{"role": "user", "content": "How do I prepare for a job interview?"}],text={"format": {"type": "json_schema","name": "content_compliance","schema": {"type": "object","properties": {"is_violating": {"type": "boolean"},"category": {"type": ["string", "null"], "enum": ["violence", "sexual", "self_harm", null]},"explanation_if_violating": {"type": ["string", "null"]}},"required": ["is_violating", "category", "explanation_if_violating"],"additionalProperties": False},"strict": True}}
)compliance = json.loads(response.output_text)
print(compliance)
示例响应
{"is_violating": false,"category": null,"explanation_if_violating": null
}
🧭 使用场景推荐指南
场景 | 推荐方式 |
---|---|
数学问题逐步解答 | text.format (思维链) |
提取非结构化数据 | text.format (数据提取) |
生成 UI 结构 | text.format (UI 生成) |
内容审核 | text.format (分类) |
工具/函数集成 | 函数调用 |
🚀 如何使用 Structured Outputs(text.format
)
步骤 1:定义 JSON Schema
- 设计模型需遵循的 JSON Schema。
- 注意:并非所有 JSON Schema 功能都受支持,详见支持的 Schema
/docs/guides/structured-outputs#supported-schemas
。
Schema 设计建议:
- 键名清晰直观。
- 为重要键添加标题和描述。
- 通过实验评估最佳结构。
步骤 2:在 API 调用中提供 Schema
使用以下格式:
text={"format": {"type": "json_schema","name": "your_schema_name","schema": {...},"strict": True}
}
📚 总结
Structured Outputs 提供了强大的结构化响应能力,适用于多种场景,从数据提取到 UI 生成。相比 JSON 模式,它更可靠且功能更强大。通过合理设计 JSON Schema,您可以充分发挥其潜力,简化开发流程并提升响应一致性。
🎤 第五课重点:Function Calling 功能概览
使模型能够获取数据并执行操作。
函数调用(Function Calling) 为 OpenAI 模型提供了一种强大且灵活的方式,用于与您的代码或外部服务交互。本指南将讲解如何将模型连接到您的自定义代码,以获取数据或执行操作。
✅ 功能简介
函数调用允许模型根据系统提示和消息决定调用您定义的函数,而不是(或除了)生成文本或音频。您将执行函数代码,返回结果,模型会将其融入最终响应。
主要用例:
用例 | 描述 |
---|---|
获取数据 | 获取最新信息以融入模型响应(如 RAG),适用于搜索知识库或从 API 获取数据(如天气数据)。 |
执行操作 | 执行操作,如提交表单、调用 API、修改应用状态(UI/前端或后端)或执行代理工作流(如交接对话)。 |
🔌 函数调用步骤
- 定义函数并调用模型:在
tools
参数中提供函数 schema,连同系统和用户消息。 - 模型决定调用函数:返回函数名称和输入参数。
- 执行函数代码:解析模型响应并处理函数调用。
- 将结果返回模型:让模型将结果融入最终响应。
- 模型生成最终响应:包含函数调用结果。
🧪 示例代码
1. 获取天气(get_weather)
从指定位置获取当前温度。
✅ Python 版本
from openai import OpenAI
import jsonclient = OpenAI()tools = [{"type": "function","name": "get_weather","description": "Get current temperature for provided coordinates in celsius.","parameters": {"type": "object","properties": {"latitude": {"type": "number"},"longitude": {"type": "number"}},"required": ["latitude", "longitude"],"additionalProperties": False},"strict": True
}]input_messages = [{"role": "user", "content": "What's the weather like in Paris today?"}]response = client.responses.create(model="gpt-4.1",input=input_messages,tools=tools
)tool_call = response.output[0]
args = json.loads(tool_call.arguments)# 假设 get_weather 函数已实现
result = get_weather(args["latitude"], args["longitude"])input_messages.append(tool_call)
input_messages.append({"type": "function_call_output","call_id": tool_call.call_id,"output": str(result)
})response_2 = client.responses.create(model="gpt-4.1",input=input_messages,tools=tools
)print(response_2.output_text)
示例输出
"The current temperature in Paris is 14°C (57.2°F)."
2. 发送邮件(send_email)
向指定收件人发送邮件。
✅ Python 版本
from openai import OpenAI
import jsonclient = OpenAI()tools = [{"type": "function","name": "send_email","description": "Send an email to a given recipient with a subject and message.","parameters": {"type": "object","properties": {"to": {"type": "string", "description": "The recipient email address."},"subject": {"type": "string", "description": "Email subject line."},"body": {"type": "string", "description": "Body of the email message."}},"required": ["to", "subject", "body"],"additionalProperties": False},"strict": True
}]input_messages = [{"role": "user", "content": "Can you send an email to ilan@example.com saying hi?"}]response = client.responses.create(model="gpt-4.1",input=input_messages,tools=tools
)for tool_call in response.output:if tool_call.type != "function_call":continueargs = json.loads(tool_call.arguments)result = send_email(**args) # 假设 send_email 函数已实现input_messages.append({"type": "function_call_output","call_id": tool_call.call_id,"output": str(result)})response_2 = client.responses.create(model="gpt-4.1",input=input_messages,tools=tools
)print(response_2.output_text)
示例输出
"Email sent to ilan@example.com."
3. 搜索知识库(search_knowledge_base)
查询知识库以获取相关信息。
✅ Python 版本
from openai import OpenAI
import jsonclient = OpenAI()tools = [{"type": "function","name": "search_knowledge_base","description": "Query a knowledge base to retrieve relevant info on a topic.","parameters": {"type": "object","properties": {"query": {"type": "string", "description": "The user question or search query."},"options": {"type": "object","properties": {"num_results": {"type": "number", "description": "Number of top results to return."},"domain_filter": {"type": ["string", "null"],"description": "Optional domain to narrow the search (e.g. 'finance')."},"sort_by": {"type": ["string", "null"],"enum": ["relevance", "date", "popularity", "alphabetical"],"description": "How to sort results."}},"required": ["num_results", "domain_filter", "sort_by"],"additionalProperties": False}},"required": ["query", "options"],"additionalProperties": False},"strict": True
}]input_messages = [{"role": "user", "content": "Can you find information about ChatGPT in the AI knowledge base?"}]response = client.responses.create(model="gpt-4.1",input=input_messages,tools=tools
)tool_call = response.output[0]
args = json.loads(tool_call.arguments)
result = search_knowledge_base(**args) # 假设函数已实现input_messages.append(tool_call)
input_messages.append({"type": "function_call_output","call_id": tool_call.call_id,"output": str(result)
})response_2 = client.responses.create(model="gpt-4.1",input=input_messages,tools=tools
)print(response_2.output_text)
示例输出
"ChatGPT is a conversational AI model developed by OpenAI, based on the GPT architecture."
🧠 定义函数
函数通过 tools
参数中的 schema 定义,包含以下字段:
字段 | 描述 |
---|---|
type | 始终为 function 。 |
name | 函数名称(如 get_weather )。 |
description | 函数用途及使用场景。 |
parameters | JSON Schema,定义函数输入参数。 |
strict | 是否启用严格模式,确保遵循 schema。 |
定义最佳实践:
- 清晰描述:为函数和参数提供明确的目的、格式和输出说明。
- 软件工程实践:
- 确保函数直观(遵循最小惊讶原则)。
- 使用枚举和对象结构避免无效状态。
- 通过“实习生测试”:仅凭 schema 是否能正确使用函数?
- 减轻模型负担:
- 已知参数无需让模型填写。
- 将总是连续调用的函数合并。
- 控制函数数量:
- 建议少于 20 个函数以提高准确性。
- 通过实验评估不同函数数量的性能。
- 利用 OpenAI 资源:
- 在 Playground
/playground
生成和迭代 schema。 - 考虑微调
/docs/guides/fine-tuning
以提高大量函数的调用准确性。
- 在 Playground
🚀 处理函数调用
模型可能返回零个、一个或多个函数调用。响应中的 output
数组包含 type: function_call
的条目,每个条目包括 call_id
、 name
和 JSON 编码的 arguments
。
处理示例
for tool_call in response.output:if tool_call.type != "function_call":continuename = tool_call.nameargs = json.loads(tool_call.arguments)result = call_function(name, args)input_messages.append({"type": "function_call_output","call_id": tool_call.call_id,"output": str(result)})response_2 = client.responses.create(model="gpt-4.1",input=input_messages,tools=tools
)
结果格式
- 结果必须是字符串(可为 JSON、错误代码、纯文本等)。
- 无返回值函数(如
send_email
)可返回"success"
或错误提示。
⚙️ 高级配置
工具选择(tool_choice)
控制模型调用工具的行为:
auto
(默认):调用 0 个、1 个或多个函数。required
:至少调用 1 个函数。{"type": "function", "name": "get_weather"}
:强制调用指定函数。none
:禁用函数调用。
并行函数调用
默认支持并行调用多个函数。可通过设置 parallel_tool_calls: false
限制为 0 或 1 次调用。
注意:
- 并行调用时,严格模式可能被禁用。
- 对于
gpt-4.1-nano-2025-04-14
,建议禁用并行调用以避免重复调用同一工具。
严格模式
设置 strict: true
确保函数调用严格遵循 schema,需满足:
- 每个对象设置
additionalProperties: false
。 properties
中的字段标记为required
(可选字段可使用type: ["string", "null"]
)。
🌊 流式处理
流式处理可实时显示函数调用进度,包括函数名称和参数填充。
示例
stream = client.responses.create(model="gpt-4.1",input=[{"role": "user", "content": "What's the weather like in Paris today?"}],tools=tools,stream=True
)final_tool_calls = {}
for event in stream:if event.type == "response.output_item.added":final_tool_calls[event.output_index] = event.itemelif event.type == "response.function_call_arguments.delta":index = event.output_indexif final_tool_calls[index]:final_tool_calls[index].arguments += event.delta
输出事件
response.output_item.added
:函数调用开始。response.function_call_arguments.delta
:参数逐步填充。response.function_call_arguments.done
:函数调用完成。
🧭 使用场景推荐指南
场景 | 推荐函数 |
---|---|
获取实时数据(如天气) | get_weather |
执行操作(如发送邮件) | send_email |
搜索知识库 | search_knowledge_base |
动态 UI 交互 | 自定义函数(如 update_ui ) |
📚 总结
函数调用为模型提供了与外部代码和服务交互的能力,适用于数据获取和操作执行。通过清晰的 schema 定义、严格模式和流式处理,您可以构建高效、可靠的交互系统。结合 Playground 和微调工具,进一步优化函数调用性能。
🎤 第六课重点:Conversation State 功能概览
学习如何在模型交互中管理会话状态。
OpenAI 提供了多种管理会话状态的方法,这对于在多轮对话中保留信息至关重要。本课将介绍如何通过手动管理或利用 API 自动管理会话状态,以确保对话的连贯性和上下文保持。
✅ 功能简介
会话状态管理用于在多条消息或多轮对话中保留上下文。OpenAI 的文本生成请求默认是无状态的(除非使用Assistants API/docs/assistants/overview
),但可以通过以下方式实现多轮对话:
- 手动管理:通过在每次请求中传递历史消息来构建会话上下文。
- API 自动管理:使用
previous_response_id
参数实现上下文的自动传递。
🧪 手动管理会话状态
通过在请求中包含历史消息(交替的 user
和 assistant
消息),可以模拟多轮对话。以下是一个敲敲门笑话的示例:
✅ Python 版本
from openai import OpenAIclient = OpenAI()response = client.responses.create(model="gpt-4o-mini",input=[{"role": "user", "content": "knock knock."},{"role": "assistant", "content": "Who's there?"},{"role": "user", "content": "Orange."},],
)print(response.output_text)
示例输出
Orange you glad I'm here?
手动管理多轮对话
通过将模型的先前响应追加到历史记录中,可以在后续请求中保留上下文。以下示例展示了请求模型讲一个笑话,然后再讲一个:
✅ Python 版本
from openai import OpenAIclient = OpenAI()history = [{"role": "user", "content": "tell me a joke"}]response = client.responses.create(model="gpt-4o-mini",input=history,store=False
)print(response.output_text)# 将响应添加到历史记录
history += [{"role": el.role, "content": el.content} for el in response.output]
history.append({"role": "user", "content": "tell me another"})second_response = client.responses.create(model="gpt-4o-mini",input=history,store=False
)print(second_response.output_text)
示例输出
Why did the scarecrow become a motivational speaker? Because he was outstanding in his field!
Another one? Alright! Why did the tomato turn red? Because it saw the salad dressing!
🚀 使用 OpenAI API 管理会话状态
通过 previous_response_id
参数,API 可以自动管理会话状态,简化上下文传递。以下示例展示了一个笑话及其解释的场景:
✅ Python 版本
from openai import OpenAIclient = OpenAI()response = client.responses.create(model="gpt-4o-mini",input="tell me a joke",
)print(response.output_text)second_response = client.responses.create(model="gpt-4o-mini",previous_response_id=response.id,input=[{"role": "user", "content": "explain why this is funny."}],
)print(second_response.output_text)
示例输出
Why did the chicken cross the road? To get to the other side!
The humor comes from the simplicity and expectation. The setup leads you to anticipate a complex answer, but the punchline is deliberately obvious, creating a humorous contrast.
注意:即使使用 previous_response_id
,链中所有之前的输入 token 都会作为输入 token 计费。
🧠 管理上下文窗口
理解上下文窗口是成功管理会话状态的关键。上下文窗口 是单次请求中可使用的最大 token 数,包括输入、输出和推理 token。不同模型的上下文窗口大小不同(参见model details/docs/models
)。
关键概念
- 输出 token:模型生成的响应 token。例如,
gpt-4o-2024-08-06
最多生成 16,384 个输出 token。 - 上下文窗口:包括输入、输出和推理 token 的总数。例如,
gpt-4o-2024-08-06
的上下文窗口为 128k token。 - 推理 token:某些模型(如 o1 model
/docs/guides/reasoning
)用于规划响应的 token。
如果输入过大(例如包含过多上下文或示例),可能超出上下文窗口,导致输出截断。
管理上下文的建议
- 使用 tokenizer tool
/tokenizer
或 tiktoken 库https://github.com/openai/tiktoken
估算消息的 token 数量。 - 避免不必要的冗长上下文,定期修剪历史记录。
- 如果接近上下文窗口限制,考虑:
- 缩短输入消息。
- 移除较旧的对话历史。
- 使用更高效的模型(如
gpt-4o-mini
)。
🧪 高级用例:结合函数调用
结合函数调用/docs/guides/function-calling
和会话状态管理,可以构建更复杂的交互。以下示例展示了一个天气查询对话,保留上下文并调用 get_weather
函数:
✅ Python 版本
from openai import OpenAI
import jsonclient = OpenAI()tools = [{"type": "function","name": "get_weather","description": "Get current temperature for provided coordinates in celsius.","parameters": {"type": "object","properties": {"latitude": {"type": "number"},"longitude": {"type": "number"}},"required": ["latitude", "longitude"],"additionalProperties": False},"strict": True
}]history = [{"role": "user", "content": "What's the weather like in Paris today?"}]response = client.responses.create(model="gpt-4o-mini",input=history,tools=tools
)tool_call = response.output[0]
args = json.loads(tool_call.arguments)
result = get_weather(args["latitude"], args["longitude"]) # 假设函数已实现history.append(tool_call)
history.append({"type": "function_call_output","call_id": tool_call.call_id,"output": str(result)
})history.append({"role": "user", "content": "How about London?"})second_response = client.responses.create(model="gpt-4o-mini",input=history,tools=tools
)print(second_response.output_text)
示例输出
The current temperature in London is 12°C (53.6°F).
🧭 使用场景推荐指南
场景 | 推荐方法 |
---|---|
简单多轮对话(如讲笑话) | 手动管理历史消息 |
复杂上下文保留(如连续查询) | 使用 previous_response_id |
结合外部数据(如天气查询) | 结合函数调用和历史管理 |
实时交互 | 结合流式处理/docs/guides/streaming-responses |
🚀 下一步
- 探索 OpenAI Cookbook:
https://cookbook.openai.com
中的具体示例和用例。 - 深入学习相关功能:
- Structured Outputs:
/docs guides/structured-outputs
生成 JSON 响应。 - Function Calling
/docs/guides/function-calling
扩展模型功能。 - Streaming Responses:
/docs/guides/streaming-responses
实现实时响应。 - Tools and Computer Use:
/docs/guides/tools-computer-use
构建复杂代理。
- Structured Outputs:
📚 总结
会话状态管理是构建连贯多轮对话的关键。通过手动管理历史消息或使用 previous_response_id
参数,您可以轻松保留上下文。结合上下文窗口管理和函数调用,可以创建更智能、动态的交互体验。使用 tokenizer 工具优化 token 使用,确保高效利用模型能力。
🎤 第七课重点:Streaming API Responses 功能概览
学习如何使用服务器端事件(Server-Sent Events)从 OpenAI API 流式传输模型响应。
默认情况下,OpenAI API 在生成完整模型输出后,通过单个 HTTP 响应返回结果。对于长输出,等待完整响应可能耗时较长。流式响应允许在模型生成完整响应的同时,开始打印或处理输出的开头部分,从而提升用户体验。
✅ 功能简介
流式响应通过设置 stream=True
启用,API 将以事件流的形式逐步发送模型输出。每个事件都遵循预定义的 schema,支持语义化事件监听,适合实时处理模型响应。
主要优势:
- 实时性:立即处理模型输出的初始部分,减少等待时间。
- 灵活性:支持文本、函数调用和结构化输出的流式处理。
- 事件驱动:通过类型化事件监听特定响应阶段。
🧪 启用流式响应
通过在 Responses 端点请求中设置 stream=True
,即可启用流式响应。以下是一个示例,要求模型快速重复短语“double bubble bath”十次:
✅ Python 版本
from openai import OpenAIclient = OpenAI()stream = client.responses.create(model="gpt-4.1",input=[{"role": "user", "content": "Say 'double bubble bath' ten times fast."},],stream=True,
)for event in stream:print(event)
示例输出(事件流)
{"type": "response.created", "response_id": "resp_1234xyz", ...}
{"type": "response.output_text.delta", "response_id": "resp_1234xyz", "delta": "Double bubble bath, "}
{"type": "response.output_text.delta", "response_id": "resp_1234xyz", "delta": "double bubble bath, "}
...
{"type": "response.completed", "response_id": "resp_1234xyz", ...}
🚀 读取流式响应
流式响应使用语义化事件,每个事件通过 type
属性标识。OpenAI SDK 提供类型化事件实例,便于处理。以下是常见的生命周期事件:
事件类型 | 描述 | 触发次数 |
---|---|---|
response.created | 响应创建 | 1 次 |
response.output_text.delta | 输出文本增量 | 多次(每次生成文本片段) |
response.completed | 响应完成 | 1 次 |
error | 错误发生 | 0 或 1 次 |
处理文本流示例
以下代码展示如何监听文本增量事件并累积输出:
✅ Python 版本
from openai import OpenAIclient = OpenAI()stream = client.responses.create(model="gpt-4.1",input=[{"role": "user", "content": "Say 'double bubble bath' ten times fast."},],stream=True,
)full_text = ""
for event in stream:if event.type == "response.output_text.delta":full_text += event.deltaprint(full_text) # 实时打印累积文本elif event.type == "response.completed":print("Stream completed:", full_text)elif event.type == "error":print("Error:", event.error)
示例输出
Double bubble bath,
Double bubble bath, double bubble bath,
...
Stream completed: Double bubble bath, double bubble bath, ... (10 times)
完整事件列表参见 API reference for streaming/docs/api-reference/responses-streaming
。
🧠 高级用例
1. 流式函数调用
流式处理函数调用可以实时显示函数名称和参数填充过程。参见Streaming Function Calls/docs/guides/function-calling#streaming
。
示例
from openai import OpenAIclient = OpenAI()tools = [{"type": "function","name": "get_weather","description": "Get current temperature for a given location.","parameters": {"type": "object","properties": {"location": {"type": "string", "description": "City and country e.g. Bogotá, Colombia"}},"required": ["location"],"additionalProperties": False}
}]stream = client.responses.create(model="gpt-4.1",input=[{"role": "user", "content": "What's the weather like in Paris today?"}],tools=tools,stream=True
)final_tool_calls = {}
for event in stream:if event.type == "response.output_item.added":final_tool_calls[event.output_index] = event.itemelif event.type == "response.function_call_arguments.delta":index = event.output_indexif final_tool_calls[index]:final_tool_calls[index].arguments += event.deltaprint(f"Function call arguments: {final_tool_calls[index].arguments}")
示例输出
Function call arguments: {"location":"Paris
Function call arguments: {"location":"Paris, France"}
2. 流式结构化输出
流式处理结构化输出(如 JSON Schema)适用于需要实时解析的场景。参见 Streaming Structured Output/docs/guides/structured-outputs#streaming
。
示例
from openai import OpenAIclient = OpenAI()stream = client.responses.create(model="gpt-4o-2024-08-06",input=[{"role": "user", "content": "Extract event info: Alice and Bob are going to a science fair on Friday."}],text={"format": {"type": "json_schema","name": "calendar_event","schema": {"type": "object","properties": {"name": {"type": "string"},"date": {"type": "string"},"participants": {"type": "array", "items": {"type": "string"}}},"required": ["name", "date", "participants"],"additionalProperties": False},"strict": True}},stream=True
)full_json = ""
for event in stream:if event.type == "response.output_text.delta":full_json += event.deltaprint(f"Partial JSON: {full_json}")
示例输出
Partial JSON: {"name":"Science Fair"
Partial JSON: {"name":"Science Fair","date":"Friday"
...
⚠️ 内容审核风险
在生产环境中流式传输模型输出可能增加内容审核难度,因为部分完成的内容难以评估。这可能影响某些使用场景的合规性。建议:
- 对流式输出实施实时监控。
- 在敏感应用中结合Moderation API
/docs/guides/moderation
进行内容检查。
🧭 使用场景推荐指南
场景 | 推荐方法 |
---|---|
实时文本生成(如聊天界面) | 监听 response.output_text.delta |
实时函数调用(如动态工具交互) | 监听 response.function_call_arguments.delta |
实时结构化数据提取 | 监听 response.output_text.delta 并解析 JSON |
低延迟用户体验 | 结合流式响应和前端优化 |
🚀 下一步
- 探索OpenAI Cookbook:
https://cookbook.openai.com
中的流式响应示例。 - 深入学习相关功能:
- Streaming Function Calls:
/docs/guides/function-calling#streaming
- Streaming Structured Outputs:
/docs/guides/structured-outputs#streaming
- Conversation State Management:
/docs/guides/conversation-state
- Moderation API:
/docs/guides/moderation
- Streaming Function Calls:
📚 总结
流式 API 响应通过服务器端事件提供实时、低延迟的模型输出,适合聊天界面、动态工具调用和结构化数据提取等场景。通过监听语义化事件,您可以精确处理响应生命周期。注意内容审核风险,并在生产环境中结合适当的监控机制以确保合规性。
🎤 第八课重点:File Inputs 功能概览
学习如何将 PDF 文件作为 OpenAI API 的输入。
支持视觉能力的 OpenAI 模型可以接受 PDF 文件作为输入。您可以通过 Base64 编码数据或通过Files API/docs/api-reference/files
或 仪表板/storage/files/
上传文件后获取的文件 ID 提供 PDF。
✅ 功能简介
为了帮助模型理解 PDF 内容,API 会将提取的文本和每页的图像放入模型的上下文。模型可以利用文本和图像生成响应,特别适合包含图表等非文本关键信息的场景。
主要优势:
- 多模态处理:结合文本和图像,全面理解 PDF 内容。
- 灵活输入:支持通过文件 ID 或 Base64 编码上传。
- 广泛应用:适用于文档分析、数据提取等场景。
🧪 如何使用 PDF 输入
1. 上传文件并使用文件 ID
通过Files API/docs/api-reference/files
上传 PDF 文件,获取文件 ID,然后在模型请求中引用该 ID。
✅ Python 版本
from openai import OpenAIclient = OpenAI()# 上传 PDF 文件
file = client.files.create(file=open("draconomicon.pdf", "rb"),purpose="user_data"
)# 使用文件 ID 请求模型
response = client.responses.create(model="gpt-4.1",input=[{"role": "user","content": [{"type": "input_file","file_id": file.id,},{"type": "input_text","text": "What is the first dragon in the book?",},]}]
)print(response.output_text)
示例输出
The first dragon in the book "Draconomicon" is the Red Dragon.
2. 使用 Base64 编码文件
直接将 PDF 文件编码为 Base64 格式,作为输入提供。
✅ Python 版本
import base64
from openai import OpenAIclient = OpenAI()# 读取并编码 PDF 文件
with open("draconomicon.pdf", "rb") as f:data = f.read()
base64_string = base64.b64encode(data).decode("utf-8")# 使用 Base64 编码请求模型
response = client.responses.create(model="gpt-4.1",input=[{"role": "user","content": [{"type": "input_file","filename": "draconomicon.pdf","file_data": f"data:application/pdf;base64,{base64_string}",},{"type": "input_text","text": "What is the first dragon in the book?",},]}]
)print(response.output_text)
示例输出
The first dragon in the book "Draconomicon" is the Red Dragon.
🧠 使用注意事项
Token 使用
- 模型会同时处理 PDF 的提取文本和每页图像(即使页面无图像),这会增加 token 消耗。
- 在大规模部署前,了解定价和 token 使用
/docs/pricing
的影响。
文件大小限制
- 单次请求支持最多 100 页和 32MB 的总内容(可包含多个文件输入)。
支持的模型
- 仅支持同时处理文本和图像的模型,如
gpt-4o
、gpt-4o-mini
和o1
。参见模型功能/docs/models
。
文件上传用途
- 建议使用
user_data
作为上传文件的purpose
,但其他用途也支持。参见Files API 用途/docs/api-reference/files/create#files-create-purpose
。
🧪 高级用例:结合结构化输出
结合结构化输出/docs/guides/structured-outputs
,可以从 PDF 中提取特定信息并以 JSON 格式返回。
✅ Python 版本
from openai import OpenAIclient = OpenAI()file = client.files.create(file=open("draconomicon.pdf", "rb"),purpose="user_data"
)response = client.responses.create(model="gpt-4.1",input=[{"role": "user","content": [{"type": "input_file","file_id": file.id,},{"type": "input_text","text": "Extract the name and description of the first dragon.",},]}],text={"format": {"type": "json_schema","name": "dragon_info","schema": {"type": "object","properties": {"name": {"type": "string"},"description": {"type": "string"}},"required": ["name", "description"],"additionalProperties": False},"strict": True}}
)print(response.output_text)
示例输出
{"name": "Red Dragon","description": "A fierce and powerful creature with crimson scales, known for its fiery breath and territorial nature."
}
🧭 使用场景推荐指南
场景 | 推荐方法 |
---|---|
文档内容分析 | 使用文件 ID 上传 PDF,结合文本查询 |
实时文档处理 | 使用 Base64 编码,适合小型文件 |
结构化数据提取 | 结合结构化输出,提取特定信息 |
图表或图像分析 | 利用模型的视觉能力处理 PDF 图像 |
🚀 下一步
- 在Playground
/playground
中实验 PDF 输入,优化提示设计。 - 查看API 参考
/docs/api-reference/responses
获取更多选项。 - 探索相关功能:
- Structured Outputs:
/docs/guides/structured-outputs
生成 JSON 响应。 - Conversation State Management:
/docs/guides/conversation-state
管理多轮对话。 - Streaming Responses:
/docs/guides/streaming-responses
实时处理输出。
- Structured Outputs:
📚 总结
通过文件 ID 或 Base64 编码,OpenAI API 支持将 PDF 文件作为输入,结合文本和图像处理能力,适用于文档分析和信息提取。注意 token 消耗和文件大小限制,合理选择支持视觉的模型。结合结构化输出和流式处理,可以进一步提升 PDF 输入的处理效率和应用场景。
🎤 第九课重点:Reasoning Models 功能概览
探索高级推理和问题解决模型。
推理模型(如 o3
和 o4-mini
)是通过强化学习训练的大型语言模型(LLMs),能够进行推理。这些模型在回答前会进行深入思考,生成内部推理链(chain of thought),在复杂问题解决、编码、科学推理和多步骤代理工作流规划中表现出色。它们也是 Codex CLI https://github.com/openai/codex
等轻量级编码代理的最佳选择。
与 GPT 系列类似,OpenAI 提供更小、更快的模型(如 o4-mini
和 o3-mini
),每 token 成本较低。大型模型(如 o3
和 o1
)速度较慢、成本较高,但在复杂任务和广泛领域中通常生成更优响应。
为确保安全部署最新推理模型(o3
和 o4-mini
),部分开发者需完成组织验证https://help.openai.com/en/articles/10910291-api-organization-verification
。可在平台设置页面https://platform.openai.com/settings/organization/general
开始验证。
✅ 开始使用推理模型
推理模型通过Responses API/docs/api-reference/responses/create
使用。以下是一个示例,要求模型编写一个转置矩阵的 Bash 脚本:
✅ Python 版本
from openai import OpenAIclient = OpenAI()prompt = """
Write a bash script that takes a matrix represented as a string with
format '[1,2],[3,4],[5,6]' and prints the transpose in the same format.
"""response = client.responses.create(model="o4-mini",reasoning={"effort": "medium"},input=[{"role": "user", "content": prompt}]
)print(response.output_text)
示例输出
#!/bin/bashinput="$1"
# Remove outer brackets and split rows
rows=$(echo "$input" | tr -d '[]' | tr ',' '\n' | sed 's/][/\n/g')
# Get number of rows and columns
num_rows=$(echo "$rows" | wc -l)
num_cols=$(echo "$rows" | head -n 1 | tr ',' '\n' | wc -l)# Initialize output array
declare -A matrix
row=0
for r in $rows; doIFS=',' read -ra cols <<< "$r"for col in "${!cols[@]}"; domatrix[$row,$col]=${cols[$col]}done((row++))
done# Print transposed matrix
for ((col=0; col<num_cols; col++)); dorow_output=""for ((row=0; row<num_rows; row++)); dorow_output+="${matrix[$row,$col]},"doneecho -n "[${row_output%,}],"
done | sed 's/,$//'
🧠 推理模型工作原理
推理模型引入了 推理 token,除了输入和输出 token 外,模型使用推理 token 进行“思考”,分解提示并探索多种生成响应的方法。推理完成后,模型生成可见的输出 token,并从上下文中丢弃推理 token。
推理 token 特点
- 不可见:推理 token 不通过 API 返回,但占用上下文窗口空间。
- 计费:推理 token 按输出 token
https://openai.com/api/pricing
计费。 - 数量:根据任务复杂性,推理 token 可能从几百到几万个不等,具体数量在响应对象的
usage.output_tokens_details.reasoning_tokens
中可见。
示例 usage 对象
{"usage": {"input_tokens": 75,"input_tokens_details": {"cached_tokens": 0},"output_tokens": 1186,"output_tokens_details": {"reasoning_tokens": 1024},"total_tokens": 1261}
}
上下文窗口管理
- 上下文窗口大小因模型而异(参见模型参考
/docs/models
)。 - 复杂任务可能生成大量推理 token,需确保上下文窗口有足够空间。
- 建议初始实验时为推理和输出保留至少 25,000 个 token,随后根据实际需求调整。
控制成本
- 使用
max_output_tokens``/docs/api-reference/responses/create#responses-create-max_output_tokens
参数限制总 token 数(包括推理和输出 token)。 - 手动管理上下文时,除非响应函数调用,否则可丢弃较旧的推理项。
处理不完整响应
如果生成 token 达到上下文窗口或 max_output_tokens
限制,响应状态将为 incomplete
,可能无可见输出。
示例处理
from openai import OpenAIclient = OpenAI()prompt = """
Write a bash script that takes a matrix represented as a string with
format '[1,2],[3,4],[5,6]' and prints the transpose in the same format.
"""response = client.responses.create(model="o4-mini",reasoning={"effort": "medium"},input=[{"role": "user", "content": prompt}],max_output_tokens=300
)if response.status == "incomplete" and response.incomplete_details.reason == "max_output_tokens":print("Ran out of tokens")if response.output_text:print("Partial output:", response.output_text)else:print("Ran out of tokens during reasoning")
🚀 推理总结(Reasoning Summaries)
虽然推理 token 不可见,但可以通过 reasoning.summary
参数查看模型推理的总结。不同模型支持不同总结器(如 o4-mini
支持 detailed
,计算机使用模型支持 concise
)。设置 summary: "auto"
可获取最详细的可用总结。
示例配置
{"reasoning": {"effort": "medium","summary": "auto"}
}
总结作为 reasoning
输出项的 summary
数组返回,支持流式处理,适用于 o4-mini
、o3
、o3-mini
和 o1
模型。
注意:使用最新推理模型的总结功能可能需要完成组织验证https://help.openai.com/en/articles/10910291-api-organization-verification
。
🧪 提示设计建议
推理模型与 GPT 模型的提示设计有所不同:
- 推理模型:像高级同事,只需提供高层次目标,模型会自行推导细节。
- GPT 模型:像初级同事,需要明确、具体的指令。
最佳实践
- 提供清晰的目标,避免过于详细的步骤说明。
- 对于复杂任务,利用推理模型的规划能力。
- 参考推理最佳实践指南
/docs/guides/reasoning-best-practices
。
示例提示
1. 编码(代码重构)
要求 o4-mini
重构 React 组件,使非虚构书籍显示为红色文本。
from openai import OpenAIclient = OpenAI()prompt = """
Instructions:
- Given the React component below, change it so that nonfiction books have red text.
- Return only the code in your reply
- Do not include any additional formatting, such as markdown code blocks
- For formatting, use four space tabs, and do not allow any lines of code to exceed 80 columnsconst books = [{ title: 'Dune', category: 'fiction', id: 1 },{ title: 'Frankenstein', category: 'fiction', id: 2 },{ title: 'Moneyball', category: 'nonfiction', id: 3 },
];export default function BookList() {const listItems = books.map(book =><li>{book.title}</li>);return (<ul>{listItems}</ul>);
}
"""response = client.responses.create(model="o4-mini",input=[{"role": "user", "content": prompt}]
)print(response.output_text)
示例输出
const books = [{ title: 'Dune', category: 'fiction', id: 1 },{ title: 'Frankenstein', category: 'fiction', id: 2 },{ title: 'Moneyball', category: 'nonfiction', id: 3 },
];export default function BookList() {const listItems = books.map(book =><li style={{ color: book.category === 'nonfiction' ? 'red' : 'black' }}>{book.title}</li>);return (<ul>{listItems}</ul>);
}
2. 编码(项目规划)
要求 o4-mini
为 Python 应用设计文件结构并提供完整代码。
from openai import OpenAIclient = OpenAI()prompt = """
I want to build a Python app that takes user questions and looks them up in a database
where they are mapped to answers. If there is a close match, it retrieves the matched
answer. If there isn't, it asks the user to provide an answer and stores the
question/answer pair in the database. Make a plan for the directory structure you'll
need, then return each file in full. Only supply your reasoning at the beginning and end,
not throughout the code.
"""response = client.responses.create(model="o4-mini",input=[{"role": "user", "content": prompt}]
)print(response.output_text)
示例输出(简化)
Reasoning: The app requires a database, question matching logic, and user interaction.
A simple directory structure with SQLite for persistence and fuzzy matching for
question lookup is suitable.Directory structure:
- qa_app/- main.py- database.py- matcher.py=== main.py ===
import database
import matcher
...=== database.py ===
import sqlite3
...=== matcher.py ===
from fuzzywuzzy import fuzz
...Reasoning: The structure separates concerns (database, matching, UI) and uses SQLite
for simplicity and fuzzywuzzy for question matching.
3. STEM 研究
要求 o4-mini
推荐抗生素研究化合物。
from openai import OpenAIclient = OpenAI()prompt = """
What are three compounds we should consider investigating to advance research into
new antibiotics? Why should we consider them?
"""response = client.responses.create(model="o4-mini",input=[{"role": "user", "content": prompt}]
)print(response.output_text)
示例输出
1. Teixobactin: A novel antibiotic discovered in 2015, effective against Gram-positive
bacteria like MRSA. Its unique mechanism targeting lipid II and lipid III makes it
promising for overcoming resistance.
2. Halicin: Identified via AI-driven screening, it shows broad-spectrum activity and a
novel mechanism disrupting bacterial membrane potential, reducing resistance likelihood.
3. Odilorhabdins: These target bacterial protein synthesis differently from existing
antibiotics, offering potential against multidrug-resistant Gram-negative bacteria.
🧭 使用场景推荐指南
场景 | 推荐方法 |
---|---|
复杂编码任务(如算法实现) | 使用 o4-mini 或 o3 ,设置 effort: high |
项目规划(如文件结构设计) | 使用 o4-mini 提供高层次目标 |
科学推理(如抗生素研究) | 使用 o3 或 o1 进行深入分析 |
数据验证 | 结合 Cookbook 示例 https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation |
🚀 下一步
- 探索 OpenAI Cookbook: `https://cookbook.openai.com) 中的推理模型用例:
- 数据验证:
https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation
- 例程生成:
https://cookbook.openai.com/examples/o1/using_reasoning_for_routine_generation
- 数据验证:
- 深入学习相关功能:
- Function Calling:
/docs/guides/function-calling
扩展推理模型能力。 - Conversation State Management:
/docs/guides/conversation-state
管理多轮对话。 - Streaming Responses:
/docs/guides/streaming-responses
实时处理输出。
- Function Calling:
📚 总结
推理模型(如 o3 和 o4-mini)通过强化学习优化复杂推理任务,适合编码、科学推理和多步骤规划。推理 token 增强了模型的思考能力,但需注意上下文窗口和成本管理。使用高层次提示和推理总结可充分发挥模型潜力,结合 Cookbook 示例可快速应用于实际场景。
🎤 第十课重点:Evaluating Model Performance 功能概览
通过评估测试和改进模型输出。
评估(Evaluations,简称 evals) 用于测试模型输出是否符合您指定的风格和内容标准。编写评估以了解 LLM 应用的表现,特别是在升级或尝试新模型时,是构建可靠应用的关键。本指南聚焦于使用Evals API/docs/api-reference/evals
编程配置评估,您也可以通过OpenAI 仪表板/evaluations
配置评估。
评估过程包括三个步骤:
- 描述要执行的任务作为评估。
- 使用测试输入(提示和输入数据)运行评估。
- 分析结果,迭代优化提示。
此过程类似于行为驱动开发(BDD),先指定系统行为,再实现和测试系统。
✅ 创建评估任务
创建评估需描述模型要执行的任务。假设我们要使用模型将 IT 支持工单分类为 Hardware
、Software
或 Other
。
以下是一个使用Chat Completions API/docs/api-reference/chat
实现此用例的示例,结合开发者指令和用户提供的工单文本:
✅ Python 版本
from openai import OpenAIclient = OpenAI()instructions = """
You are an expert in categorizing IT support tickets. Given the support
ticket below, categorize the request into one of "Hardware", "Software",
or "Other". Respond with only one of those words.
"""ticket = "My monitor won't turn on - help!"completion = client.chat.completions.create(model="gpt-4.1",messages=[{"role": "developer", "content": instructions},{"role": "user", "content": ticket}]
)print(completion.choices[0].message.content)
示例输出
Hardware
创建评估
通过 Evals API/docs/api-reference/evals
创建评估,需要:
- 数据源配置(
data_source_config
):定义测试数据的 schema。 - 测试标准(
testing_criteria
):确定模型输出是否正确的标准。
✅ Python 版本
from openai import OpenAIclient = OpenAI()eval_config = {"name": "IT Ticket Categorization","data_source_config": {"type": "custom","item_schema": {"type": "object","properties": {"ticket_text": {"type": "string"},"correct_label": {"type": "string"}},"required": ["ticket_text", "correct_label"]},"include_sample_schema": True},"testing_criteria": [{"type": "string_check","name": "Match output to human label","input": "{{ sample.output_text }}","operation": "eq","reference": "{{ item.correct_label }}"}]
}response = client.evals.create(**eval_config)
print(response)
示例输出
{"object": "eval","id": "eval_67e321d23b54819096e6bfe140161184","name": "IT Ticket Categorization","created_at": 1742938578,...
}
说明
- data_source_config:定义测试数据项的 JSON schema,每个项包含
ticket_text
(工单文本)和correct_label
(人工标注的正确分类)。include_sample_schema: True
允许引用模型生成的样本输出。 - testing_criteria:使用
string_check
检查模型输出 (sample.output_text
) 是否与正确标签 (item.correct_label
) 完全匹配。{{}}
语法用于插入动态内容。
🧪 测试提示与评估
创建评估后,使用测试数据和提示运行评估,验证模型表现。
上传测试数据
测试数据需符合评估中定义的 schema,通常以 JSONL https://jsonlines.org/
格式提供。以下是一个示例 tickets.jsonl
:
{"item": {"ticket_text": "My monitor won't turn on!", "correct_label": "Hardware"}}
{"item": {"ticket_text": "I'm in vim and I can't quit!", "correct_label": "Software"}}
{"item": {"ticket_text": "Best restaurants in Cleveland?", "correct_label": "Other"}}
通过Files API/docs/api-reference/files/create
上传测试数据:
✅ Python 版本
from openai import OpenAIclient = OpenAI()file = client.files.create(file=open("tickets.jsonl", "rb"),purpose="evals"
)print(file.id) # 记录文件 ID
示例输出
{"object": "file","id": "file-CwHg45Fo7YXwkWRPUkLNHW",...
}
创建评估运行
使用 Evals API 创建运行/docs/api-reference/evals/createRun
,指定评估 ID、测试数据文件 ID 和提示模板。
✅ Python 版本
from openai import OpenAIclient = OpenAI()run_config = {"name": "Categorization text run","data_source": {"type": "completions","model": "gpt-4.1","input": [{"role": "developer","content": "You are an expert in categorizing IT support tickets. Given the support ticket below, categorize the request into one of \"Hardware\", \"Software\", or \"Other\". Respond with only one of those words."},{"role": "user","content": "{{ item.ticket_text }}"}],"source": {"type": "file_id","id": "file-CwHg45Fo7YXwkWRPUkLNHW" # 替换为实际文件 ID}}
}response = client.evals.create_run(eval_id="eval_67e321d23b54819096e6bfe140161184", # 替换为实际评估 ID**run_config
)print(response)
示例输出
{"object": "eval.run","id": "evalrun_67e44c73eb6481909f79a457749222c7","eval_id": "eval_67e44c5becec81909704be0318146157","status": "queued",...
}
说明
- 提示模板使用
{{ item.ticket_text }}
动态插入测试数据中的工单文本。 - 运行将异步处理数据集的每行,生成模型响应并根据测试标准评估。
🚀 分析结果
评估运行可能需要时间,具体取决于数据集大小。您可以通过 仪表板/evaluations
查看状态,或通过 Evals API 获取运行状态/docs/api-reference/evals/getRun
✅ Python 版本
from openai import OpenAIclient = OpenAI()run_status = client.evals.get_run(eval_id="eval_67e321d23b54819096e6bfe140161184",run_id="evalrun_67e44c73eb6481909f79a457749222c7"
)print(run_status)
示例输出
{"object": "eval.run","id": "evalrun_67e44c73eb6481909f79a457749222c7","status": "completed","result_counts": {"total": 3,"errored": 0,"failed": 0,"passed": 3},"per_model_usage": [{"model_name": "gpt-4o-2024-08-06","prompt_tokens": 166,"completion_tokens": 6,"total_tokens": 172}],"per_testing_criteria_results": [{"testing_criteria": "Match output to human label-40d67441-5000-4754-ab8c-181c125803ce","passed": 3,"failed": 0}],"report_url": "https://platform.openai.com/evaluations/xxx",...
}
分析
- result_counts:显示通过、失败和错误的测试用例数量(本例中 3 个用例全部通过)。
- per_model_usage:提供模型的 token 使用情况,便于成本分析。
- report_url:链接到仪表板,供可视化结果探索。
如果评估显示失败用例,需检查失败的测试用例,调整提示或添加更多测试数据,然后重新运行评估。
🧠 高级用例:结合推理模型
结合推理模型/docs/guides/reasoning
可以增强评估的复杂任务处理能力。以下示例评估推理模型在工单分类中的表现
✅ Python 版本
from openai import OpenAIclient = OpenAI()run_config = {"name": "Reasoning Categorization Run","data_source": {"type": "completions","model": "o4-mini","input": [{"role": "developer","content": "Classify the IT support ticket into Hardware, Software, or Other. Provide only the category name."},{"role": "user","content": "{{ item.ticket_text }}"}],"source": {"type": "file_id","id": "file-CwHg45Fo7YXwkWRPUkLNHW"}},"reasoning": {"effort": "medium"}
}response = client.evals.create_run(eval_id="eval_67e321d23b54819096e6bfe140161184",**run_config
)print(response)
说明
- 使用
o4-mini
推理模型,设置reasoning.effort: medium
以平衡速度和推理深度。 - 提示更简洁,利用推理模型的自主推导能力。
🧭 使用场景推荐指南
场景 | 推荐方法 |
---|---|
提示优化 | 使用小数据集快速迭代提示,检查 result_counts |
模型比较 | 对不同模型运行相同评估,比较 per_model_usage 和通过率 |
复杂任务评估 | 结合推理模型,测试多步骤推理任务 |
回归测试 | 定期运行评估,检测提示或模型升级的性能退化 |
🚀 下一步
- 探索OpenAI Cookbook:
https://cookbook.openai.com
中的评估用例: - 检测提示回归:
https://cookbook.openai.com/examples/evaluation/use-cases/regression
- 批量模型和提示实验:
https://cookbook.openai.com/examples/evaluation/use-cases/bulk-experimentation
- 监控存储的完成:
https://cookbook.openai.com/examples/evaluation/use-cases/completion-monitoring
- 深入学习相关功能:
- Fine-tuning:
/docs/guides/fine-tuning
优化模型特定用例表现。 - Model Distillation: `/docs/guides/distillation将大模型结果蒸馏到小模型。
- Reasoning Models:
/docs/guides/reasoning
增强复杂任务处理。
- Fine-tuning:
📚 总结
评估(evals)是测试和改进 LLM 应用性能的关键工具。通过 Evals API,您可以定义任务、运行测试并分析结果,优化提示和模型选择。结合推理模型和仪表板可视化,评估过程更高效。定期运行评估,结合 Cookbook 示例,可确保应用在迭代和升级中保持可靠性和高质量输出。
通过这十节课相信大家会对openai的基础能力有一定的了解。同时这些也基本覆盖住了大模型生成式模型中日常所用到的底层工具。希望这些内容对大家有帮助。