# 2.4 少样本学习：AI 的“举一反三”

如果把编写 System Prompt 比作编写“职位描述”，那么 **Few-Shot Prompting (少样本提示)** 就是在进行“岗前培训”。

通过向 Claude 展示几个“完美案例”，无需费力解释抽象规则，就能让模型迅速领悟意图。这被称为 **In-Context Learning (上下文学习)**。

## 2.4.1 原理：从模仿到泛化

LLM 是强大的模式识别引擎。当提供示例（Shots）时，Claude 实际上在做两件事：

1. **格式模仿**：识别输入和输出的结构（JSON, Markdown, XML）。
2. **逻辑泛化**：分析从 Input 变到 Output 的潜在逻辑规则。

### Shot 的数量级

| 类型            | 数量  | 适用场景                          |
| ------------- | --- | ----------------------------- |
| **Zero-Shot** | 0   | 简单任务，通用常识（“把这段话翻译成英文”）        |
| **One-Shot**  | 1   | 需要强制规定特定格式 / 风格               |
| **Few-Shot**  | 3-5 | 复杂任务，边缘情况多，需要很难用语言描述清楚的逻辑     |
| **Many-Shot** | 50+ | 极高难度的分类任务、微调级别的风格模仿（利用长上下文窗口） |

## 2.4.2 标准构造范式

推荐使用 XML 标签 `<examples>` 包裹示例。

### 基础结构

```xml
<system_prompt>
    ...
</system_prompt>

<examples>
    <example>
        <input>苹果</input>
        <output>红色，圆形，水果</output>
    </example>
    <example>
        <input>天空</input>
        <output>蓝色，广阔，自然现象</output>
    </example>
</examples>

<user_input>
    消防车
</user_input>
```

### 黄金法则：多样性覆盖

示例集必须覆盖任务的 **边界情况 (Corner Cases)**。

* **Bad Set**: 3个示例全是简单的正面情况。
* **Good Set**:
  * Ex 1: 简单标准情况。
  * Ex 2: 复杂情况（输入很长）。
  * Ex 3: 异常情况（输入缺损，输出报错）。
  * Ex 4: 干扰情况（输入包含无关信息，输出需忽略）。

## 2.4.3 进阶技巧

### 格式强化

有时即使写了 “Output valid JSON”，模型还是会啰嗦 “Here is the JSON...”。 通过 Few-Shot，直接展示 JSON Only 的输出，Claude 就会乖乖闭嘴。

```xml
<example>
    <input>张三, 25岁</input>
    <output>{"name": "张三", "age": 25}</output>
</example>
```

### 思维链演示

如果希望 Claude 在推理时必须展示步骤，不要只在 System Prompt 里说。**在示例里直接写出来。**

```xml
<example>
    <question>如果我把一块 20度的铁扔进 80度的水里，会发生什么？</question>
    <answer>
    <thinking>
    1. 铁比水的比热容小。
    2. 热量会从高温物体传向低温物体。
    3. 最终两者会达到热平衡。
    4. 平衡温度会在 20 到 80 度之间。
    </thinking>
    热量会从水传递给铁，铁变热，水变冷，最终两者温度一致。
    </answer>
</example>
```

### 负面示例

告诉 Claude “不要做什么”往往很难，不如直接演示“错误的做法”以及“如何修正”。

```xml
<example>
    <input>把这个以 CSV 格式输出：A,B,C</input>
    <wrong_output>A, B, C</wrong_output> <!-- 模型常犯错误：加了多余空格 -->
    <correct_output>"A","B","C"</correct_output> <!-- 我们期望的标准CSV -->
</example>
```

*(注：这种写法需要配合说明，明确告诉模型哪个是错的。)*

## 2.4.4 Many-Shot Prompting

这是 Claude 长上下文能力的特有玩法。 如果你的任务很难（例如：将自然语言转为一种极其晦涩的内部 DSL 查询语言），提供 3 个例子根本不够。 可以利用 Claude 最新版本的 1M token 窗口，一次性塞入 **50-100 个甚至更多** 高质量的 Input-Output 对。

**效果惊人**：根据 Anthropic 的研究，Many-Shot 在某些复杂任务上的表现可以媲美经过 Fine-tuning（微调）的模型，但无需任何训练成本。

## 2.4.5 动态示例库

在生产环境中，可能有 1000 个完美的示例，但不能每次都全部发给模型（Token太贵）。 最佳实践是建立一个 **动态示例库**：

1. **Embed**: 将 1000 个示例的 `input` 转化为向量并存入向量数据库。
2. **Retrieve**: 当用户发来新问题 `Q` 时，先去库里搜最相似的 5 个示例。
3. **Construct**: 将这 Top-5 示例动态插入 System Prompt 的 `<examples>` 插槽中。
4. **Generate**: 发送给 Claude。

这种方法大大提升了针对特定问题的回复准确率。

***

掌握了 Few-Shot，已经能够解决 90% 的格式和风格问题。但面对复杂的逻辑推理难题，还需要一把更锋利的武器 —— 让 AI “慢下来思考”。

➡️ [链式思维 (Chain of Thought)](/claude_guide/di-yi-bu-fen-ji-chu-pian/02_prompt/2.5_cot.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yeasy.gitbook.io/claude_guide/di-yi-bu-fen-ji-chu-pian/02_prompt/2.4_few_shot.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
