提示词工程最佳实践:迭代式提示词开发

2026-11-03 📁 翻译

https://medium.com/towards-artificial-intelligence/prompt-engineering-best-practices-iterative-prompt-development-22759b309919

迭代式提示工程:持续优化 LLM 提示词

用 LLM 构建应用时,提示词很少能在第一次尝试时就达到可用状态。建立良好的迭代流程后,可以根据输出持续调整提示词,逐步形成稳定、有效且能完成预期任务的方案。

这与机器学习模型的训练过程相似,两者都很难一次成功。本文介绍如何通过迭代开发,得到适合具体应用的提示词。

目录

我在 Medium 上分享的大多数见解,此前都已在每周通讯 To Data & Beyond 中发布。通讯关注 AI 领域的快速发展,并提供未在其他任何平台(包括 Medium)发布的内容。可在下方订阅。

To Data & Beyond | Youssef Hosni | Substack
数据科学、机器学习、AI,以及它们之外的更多内容。点击阅读 Youssef Hosni 的 To Data & Beyond,这是一份……
youssefh.substack.com

1. 提示工程的迭代本质

如果你学过机器学习课程,可能见过一张介绍机器学习开发流程的图:获取数据、训练模型并得到实验结果,再检查输出、进行误差分析,找出模型在哪些情况下有效、哪些情况下无效。过程中,你甚至可能重新认识自己究竟要解决什么问题,以及应该如何解决。随后修改实现方案,再次运行实验,如此反复,最终得到有效的机器学习模型。

使用 LLM 开发应用、编写提示词时,也可以采用类似流程:

  1. 明确自己想做什么、需要完成什么任务。
  2. 初次编写提示词,尽量做到清晰、具体,并在适当情况下给系统留出思考时间。
  3. 运行提示词并检查结果。
  4. 如果第一次的效果不够好,就分析原因,例如指令是否不够清晰,或者是否没有给算法足够的思考时间。
  5. 根据分析结果完善思路、改进提示词,然后再次运行。

多次重复这一过程,直到得到适用于具体应用的提示词。

这也是我个人不太关注网上那些宣称“30 个完美提示词”的文章的原因。我认为,世间恐怕不存在一个适用于一切的完美提示词。更重要的是,你要有一套流程,能够为自己的具体应用开发出好的提示词。

Andrew NG

2. 设置工作环境与入门

先设置工作环境:导入 OpenAI 和 OS 包,配置 OpenAI API 密钥,并定义 get_completion 函数。该函数接收提示词,返回模型生成的响应。

import openai
import os

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file

openai.api_key  = os.getenv('OPENAI_API_KEY')


def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0, # this is the degree of randomness of the model's output
    )
    return response.choices[0].message["content"]

下面是一份笔记本电脑的技术资料表,包含结构、尺寸、配置选项和材质等信息。

fact_sheet_laptop = """
OVERVIEW

Introducing our sleek Laptop Series, an embodiment of cutting-edge design and functionality for modern workspaces.
Part of a sophisticated family of tech-inspired devices, including laptops, docking stations, accessories, and more.
Available in multiple colors and finishes to seamlessly integrate with your personal or professional aesthetic.
Crafted with premium materials for a durable and stylish appeal.
Suitable for a variety of environments, whether it's your home office or a corporate setting.
Engineered for superior performance and productivity, making it an ideal choice for professionals.
DESIGN

The laptop is available in various color options, allowing you to personalize it to your preference.
Choose between different finishes, including brushed aluminum, matte black, glossy white, or chrome accents.
Select from configurations with a standard display or a touchscreen option.
Options for additional features such as a backlit keyboard, fingerprint sensor, or face recognition technology.
Sleek and lightweight design for portability without compromising on power.
SPECIFICATIONS

Powerful Intel/AMD processors for seamless multitasking and high-performance computing.
Ultra-thin design with dimensions:
WIDTH 35 CM | 13.78”
DEPTH 24 CM | 9.45”
HEIGHT 1.5 CM | 0.59”
Crisp and vibrant display with a resolution tailored for immersive work or entertainment experiences.
OPTIONS

Choose between SSD or HDD storage options for speed and capacity tailored to your needs.
Various connectivity options, including USB-C, HDMI, and Thunderbolt for versatile compatibility.
Different RAM configurations to suit your processing requirements.
Options for operating systems, catering to both Windows and MacOS preferences.
MATERIALS

Durable aluminum casing for a premium look and robust protection.
High-resolution display with anti-glare coating for comfortable viewing in any lighting condition.
Cutting-edge cooling technology to ensure optimal performance during extended usage.
COUNTRY OF ORIGIN

Crafted with precision in state-of-the-art facilities in Japan, combining traditional craftsmanship with technological innovation.

"""

假设你要用这份资料表,帮助营销团队为一家在线零售网站撰写产品描述。提示词可以要求模型根据技术资料表,为网站上的产品撰写描述。运行后,查看模型返回的结果。

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

Technical specifications: ```{fact_sheet_laptop}```
"""
response = get_completion(prompt)
print(response)

Laptop Series 笔记本电脑系列设计时尚纤薄,兼顾前沿设计与实用功能,面向现代工作空间。它所属的设备产品家族还包括扩展坞和各类配件,并提供多种配色和饰面,可匹配个人审美或职业风格。

产品采用优质材料,兼顾耐用性和外观,既适用于家庭办公,也适用于企业环境。它面向性能与生产力需求,适合专业人士使用。

这款笔记本提供多种配色,方便按个人喜好选择。饰面可选拉丝铝、哑光黑、亮面白或镀铬点缀,也可选择标准显示屏或触摸屏配置。

附加功能包括背光键盘、指纹传感器或人脸识别技术。机身时尚轻薄,同时不牺牲性能,适合移动办公的专业人士。

它搭载 Intel/AMD 处理器,支持流畅的多任务处理和高性能计算。超薄机身宽 35 厘米(13.78 英寸)、深 24 厘米(9.45 英寸)、高 1.5 厘米(0.59 英寸),在不牺牲性能的情况下提供便携性。

显示屏清晰锐利、色彩鲜明,分辨率面向沉浸式工作或娱乐体验。存储可选 SSD 或 HDD,以匹配速度和容量需求。连接选项包括 USB-C、HDMI 和 Thunderbolt,提供广泛而灵活的兼容性。

多种内存(RAM)配置可按运算需求选择,操作系统可选 Windows 或 MacOS。

耐用的铝制外壳兼顾高端外观和防护。高分辨率显示屏配有防眩光涂层,确保在任何光照条件下都能舒适观看。前沿散热技术用于在长时间使用时保持最佳性能。

产品在日本的先进设施中精密制造,结合传统工艺与技术创新。

这段输出完成了根据技术资料表撰写产品描述的任务,但明显过长。如果希望文案更简洁,就需要继续调整提示词。

3. 解决 LLM 输出结果过长的问题

上一节的输出符合任务要求,但长度并不理想。可以在提示词中增加“最多使用 50 个单词”的限制,明确期望的输出长度,然后再次运行。

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

Use at most 50 words.

Technical specifications: ```{fact_sheet_laptop}```
"""
response = get_completion(prompt)
print(response)

我们时尚的笔记本电脑系列兼顾设计与功能,提供多种颜色和饰面,可匹配个人或职业风格。产品采用优质材料,兼具耐用性和时尚感,适合追求性能、需要在任何环境下工作的专业人士。

这段输出更加简洁,适合作为简短的产品描述。接下来检查回复长度:将响应按空格拆分,再输出拆分后的长度。结果为 47 个单词,基本符合要求。

LLM 通常能大致遵循长度要求,但并不擅长严格执行精确的字数限制。有时它可能输出 60 或 65 个单词,不过通常仍在合理范围内。也可以尝试将限制改为“最多使用三句话”。

用于统计长度的代码及结果如下:

len(response.split())

47

4. 强制 LLM 关注特定细节

继续完善网站文案时,销售对象可能发生变化:产品不再通过网站直接卖给消费者,而是卖给笔记本电脑零售商。与普通消费者相比,零售商通常更关注产品的技术细节。

此时可以进一步修改提示词,明确说明这段描述面向笔记本电脑零售商,因此应具有技术性,并重点介绍技术细节。

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

The description is intended for laptop retailers, 
so should be technical in nature and focus on the 
materials the product is constructed from.

At the end of the description, include every 7-character 
Product ID in the technical specification.

Use at most 50 words.

Technical specifications: ```{fact_sheet_laptop}```
"""
response = get_completion(prompt)
print(response)

我们时尚的笔记本电脑系列采用优质材料,兼顾耐用性和外观,提供多种颜色和饰面,包括拉丝铝、哑光黑、亮面白或镀铬装饰。它配备高分辨率显示屏,采用防眩光涂层和前沿散热技术,可实现最佳性能。产品在日本的先进工厂精密制造。

修改提示词可以引导模型关注真正需要的细节和特征。例如,还可以要求在描述末尾加入产品 ID:在提示词末尾增加一条指令,要求模型在技术规格中包含每个由 7 个字符组成的产品 ID,然后运行并检查结果。

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

The description is intended for laptop retailers, 
so should be technical in nature and focus on the 
materials the product is constructed from.

At the end of the description, include every 7-character 
Product ID in the technical specification.

Use at most 50 words.

Technical specifications: ```{fact_sheet_laptop}```
"""
response = get_completion(prompt)
print(response)

我们时尚的笔记本电脑系列采用优质材料,兼顾耐用性和外观,提供拉丝铝、哑光黑、亮面白或镀铬装饰等多种颜色和饰面。高分辨率显示屏配有防眩光涂层,可在任何光照条件下舒适观看。产品搭载 Intel/AMD 处理器,并提供多种存储和内存配置,旨在实现卓越性能、提升工作效率。前沿散热技术可确保长时间使用时仍能保持最佳性能。这款设备精致可靠,可匹配个人风格或职业形象。

产品 ID:Laptop01、Laptop02

这就是许多开发者都会经历的迭代式提示词开发过程。通常,可以先编写一个提示词,观察输出结果,再持续迭代,使其逐步接近实际需求。

5. 获取复杂响应

下面通过一个更复杂的提示词,进一步了解 ChatGPT 的能力。除产品描述外,这次还要求模型加入列出产品尺寸的表格,并将所有内容整理为 HTML 格式,以便后续显示和检查呈现效果。在实践中,通常需要经过多次迭代,才能最终得到这样的提示词。

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

The description is intended for laptop retailers, 
so should be technical in nature and focus on the 
materials the product is constructed from.

At the end of the description, include every 7-character 
Product ID in the technical specification.

After the description, include a table that gives the 
product's dimensions. The table should have two columns.
In the first column include the name of the dimension. 
In the second column include the measurements in inches only.

Give the table the title 'Product Dimensions'.

Format everything as HTML that can be used in a website. 
Place the description in a <div> element.

Technical specifications: ```{fact_sheet_laptop}```
"""

response = get_completion(prompt)
print(response)
<div>
  <h2>产品描述</h2>
  <p>
    我们时尚的笔记本电脑系列兼顾前沿设计与功能,面向现代工作空间。它所属的设备家族涵盖笔记本电脑、扩展坞、配件等,提供多种颜色和饰面,可匹配个人风格或职场审美。产品采用优质材料,兼顾耐用性和外观,适用于家庭办公室和企业办公场所,面向注重性能与生产力的专业人士。
  </p>
  <p>
    这款笔记本电脑提供多种配色,方便按个人喜好选择。饰面可选拉丝铝、哑光黑、亮面白或镀铬点缀,也可选择标准显示屏或触摸屏配置。还可选配背光键盘、指纹传感器或人脸识别技术等附加功能。设计时尚轻巧,便于携带,同时不牺牲性能。
  </p>
  <p>
    Intel/AMD 处理器支持流畅的多任务处理和高性能计算。显示屏清晰锐利、色彩鲜明,分辨率针对沉浸式工作或娱乐体验进行了优化。存储可选 SSD 或 HDD,以匹配速度和容量需求。连接选项包括 USB-C、HDMI 和 Thunderbolt,兼容性强,可灵活适配。不同内存配置可满足处理需求,操作系统则兼顾 Windows 和 MacOS 用户偏好。
  </p>
  <p>
    产品在日本最先进的设施中精密制造,结合传统工艺与技术创新。
  </p>
  <h2>产品尺寸</h2>
  <table>
    <tr>
      <th>尺寸名称</th>
      <th>测量值(英寸)</th>
    </tr>
    <tr>
      <td>宽度</td>
      <td>13.78"</td>
    </tr>
    <tr>
      <td>深度</td>
      <td>9.45"</td>
    </tr>
    <tr>
      <td>高度</td>
      <td>0.59"</td>
    </tr>
  </table>
</div>

产品 ID:[将根据技术规格提供]

接下来显示这段 HTML,检查它是否有效,以及能否正常呈现。

from IPython.display import display, HTML
display(HTML(response))

显示后的结果如下:


支持本文

参考项目:GitHub

订阅 To Data & Beyond 通讯,可完整阅读并提前获取我的文章:

To Data & Beyond | Youssef Hosni | Substack

数据科学、机器学习、AI,以及它们之外的领域。点击阅读 Youssef Hosni 的 To Data & Beyond,这是一份……

youssefh.substack.com

数据科学与 AI 职业辅导

我提供数据科学辅导课程和长期职业辅导:

© 2026 Hot Ingest