# 2.6 输出格式控制：让 Claude 乖乖听话

Prompt Engineering 的终极目标往往不仅仅是获得“正确”的答案，更是获得“可用”的答案。 对于开发者而言，最令人头疼的就是 Claude 回复了一堆 *“Here is the JSON you requested...”* 的废话，或者在 JSON 里加了注释导致 `JSON.parse` 报错。

本节将传授几招确保留下 **干净的机器可读输出 (Clean Machine-Readable Output)** 的绝技。

## 2.6.1 核心技术：Prefill

> **兼容性提示**：Prefill 在 Claude Mythos Preview、Opus 4.7、Opus 4.6 和 Sonnet 4.6 上**不受支持**，使用时会返回 400 错误。对于这些新模型，请使用 Structured Outputs（见 2.6.3 节）或系统提示词来控制输出格式。以下内容仅适用于 Claude Sonnet 4.5 / 3.5 等仍支持 Prefill 的模型。

这是 Claude 早期模型独特的格式控制技术。 在通用的 Chat Completions API (如 OpenAI) 中，通常 `Assistant` 的消息是由模型生成的。但在 Claude 的 Messages API 中，**可以手动代替 Assistant 说“第一句话”**。

这就像是在它的嘴边放了一句话，强迫它接下去。

### 强制 JSON 输出

不要仅仅在 System Prompt 里求它。直接把 `{` 塞进它的嘴里。

**API Payload:**

```jsonc
{
  "messages": [
    {"role": "user", "content": "请分析这段文本的情感，输出 JSON。文本：..."},
    {"role": "assistant", "content": "{"} // <--- 关键！
  ]
}
```

**Claude 的反应**： 它必须从 `{` 后面接着写。它 **不可能** 再说 “好的，这是你的分析：”，因为 `{` 已经发出来了。它只能继续生成 `"sentiment": "positive"...`。

**后端拼接**：

```javascript
async function main() {
  const response = await callClaude({ messages });
  const fullJson = "{" + response.content[0].text; // 记得把预填充的字符拼回去！
  return JSON.parse(fullJson);
}
```

### 强制 XML 输出

同理，预填充 `<root>` 标签。

```python
messages=[
    {"role": "user", "content": "..."},
    {"role": "assistant", "content": "<analysis>"}
]
```

### 引导思维方向

Prefill 不仅能控制格式，还能控制内容方向。

* *User*: “给我写个故事。”
* *Assistant (Prefill)*: “这是一个漆黑风暴的夜晚，”
* *Claude*: “侦探史密斯压低了帽檐...”

## 2.6.2 移除“废话”

如果无法使用 API 的 Prefill 功能（例如在使用某些第三方客户端），可以通过 Prompt 咒语来减少废话。

### 负面约束法

````xml
<format_instructions>
只输出 JSON。
不要输出 Markdown 代码块标记（如 ```json）。
不要输出任何解释性文字。
如果输出包含 JSON 以外的任何字符，世界就会爆炸。
</format_instructions>
````

### 示例示范法

通过 Few-Shot 展示“沉默”的美德。

```xml
<example>
    <input>提取姓名</input>
    <output>{"name": "John"}</output>
</example>
```

## 2.6.3 标准格式详解

### JSON Mode

对于 API 集成，JSON 是王道。建议定义 Schema：

```xml
<output_schema>
{
  "type": "object",
  "properties": {
    "summary": {"type": "string"},
    "tags": {"type": "array", "items": {"type": "string"}},
    "score": {"type": "number", "minimum": 1, "maximum": 10}
  },
  "required": ["summary", "tags", "score"]
}
</output_schema>
```

Claude 非常擅长遵循这种类 JSON Schema 的定义。

### Structured Outputs：原生结构化输出

除了通过 Prompt 控制外，Claude API 支持两类结构化输出能力：

* **JSON outputs**：通过 `output_config.format` 指定 JSON Schema，让最终响应按 schema 返回。
* **Strict tool use**：通过工具定义中的 `input_schema` 与 `strict: true` 保证工具调用参数符合 schema。
* **选择原则**：纯数据抽取或结构化报告优先用 `output_config.format`；需要调用业务函数时再使用 strict tool use。

### CSV

当需要生成大量数据供 Excel 分析时。

```
请生成 50 条模拟用户数据。格式：id,name,email,role。
不要包含表头。每行一条。
```

### Markdown 表格

最适合人类阅读的结构化格式。

```
| ID | Name | Status |
|---|---|---|
...
```

## 2.6.4 长度控制

Claude 有时会变得很啰嗦。

| 目标       | Prompt 技巧                                                   |
| -------- | ----------------------------------------------------------- |
| **极简**   | “Be extremely concise. No filler words.” (极度简洁，无废话)         |
| **字数限制** | “Strictly under 50 words.” (严格控制在50字以内，注意 token vs word 差异) |
| **段落限制** | “Answer in exactly 3 bullet points.” (确切使用3个要点)             |
| **针对性**  | “Only answer the 'What', ignore the 'Why'.” (只答是什么，不答为什么)   |

## 2.6.5 Stop Sequences：停止序列

这是 API 层面的核武器。可以告诉 API：“一看到某个特定字符，就立即切断生成”。

**场景**：只希望 Claude 填空。 Prompt: `Q: 1+1=? A:` Stop Sequence: `\n`

当 Claude 生成 `2` 后，它想换行写解释，但碰到了 `\n`，API 强制截断。得到了干净的 `2`。

***

现在，已掌握了提示工程的所有组件：基础原则、XML 结构、System Prompt、Few-Shot、CoT 和格式控制。 但是，怎么知道写的 Prompt 到底好不好？如何科学地改进它？

➡️ [Prompt 优化方法论](/claude_guide/di-yi-bu-fen-ji-chu-pian/02_prompt/2.7_optimization.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.6_format.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.
