← 返回首页
🧠

Prompt Engineering:提示工程实战指南

📂 llm ⏱ 2 min 346 words

--- title: "Prompt Engineering:提示工程实战指南" description: "掌握高效的大语言模型提示技巧,包括零样本、少样本和思维链等方法" tags: ["Prompt Engineering", "提示工程", "LLM", "实战"] category: "llm" icon: "🧠"

Prompt Engineering:提示工程实战指南

什么是Prompt Engineering

Prompt Engineering(提示工程)是设计和优化输入提示(Prompt)以引导大语言模型生成期望输出的技术。好的提示可以显著提升模型的表现。

基础提示技巧

1. 清晰的指令

from openai import OpenAI

client = OpenAI()

# ❌ 模糊的提示
response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": "写点关于AI的东西"}]
)

# ✅ 清晰的提示
response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": "用500字介绍人工智能在医疗领域的三个主要应用,每个应用包含一个具体案例"}]
)

2. 角色设定

# 设定系统角色
messages = [
    {
        "role": "system",
        "content": "你是一位资深的Python开发专家,擅长用简洁清晰的代码解决实际问题。回答时先给出代码示例,再解释关键点。"
    },
    {
        "role": "user",
        "content": "如何用Python实现一个简单的REST API?"
    }
]

3. 输出格式控制

# 要求结构化输出
prompt = """分析以下产品的用户评价,返回JSON格式:
{
  "sentiment": "positive/negative/neutral",
  "score": 1-5,
  "keywords": ["关键词1", "关键词2"],
  "summary": "一句话总结"
}

用户评价:这个产品质量很好,但价格有点贵,物流速度可以接受。
"""

高级提示技术

1. 零样本学习(Zero-shot)

zero_shot_prompt = """请将以下英文翻译成中文:
"Machine learning is transforming how we approach complex problems."
"""

2. 少样本学习(Few-shot)

few_shot_prompt = """将英文情感分类为正面、负面或中性。

示例:
输入: "I love this product, it's amazing!" 
输出: 正面

输入: "Terrible experience, would not recommend."
输出: 负面

输入: "The product is okay, nothing special."
输出: 中性

现在请分类:
输入: "Quality is good but delivery was slow."
输出: """

3. 思维链(Chain-of-Thought)

cot_prompt = """请一步一步思考以下问题:

问题:一个水池有两个进水管和一个出水管。进水管A每小时注入3立方米,进水管B每小时注入5立方米,出水管每小时排出4立方米。水池初始有10立方米水,问3小时后水池有多少水?

让我们一步一步思考:
1. 首先计算每小时的净进水量
2. 然后计算3小时的总进水量
3. 最后加上初始水量

请按此步骤计算并给出答案。"""

4. 自我一致性(Self-Consistency)

def self_consistent_answer(prompt, n_samples=5):
    """多次采样取多数答案"""
    answers = []
    for _ in range(n_samples):
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.7
        )
        answers.append(response.choices[0].message.content)
    
    # 统计最频繁的答案
    from collections import Counter
    most_common = Counter(answers).most_common(1)[0]
    return most_common[0], most_common[1]

# 使用示例
prompt = "如果一个物体从10米高处自由落体,忽略空气阻力,它落地需要多少秒?(g=10m/s²)"
answer, count = self_consistent_answer(prompt)
print(f"最一致的答案: {answer} (出现{count}次)")

实用提示模板

代码生成

code_gen_prompt = """请编写一个Python函数,要求:
1. 函数名:calculate_fibonacci
2. 功能:计算第n个斐波那契数
3. 输入:正整数n
4. 输出:第n个斐波那契数
5. 使用动态规划优化时间复杂度
6. 包含类型注解和文档字符串
7. 包含简单的单元测试

请直接给出可运行的代码。"""

文本摘要

summary_prompt = """请对以下文本进行摘要,要求:
- 使用中文
- 不超过100字
- 保留关键信息
- 使用要点列表格式

文本:
[在此粘贴需要摘要的文本]
"""

数据分析

analysis_prompt = """分析以下销售数据并提供洞察:

月份,销售额,订单数
1月,150000,500
2月,180000,600
3月,120000,400
4月,200000,700

请提供:
1. 销售趋势分析
2. 异常点说明
3. 下月预测
4. 改进建议"""

提示优化策略

1. 迭代优化

def optimize_prompt(base_prompt, test_cases):
    """通过测试用例迭代优化提示"""
    best_prompt = base_prompt
    best_score = 0
    
    for test_input, expected_output in test_cases:
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": f"{best_prompt}\n\n输入:{test_input}"}]
        )
        actual = response.choices[0].message.content
        score = evaluate_similarity(actual, expected_output)
        
        if score > best_score:
            best_score = score
            # 分析改进方向,调整提示
    
    return best_prompt, best_score

2. 提示分解

# 复杂任务分解为简单步骤
complex_task_prompt = """请按以下步骤处理这段文本:

步骤1:识别文本中的关键实体(人名、地名、组织名)
步骤2:提取实体之间的关系
步骤3:构建知识三元组
步骤4:以JSON格式输出结果

文本:[待处理文本]
"""

常见错误与解决方案

1. 模型生成过长内容

# 限制输出长度
prompt = """请用3句话总结以下内容:
[内容]
注意:严格限制为3句话。"""

2. 模型理解偏差

# 提供具体示例
prompt = """提取日期信息。

示例输入:明天下午3点开会
示例输出:日期:明天,时间:15:00

请分析:
输入:[您的文本]"""

总结

Prompt Engineering 是使用大语言模型的核心技能。通过清晰的指令、角色设定、示例提供和思维链等技巧,可以显著提升模型的输出质量和可靠性。实践中应根据具体任务不断试验和优化提示,找到最佳的提示策略。