第02章:基础技术全景——Zero-Shot、Few-Shot、CoT与选择框架

第02章:基础技术全景——Zero-Shot、Few-Shot、CoT与选择框架

五种Prompt技术覆盖了80%的场景。知道每种技术的原理,比背诵100个Prompt模板有价值得多。


2.1 五种核心技术总览

PROMPT_TECHNIQUES = {
    "zero_shot": {
        "description": "直接指令,不给示例",
        "token_cost": "最低",
        "best_for": ["简单分类", "格式转换", "创意生成"],
        "weakness": "复杂任务成功率低"
    },
    "few_shot": {
        "description": "给1-5个输入输出示例",
        "token_cost": "中等",
        "best_for": ["特定输出格式", "领域特定任务", "风格模仿"],
        "weakness": "示例选不好反而有害"
    },
    "chain_of_thought": {
        "description": "要求LLM显式写出推理步骤",
        "token_cost": "中高",
        "best_for": ["数学推理", "逻辑判断", "多步骤问题"],
        "weakness": "输出更长,延迟更高"
    },
    "self_consistency": {
        "description": "多次采样,投票选最一致答案",
        "token_cost": "高(N倍)",
        "best_for": ["高精度要求", "有单一正确答案的任务"],
        "weakness": "成本高,延迟高"
    },
    "role_prompting": {
        "description": "给LLM分配专家角色",
        "token_cost": "低",
        "best_for": ["专业领域任务", "特定写作风格"],
        "weakness": "角色定义不精确效果有限"
    }
}

2.2 Zero-Shot:最简洁的起点

from openai import OpenAI
client = OpenAI()

# ====== Zero-Shot的基本结构 ======

def zero_shot(task_description: str, input_text: str, output_format: str = None) -> str:
    """
    标准Zero-Shot Prompt结构
    """
    
    prompt = f"{task_description}"
    
    if output_format:
        prompt += f"\n\n输出格式:{output_format}"
    
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": f"{prompt}\n\n输入:\n{input_text}"}],
        temperature=0
    )
    
    return response.choices[0].message.content


# ====== Zero-Shot的三种写法对比 ======

input_text = "苹果公司今天宣布,iPhone 17将于9月发布,起售价为999美元。CEO Tim Cook在发布会上表示这是公司历史上最重要的产品。"

# 写法A:任务描述(最差)
result_a = zero_shot(
    task_description="提取信息",
    input_text=input_text
)

# 写法B:明确任务+格式(中等)
result_b = zero_shot(
    task_description="从新闻文本中提取关键信息",
    input_text=input_text,
    output_format="bullet points"
)

# 写法C:精确任务+精确格式(最好)
result_c = zero_shot(
    task_description="""从新闻文本中提取以下信息:
    - 公司名称
    - 产品名称
    - 发布日期
    - 起售价格(仅数字,美元)
    - 关键引语(人名:引语)""",
    input_text=input_text,
    output_format='JSON格式,键名用下划线命名法,如 {"company_name": "..."}'
)

print("写法A:", result_a)
print("写法B:", result_b)  
print("写法C:", result_c)

2.3 Few-Shot:示例驱动的精准控制

def few_shot_prompt(
    task_description: str,
    examples: list[dict],  # [{"input": "...", "output": "..."}]
    test_input: str
) -> str:
    """
    Few-Shot Prompt构建器
    """
    
    messages = [{"role": "system", "content": task_description}]
    
    # 注入示例(交替user/assistant格式)
    for example in examples:
        messages.append({"role": "user", "content": example["input"]})
        messages.append({"role": "assistant", "content": example["output"]})
    
    # 测试输入
    messages.append({"role": "user", "content": test_input})
    
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        temperature=0
    )
    
    return response.choices[0].message.content


# ====== 实际案例:情感分析 ======

examples = [
    {
        "input": "这个产品简直太棒了,用了之后爱不释手!",
        "output": '{"sentiment": "positive", "confidence": 0.95, "keywords": ["太棒了", "爱不释手"]}'
    },
    {
        "input": "质量一般,和描述差距较大,不太推荐",
        "output": '{"sentiment": "negative", "confidence": 0.80, "keywords": ["质量一般", "差距较大"]}'
    },
    {
        "input": "功能完整,价格合理,但客服响应较慢",
        "output": '{"sentiment": "mixed", "confidence": 0.75, "keywords": ["功能完整", "客服响应较慢"]}'
    }
]

result = few_shot_prompt(
    task_description="分析用户评论的情感,输出JSON格式",
    examples=examples,
    test_input="物流超快,包装完好,商品和图片一致,下次还会来买"
)
print(result)
# 输出:{"sentiment": "positive", "confidence": 0.92, "keywords": ["物流超快", "包装完好"]}

2.4 Chain-of-Thought:让推理可见

# ====== 标准CoT vs Zero-Shot对比 ======

problem = """
一家公司有120名员工。其中40%是工程师,工程师中的25%是女性。
营销部门有15人,都是非工程师。
问:公司中男性工程师有多少人?
"""

# Zero-Shot(可能直接给答案,容易出错)
zero_shot_response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": problem}],
    temperature=0
)

# CoT(强制中间步骤)
cot_response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{
        "role": "user",
        "content": problem + "\n\n请一步一步地推导,最后给出答案。"
    }],
    temperature=0
)

# Zero-Shot CoT(魔法咒语)
zero_shot_cot = client.chat.completions.create(
    model="gpt-4o",
    messages=[{
        "role": "user",
        "content": problem + "\n\nLet's think step by step."
    }],
    temperature=0
)

CoT的几种触发方式(效果从好到差):

方式 Prompt片段 适用场景
显式步骤要求 “请按步骤1.2.3逐步推理” 数学/逻辑题
思考框架 “先分析已知条件,再推导” 复杂分析
Zero-Shot CoT “Let’s think step by step” 通用推理
Few-Shot CoT 给包含推理步骤的示例 需要特定推理风格时

2.5 技术选择决策树

def select_prompt_technique(task: dict) -> str:
    """
    根据任务特征选择最优Prompt技术
    """
    
    if task["has_single_correct_answer"] and task["requires_high_accuracy"]:
        return "self_consistency"  # 多次采样投票
    
    if task["requires_multi_step_reasoning"]:
        if task["has_example_reasoning_chains"]:
            return "few_shot_cot"
        return "zero_shot_cot"
    
    if task["has_specific_output_format"] or task["domain_specific"]:
        if task["has_examples"]:
            return "few_shot"
        return "zero_shot_with_format"
    
    if task["creative"] or task["open_ended"]:
        if task["needs_specific_style"]:
            return "role_prompting + few_shot"
        return "zero_shot"
    
    return "zero_shot"  # 默认:最简单的方案


# 使用示例
task_examples = [
    {
        "name": "提取合同中的关键日期",
        "has_single_correct_answer": True,
        "requires_high_accuracy": True,
        "requires_multi_step_reasoning": False,
        "has_specific_output_format": True,
        "domain_specific": True,
        "has_examples": True,
        "creative": False,
        "open_ended": False,
        "needs_specific_style": False,
        "has_example_reasoning_chains": False
    },
    # 建议技术: few_shot(有格式要求,有示例可提供)
    
    {
        "name": "解一道数学应用题",
        "has_single_correct_answer": True,
        "requires_high_accuracy": True,
        "requires_multi_step_reasoning": True,
        "has_specific_output_format": False,
        "domain_specific": False,
        "has_examples": False,
        "creative": False,
        "open_ended": False,
        "needs_specific_style": False,
        "has_example_reasoning_chains": False
    },
    # 建议技术: self_consistency(高精度+推理)
]

2.6 综合案例:五种技术对比同一任务

# 任务:判断一段客户反馈是否需要紧急处理

feedback = """
我已经等了3周了!你们的客服完全不回复,我的问题还没解决。
我需要立即退款,否则我会投诉到消费者保护委员会。
这是我见过最差的服务!"""

TECHNIQUES = {
    "zero_shot": "判断以下客户反馈是否需要紧急处理,输出YES/NO",
    
    "zero_shot_with_format": """判断以下客户反馈是否需要紧急处理。
    紧急处理标准:提到退款/投诉/法律/立即等词汇,或情绪极端负面。
    输出JSON:{"urgent": true/false, "reason": "...", "priority": 1-5}""",
    
    "few_shot": """判断客户反馈紧急程度。

示例1:
输入:我的订单昨天才到,感谢!
输出:{"urgent": false, "priority": 1}

示例2:
输入:你们扣了我的钱但没发货,我要报警!
输出:{"urgent": true, "priority": 5}""",
    
    "cot": """判断客户反馈是否紧急。
    请先分析:1)提到哪些关键词 2)情绪程度 3)是否有法律威胁 4)等待时间
    最后综合判断给出JSON结论。""",
    
    "role_prompting": """你是一个有10年经验的客户成功经理,
    专门处理高危客户投诉,对客户情绪和法律风险极度敏感。
    请评估以下客户反馈的紧急程度。"""
}

for technique, prompt in TECHNIQUES.items():
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": prompt},
            {"role": "user", "content": feedback}
        ],
        temperature=0
    )
    print(f"\n[{technique}]\n{response.choices[0].message.content}")

本章小结

  1. 五种技术:Zero-Shot(最简单)、Few-Shot(格式控制)、CoT(推理)、Self-Consistency(高精度)、角色扮演(风格控制)
  2. 选择原则:从Zero-Shot开始,在测试中发现不足后,才升级到更复杂的技术
  3. CoT在数学/逻辑推理任务中效果最显著,触发词"一步一步"或提供推理示例
  4. Few-Shot的示例质量比数量更重要:3个高质量示例 > 10个低质量示例
  5. Self-Consistency(多次采样投票)是成本换精度的策略,只在有必要时使用

行动项:选取你工作中3个常用的LLM任务,用本章的决策树为每个任务选择最合适的技术,实现并测试,记录效果差异。