首页
/ generative-ai-for-beginners 第6课:基于 OpenAI 客户端与 Responses API 构建文本生成应用

generative-ai-for-beginners 第6课:基于 OpenAI 客户端与 Responses API 构建文本生成应用

2026-09-06 20:45:06作者:廉皓灿Ida

本篇指南基于课程仓库的 06 课文档,系统讲解如何用 openai Python 库与 Responses API 从零搭建一个文本生成应用:从环境配置、密钥管理,到 Prompt 设计、max_output_tokenstemperature 调参,并通过仓库中配套的食谱生成器(recipe generator)完整实战代码,掌握“提示词迭代 + 多步提示 + 上下文传递”的核心技术。读完并动手完成后,你将具备独立构建食谱生成器、学习伙伴(study buddy)、历史角色问答机器人(history bot)等文本生成应用的能力。

1. 什么是文本生成应用

传统应用通常具备某种固定界面:

  • 命令式应用(Command-based):控制台输入命令、执行任务,例如 git
  • 图形界面应用(UI):点击按钮、输入文本、选择选项的 GUI。

这类应用存在两个固有局限:

  • 能力受限:只能执行应用预先支持的命令,无法任意输入;
  • 语言绑定:应用默认面向特定语言构建,扩展其他语言支持需要额外开发。

文本生成应用则不同:你不再受限于固定的命令集或输入语言,而是用自然语言与应用交互。另一个关键收益是:你直接对接的是一个在海量语料上训练过的数据源,而传统应用往往只能查询数据库里已有的有限内容。

典型的文本生成应用形态包括:

  • 聊天机器人:回答关于某主题(例如你的公司与产品)的问题;
  • 助手类应用:LLM 擅长文本摘要、从文本中提炼洞见、生成简历等文本产出;
  • 代码助手:视所选语言模型而定,可辅助编写代码。

2. 与 LLM 集成的两条路线:API 与 SDK

要把这种体验加入自己的应用,你需要理解 prompt、completion 等概念,并选择一个库来工作。集成的方式通常有两类:

  • 直接调用 API:用 prompt 构造 Web 请求,取回生成的文本;
  • 使用库/SDK:库对 API 调用做了封装,用起来更简单。

课程推荐的常用库包括:

  • openai:让连接模型并发送 prompt 变得简单(本课主线);
  • 更高层的框架:Langchain(知名、支持 Python)、Semantic Kernel(微软出品,支持 C#、Python、Java)。

本仓库 06 课同时提供了 Python 与 TypeScript 两套实现:Python 侧使用 openai 官方库(见 python 目录),TypeScript 侧使用 Azure AI Inference 的 REST 客户端(见 js-githubmodels/app.js)。

3. 环境准备:安装 openai 库与创建资源

3.1 安装 openai

交互 OpenAI / Azure OpenAI 的库很多,也支持 C#、Python、JavaScript、Java 等多种语言。课程选择 openai Python 库,用 pip 安装:

pip install openai

仓库中 06 课的依赖清单 锁定了具体版本,可直接复现:

openai==1.55.1
python-dotenv==1.2.2

3.2 创建 Azure OpenAI 资源

若走 Azure OpenAI(现已并入 Microsoft Foundry)路线,需要依次完成:

  1. 注册 Azure 免费账户(azure.microsoft.com/free);
  2. 申请 Azure OpenAI 的访问资格(提交 access 申请);
  3. 安装 Python;
  4. 在 Azure 门户创建 Azure OpenAI 服务资源并部署模型(部署名即后续代码中的 deployment)。

3.3 定位 API Key 与 Endpoint

在 Azure OpenAI 资源的 “Keys and Endpoint” 页签中,复制 Key 1 的值与资源端点。

值得把 API key 与代码分离,标准做法是使用环境变量,例如在终端执行 export OPENAI_API_KEY='sk-...',Azure 路线则设置 AZURE_OPENAI_API_KEYAZURE_OPENAI_ENDPOINT

os.environ 负责读取环境变量,也可用 dotenv 这类库从文件加载。仓库配套代码正是这么做的:aoai-app.py 开头先 load_dotenv() 再构造客户端;此外仓库还提供了通用的 shared/python/env_utils.py 工具模块,其中的 get_required_env() 会在环境变量缺失时抛出带提示信息(“请在 .env 文件中设置”)的 ValueError,避免带着空配置悄悄运行。

4. 配置客户端:标准 OpenAI 客户端指向 Azure OpenAI

如果走 Azure OpenAI(Microsoft Foundry)路线,仓库的做法是用标准 OpenAI 客户端指向 Azure OpenAI 的 /openai/v1/ 端点,该稳定 v1 端点同时兼容 OpenAI 与 Azure OpenAI,且无需管理 api_version

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AZURE_OPENAI_API_KEY"],
    base_url=f"{os.environ['AZURE_OPENAI_ENDPOINT'].rstrip('/')}/openai/v1/",
)
  • api_key:Azure Portal / Microsoft Foundry 门户中的 API key;
  • base_url:Foundry 资源端点加上 /openai/v1/ 后缀。

对照仓库源码可以印证细节:aoai-app.pyaoai-app-recipe.py 都是同样的 OpenAI(api_key=..., base_url=...) 写法,并通过 rstrip('/') 防止端点末尾斜杠造成双斜杠;而 oai-app.py 走纯 OpenAI 路线,直接 client = OpenAI()(API key 自动从 OPENAI_API_KEY 读取,不传 base_url),模型名固定为 gpt-4o-mini

5. 生成文本:Responses API 与多轮对话

生成文本的核心是 Responses APIresponses.create 方法:

prompt = "Complete the following: Once upon a time there was a"

response = client.responses.create(
    model="gpt-4o-mini",  # 模型(或部署)名
    input=prompt,
    store=False,
)
print(response.output_text)

要点说明:

  • model:Azure 路线填部署名(deployment),纯 OpenAI 路线填模型名如 gpt-4o-mini
  • input:本次请求的提示词(字符串,或消息列表);
  • store=False:不落盘存储本次响应,适合无状态调用;
  • response.output_text:直接取出模型生成的文本。

关于多轮对话:Responses API 同样适用于单轮文本生成与多轮聊天机器人,通过 input 传入消息列表即可累积会话上下文。真正的多轮聊天实现在课程第 7 课(07 课文档)展开,本篇聚焦单轮生成。

6. 练习一:你的第一个文本生成应用

6.1 创建虚拟环境并安装依赖

python -m venv venv
source venv/bin/activate
pip install openai

Windows 下请用 venv\Scripts\activate 代替 source venv/bin/activate

同时到 Azure 门户搜索 Open AI,选中你的资源,进入 Keys and Endpoint 复制 Key 1

6.2 编写 app.py

import os
from openai import OpenAI

client = OpenAI(
    api_key="<替换为你的 Azure OpenAI key>",
    base_url="<Azure 门户中的端点>/openai/v1/",
)
deployment_name = "<部署名>"

# 添加你的补全代码
prompt = "Complete the following: Once upon a time there was a"

# 使用 Responses API 发起请求
response = client.responses.create(model=deployment_name, input=prompt, store=False)

# 打印响应
print(response.output_text)

如果使用纯 OpenAI(而非 Azure):client = OpenAI(api_key="<你的 OpenAI key>")(不传 base_url),并把部署名换成模型名如 gpt-4o-mini

运行后你会看到类似如下输出:

 very unhappy _____.

Once upon a time there was a very unhappy mermaid.

这个最小可用版本与仓库中的 aoai-app.py / oai-app.py 完全对应,注释中还保留了示例输出的原文,方便比对。

7. 不同类型的提示词,对应不同的事

生成文本跑通之后,你可以修改 prompt 生成不同类型的文本。提示词可用于各种任务:

  • 生成某种类型的文本:生成一首诗、生成测验题目等;
  • 查询信息:例如 “What does CORS mean in web development?”;
  • 生成代码:例如生成校验邮箱的正则表达式,甚至生成整个 Web 应用程序。

8. 实战用例:食谱生成器(Recipe Generator)

场景:家里有一些食材,想做一道菜。除了搜索引擎,也可以用 LLM 来“找”食谱。

第一步提示词:

“Show me 5 recipes for a dish with the following ingredients: chicken, potatoes, and carrots. Per recipe, list all the ingredients used”

模型会返回类似如下结果(节选原文档示例):

1. Roasted Chicken and Vegetables:
Ingredients:
- 4 chicken thighs
- 2 potatoes, cut into cubes
- 2 carrots, cut into cubes
- 2 tablespoons olive oil
- 2 cloves garlic, minced
- 1 teaspoon dried thyme
- 1 teaspoon dried oregano
- Salt and pepper, to taste

2. Chicken and Potato Stew:
Ingredients:
- 2 tablespoons olive oil
- 1 onion, diced
- 2 cloves garlic, minced
- 2 chicken breasts, cut into cubes
- 2 potatoes, cut into cubes
- 2 carrots, cut into cubes
- 1 teaspoon dried oregano
- 1 teaspoon dried thyme
- 1 cup chicken broth
- Salt and pepper, to taste

3. Chicken and Potato Bake:
Ingredients:
- 2 tablespoons olive oil
- 2 chicken breasts, cut into cubes
- 2 potatoes, cut into cubes
- 2 carrots, cut into cubes
- 1 onion, diced
- 2 cloves garlic, minced
- 1 teaspoon dried oregano
- 1 teaspoon dried thyme
- 1 cup chicken broth
- Salt and pepper, to taste

4. Chicken and Potato Soup:
Ingredients:
- 2 tablespoons olive oil
- 1 onion, diced
- 2 cloves garlic, minced
- 2 chicken breasts, cut into cubes
- 2 potatoes, cut into cubes
- 2 carrots, cut into cubes
- 1 teaspoon dried oregano
- 1 teaspoon dried thyme
- 4 cups chicken broth
- Salt and pepper, to taste

5. Chicken and Potato Hash:
Ingredients:
- 2 tablespoons olive oil
- 2 chicken breasts, cut into cubes
- 2 potatoes, cut into cubes
- 2 carrots, cut into cubes
- 1 onion, diced
- 2 cloves garlic, minced
- 1 teaspoon dried oregano

这个结果已经可用,但还有两个有价值的改进方向:

  • 过滤掉不喜欢的/过敏的食材
  • 生成购物清单(考虑家里已有的食材)。

于是追加一条提示:

“Please remove recipes with garlic as I'm allergic and replace it with something else. Also, please produce a shopping list for the recipes, considering I already have chicken, potatoes and carrots at home.”

再次得到的结果中,所有含大蒜的食谱已被剔除,并且末尾多了一份购物清单:

1. Roasted Chicken and Vegetables:
Ingredients:
- 4 chicken thighs
- 2 potatoes, cut into cubes
- 2 carrots, cut into cubes
- 2 tablespoons olive oil
- 1 teaspoon dried thyme
- 1 teaspoon dried oregano
- Salt and pepper, to taste

2. Chicken and Potato Stew:
Ingredients:
- 2 tablespoons olive oil
- 1 onion, diced
- 2 chicken breasts, cut into cubes
- 2 potatoes, cut into cubes
- 2 carrots, cut into cubes
- 1 teaspoon dried oregano
- 1 teaspoon dried thyme
- 1 cup chicken broth
- Salt and pepper, to taste

3. Chicken and Potato Bake:
Ingredients:
- 2 tablespoons olive oil
- 2 chicken breasts, cut into cubes
- 2 potatoes, cut into cubes
- 2 carrots, cut into cubes
- 1 onion, diced
- 1 teaspoon dried oregano
- 1 teaspoon dried thyme
- 1 cup chicken broth
- Salt and pepper, to taste

4. Chicken and Potato Soup:
Ingredients:
- 2 tablespoons olive oil
- 1 onion, diced
- 2 chicken breasts, cut into cubes
- 2 potatoes, cut into cubes
- 2 carrots, cut into cubes
- 1 teaspoon dried oregano
- 1 teaspoon dried thyme
- 4 cups chicken broth
- Salt and pepper, to taste

5. Chicken and Potato Hash:
Ingredients:
- 2 tablespoons olive oil
- 2 chicken breasts, cut into cubes
- 2 potatoes, cut into cubes
- 2 carrots, cut into cubes
- 1 onion, diced
- 2 cloves garlic, minced
- 1 teaspoon dried oregano

Shopping List:
- Olive oil
- Onion
- Thyme
- Oregano
- Salt
- Pepper

五份食谱中不再出现大蒜,同时得到了考虑现有库存的购物清单。接下来把这个演示过程写成真正的代码。

9. 练习二:逐步构建食谱生成器

9.1 硬编码提示词的第一版

以现有 app.py 为起点,把 prompt 变量改为:

prompt = "Show me 5 recipes for a dish with the following ingredients: chicken, potatoes, and carrots. Per recipe, list all the ingredients used"

运行后你会看到类似输出(原文档示例,注意 LLM 具有非确定性,每次运行结果可能不同):

-Chicken Stew with Potatoes and Carrots: 3 tablespoons oil, 1 onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 bay leaf, 1 thyme sprig, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 1 1/2 cups chicken broth, 1/2 cup dry white wine, 2 tablespoons chopped fresh parsley, 2 tablespoons unsalted butter, 1 1/2 pounds boneless, skinless chicken thighs, cut into 1-inch pieces
-Oven-Roasted Chicken with Potatoes and Carrots: 3 tablespoons extra-virgin olive oil, 1 tablespoon Dijon mustard, 1 tablespoon chopped fresh rosemary, 1 tablespoon chopped fresh thyme, 4 cloves garlic, minced, 1 1/2 pounds small red potatoes, quartered, 1 1/2 pounds carrots, quartered lengthwise, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 1 (4-pound) whole chicken
-Chicken, Potato, and Carrot Casserole: cooking spray, 1 large onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and shredded, 1 potato, peeled and shredded, 1/2 teaspoon dried thyme leaves, 1/4 teaspoon salt, 1/4 teaspoon black pepper, 2 cups fat-free, low-sodium chicken broth, 1 cup frozen peas, 1/4 cup all-purpose flour, 1 cup 2% reduced-fat milk, 1/4 cup grated Parmesan cheese
-One Pot Chicken and Potato Dinner: 2 tablespoons olive oil, 1 pound boneless, skinless chicken thighs, cut into 1-inch pieces, 1 large onion, chopped, 3 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 bay leaf, 1 thyme sprig, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 2 cups chicken broth, 1/2 cup dry white wine
-Chicken, Potato, and Carrot Curry: 1 tablespoon vegetable oil, 1 large onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 teaspoon ground coriander, 1 teaspoon ground cumin, 1/2 teaspoon ground turmeric, 1/2 teaspoon ground ginger, 1/4 teaspoon cayenne pepper, 2 cups chicken broth, 1/2 cup dry white wine, 1 (15-ounce) can chickpeas, drained and rinsed, 1/2 cup raisins, 1/2 cup chopped fresh cilantro

9.2 让应用灵活:接收用户输入

为了让“几份食谱”“哪些食材”都可以动态指定,把硬编码改为 input() 收集 + f-string 插值:

no_recipes = input("No of recipes (for example, 5): ")

ingredients = input("List of ingredients (for example, chicken, potatoes, and carrots): ")

# 将食谱数量与食材插值进提示词
prompt = f"Show me {no_recipes} recipes for a dish with the following ingredients: {ingredients}. Per recipe, list all the ingredients used"

一次实际运行可能长这样:

No of recipes (for example, 5): 3
List of ingredients (for example, chicken, potatoes, and carrots): milk,strawberries

-Strawberry milk shake: milk, strawberries, sugar, vanilla extract, ice cubes
-Strawberry shortcake: milk, flour, baking powder, sugar, salt, unsalted butter, strawberries, whipped cream
-Strawberry milk: milk, strawberries, sugar, vanilla extract

9.3 改进一:过滤条件(Filter)

加入过滤:编辑现有 prompt,在末尾追加过滤条件,并从用户处捕获过滤值:

filter = input("Filter (for example, vegetarian, vegan, or gluten-free): ")

prompt = f"Show me {no_recipes} recipes for a dish with the following ingredients: {ingredients}. Per recipe, list all the ingredients used, no {filter}"

示例运行:

No of recipes (for example, 5): 3
List of ingredients (for example, chicken, potatoes, and carrots): onion,milk
Filter (for example, vegetarian, vegan, or gluten-free): no milk

1. French Onion Soup

Ingredients:

-1 large onion, sliced
-3 cups beef broth
-1 cup milk
-6 slices french bread
-1/4 cup shredded Parmesan cheese
-1 tablespoon butter
-1 teaspoon dried thyme
-1/4 teaspoon salt
-1/4 teaspoon black pepper

Instructions:

1. In a large pot, sauté onions in butter until golden brown.
2. Add beef broth, milk, thyme, salt, and pepper. Bring to a boil.
3. Reduce heat and simmer for 10 minutes.
4. Place french bread slices on soup bowls.
5. Ladle soup over bread.
6. Sprinkle with Parmesan cheese.

2. Onion and Potato Soup

Ingredients:

-1 large onion, chopped
-2 cups potatoes, diced
-3 cups vegetable broth
-1 cup milk
-1/4 teaspoon black pepper

Instructions:

1. In a large pot, sauté onions in butter until golden brown.
2. Add potatoes, vegetable broth, milk, and pepper. Bring to a boil.
3. Reduce heat and simmer for 10 minutes.
4. Serve hot.

3. Creamy Onion Soup

Ingredients:

-1 large onion, chopped
-3 cups vegetable broth
-1 cup milk
-1/4 teaspoon black pepper
-1/4 cup all-purpose flour
-1/2 cup shredded Parmesan cheese

Instructions:

1. In a large pot, sauté onions in butter until golden brown.
2. Add vegetable broth, milk, and pepper. Bring to a boil.
3. Reduce heat and simmer for 10 minutes.
4. In a small bowl, whisk together flour and Parmesan cheese until smooth.
5. Add to soup and simmer for an additional 5 minutes, or until soup has thickened.

可以看到含牛奶的食谱被过滤掉了。但如果你乳糖不耐受,可能还想过滤含奶酪的食谱——提示词必须表述清楚,模型才会按你的意图执行。

9.4 改进二:生成购物清单(两阶段提示)

要生成购物清单,可以“一个提示词全解决”,也可以拆成两个提示词。课程选择后者:把第一个提示词的结果作为第二个提示词的上下文。找到打印第一次结果的代码,在其后添加:

old_prompt_result = response.output_text
prompt = "Produce a shopping list for the generated recipes and please don't include ingredients that I already have."

new_prompt = f"{old_prompt_result} {prompt}"
response = client.responses.create(model=deployment_name, input=new_prompt, max_output_tokens=1200, store=False)

# 打印响应
print("Shopping list:")
print(response.output_text)

两个关键细节:

  1. 构造新提示词 = 第一次结果 + 新指令new_prompt = f"{old_prompt_result} {prompt}"。这就是文本生成应用里常见的“结果接力”模式——前一步的输出成为后一步的上下文;
  2. 控制输出长度:既然要承接上一段食谱文本,输出预算要放宽,因此第二次请求显式指定 max_output_tokens=1200

实际运行效果(原文档示例):

No of recipes (for example, 5): 2
List of ingredients (for example, chicken, potatoes, and carrots): apple,flour
Filter (for example, vegetarian, vegan, or gluten-free): sugar

-Apple and flour pancakes: 1 cup flour, 1/2 tsp baking powder, 1/2 tsp baking soda, 1/4 tsp salt, 1 tbsp sugar, 1 egg, 1 cup buttermilk or sour milk, 1/4 cup melted butter, 1 Granny Smith apple, peeled and grated
-Apple fritters: 1-1/2 cups flour, 1 tsp baking powder, 1/4 tsp salt, 1/4 tsp baking soda, 1/4 tsp nutmeg, 1/4 tsp cinnamon, 1/4 tsp allspice, 1/4 cup sugar, 1/4 cup vegetable shortening, 1/4 cup milk, 1 egg, 2 cups shredded, peeled apples
Shopping list:
-Flour, baking powder, baking soda, salt, sugar, egg, buttermilk, butter, apple, nutmeg, cinnamon, allspice

9.5 仓库中的完整参考实现:两阶段请求 + 输入校验

上面的练习代码,在仓库中有更完整的工程化版本 aoai-app-recipe.py(纯 OpenAI 版为 oai-app-recipe.py),值得逐点对照学习:

  1. 环境变量强校验get_required_env('AZURE_OPENAI_API_KEY') 等函数在关键变量缺失时直接抛错退出,而不是带着空配置运行;
  2. 用户输入校验(防止提示注入与越界参数):
def validate_number_input(value: str, min_val: int = 1, max_val: int = 20) -> int:
    """Validate and sanitize numeric input."""
    try:
        num = int(value)
        if num < min_val or num > max_val:
            raise ValueError(f"Number must be between {min_val} and {max_val}")
        return num
    except ValueError:
        raise ValueError(f"Please enter a valid number between {min_val} and {max_val}")

def validate_text_input(value: str, max_length: int = 500) -> str:
    """Validate and sanitize text input to prevent prompt injection."""
    if len(value) > max_length:
        raise ValueError(f"Input too long. Maximum {max_length} characters allowed.")
    sanitized = re.sub(r'[<>{}[\]|\\`]', '', value)
    if not re.match(r'^[\w\s,.\'-]+$', sanitized, re.UNICODE):
        raise ValueError("Input contains invalid characters")
    return sanitized.strip()

食谱数量被限制在 1~20 之间,食材文本限制 500 字符、过滤词限制 100 字符,并剔除 <>{} 等潜在注入字符; 3. 两阶段请求的温度策略:第一次生成食谱用 temperature=0.1(低随机性、结果更稳定),第二次生成购物清单用 temperature=0(几乎完全确定),且两者都设置 max_output_tokens=600

response = client.responses.create(model=deployment, input=prompt, max_output_tokens=600, temperature=0.1, store=False)
# ... 打印食谱后 ...
prompt_shopping = "Produce a shopping list, and please don't include ingredients that I already have at home: "
new_prompt = f"Given ingredients at home {ingredients} and these generated recipes: {old_prompt_result}, {prompt_shopping}"
response = client.responses.create(model=deployment, input=new_prompt, max_output_tokens=600, temperature=0, store=False)

注意参考实现里第二个提示词的写法比练习版更严谨:它不仅把食谱结果带入上下文,还显式回传了“家里已有的食材”{ingredients},让“不要包含已有食材”这条指令有明确依据。此外代码对 response.output_text 为空的情况做了 if not old_prompt_result 的防御分支。

TypeScript 路线的 js-githubmodels/app.js 实现了同样的两阶段流程,但调用的是 @azure-rest/ai-inferenceclient.path("/chat/completions").post(...)temperature: 1.0max_tokens: 1000top_p: 1.0),可以看到“食谱 → 购物清单”的上下文接力逻辑在不同 SDK 下是同构的。

10. 改进你的设置:密钥、Token 与温度

目前代码可以跑,但还有三类工程化改进。

10.1 把密钥与代码分离

密钥不属于代码,应存放在安全位置。用环境变量 + python-dotenv 从文件加载:

  1. 创建 .env 文件:

    OPENAI_API_KEY=sk-...
    

    若使用 Azure OpenAI(Microsoft Foundry),则改为:

    AZURE_OPENAI_API_KEY=<替换>
    AZURE_OPENAI_ENDPOINT=<替换>
    AZURE_OPENAI_API_VERSION=2024-10-21
    
  2. 代码中加载环境变量:

    import os
    from dotenv import load_dotenv
    from openai import OpenAI
    
    load_dotenv()
    
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    

仓库的所有 Python 示例都遵循这一模式:from dotenv import load_dotenv + load_dotenv() 作为固定前置步骤(见 oai-app.pyaoai-app-recipe.py)。

10.2 关于 Token 长度

要生成想要的文本需要考虑需要多少 token——token 是计费单位,应尽量经济地使用(例如能否把提示词写得更短)。用 max_output_tokens 参数控制输出上限,例如限制为 100 个 token:

response = client.responses.create(model=deployment, input=prompt, max_output_tokens=100, store=False)

10.3 实验温度(Temperature)

温度决定输出的随机程度:值越高输出越随机,值越低输出越可预测——需要变化多样的输出就调高,需要稳定一致的输出就调低。用 temperature 参数调整,例如设为 0.5:

response = client.responses.create(model=deployment, input=prompt, temperature=0.5, store=False)

越接近 1.0,输出越多样。

结合 9.5 节参考实现的用法可以总结一条实用经验:生成创意内容(食谱)用 0.1 这样的低值,生成清单类结构化输出用 0,让每一步都在“稳定”和“多样”之间取得明确取舍。

11. 作业与参考解法

作业允许自选方向,课程给出的三个建议及仓库中的参考实现:

  • 打磨食谱生成器:调整 temperature、修改提示词,观察不同组合的效果;
  • 构建“学习伙伴”(study buddy):回答某个主题(例如 Python)的问题,提示词如 “What is a certain topic in Python?”。仓库中的 aoai-study-buddy.py 展示了如何把“专家人设 + 固定输出格式(概念 / 示例代码 / 解释)”写成结构化多行 prompt,并用 input() 接收用户问题后插值进提示词;
  • 历史机器人(history bot):让机器人扮演某个历史人物,回答关于其生平与时代的问题。aoai-history-bot.py 的提示词中有一条很好的防幻觉约束:“remember facts about the timelines and incidents and respond the accurate answer only. Don't create content yourself. If you don't know something, tell that you don't remember.”——即不知道就明说,不要编造

课程文档给出的起始提示词:

- "You're an expert on the Python language

    Suggest a beginner lesson for Python in the following format:

    Format:
    - concepts:
    - brief explanation of the lesson:
    - exercise in code with solutions"

历史机器人示例提示词:

- "You are Abe Lincoln, tell me about yourself in 3 sentences, and respond using grammar and words like Abe would have used"
- "You are Abe Lincoln, respond using grammar and words like Abe would have used:

   Tell me about your greatest accomplishments, in 300 words"

12. 知识检查与进阶挑战

知识检查:temperature(温度)这个概念的作用是什么?

  1. 它控制输出的随机程度;
  2. 它控制响应的大小;
  3. 它控制使用的 token 数量。

(正确答案:1。)

进阶挑战:在做作业时有意识地变换温度——分别尝试 0、0.5 和 1(0 最稳定、1 最多样),观察哪种取值最适合你的应用。


本篇小结:本课以 openai 库与 Responses API 为主线,完整走通了“环境配置 → 最小生成应用 → 提示词迭代 → 两阶段提示接力 → 密钥/Token/温度工程化”的全流程。仓库中 06 课目录 下提供了 aoai-app.pyoai-app.pyaoai-app-recipe.pyoai-app-recipe.pyaoai-study-buddy.pyaoai-history-bot.py 六套可运行脚本及锁版依赖清单,均可对照本文逐行复现。下一步可进入 07 课:构建聊天应用,把单轮文本生成升级为带上下文的多轮对话。

登录后查看全文
热门项目推荐
相关项目推荐