## 什么是内容协商?

内容协商指根据客户端的要求提供不同的响应。对 AI 智能体而言,这意味着当请求来自智能体时,返回结构化文本(JSON、markdown 或纯文本)而不是笨重的 HTML。

## 为什么重要

AI 智能体在模型看到内容之前会去掉 HTTP 头。模型永远看不到 Content-Type、状态码或重定向链 — 只看到正文文本。返回 HTML 会迫使智能体解析 DOM 结构、提取文本、丢弃布局 — 浪费 token 又丢失意义。

## 我们检查什么

**智能体 UA 收到非 HTML** — 我们使用已知 AI 智能体 User-Agent (例如 `ClaudeBot`) 发送请求,检查响应的 Content-Type 是否不是 `text/html`。能检测智能体 UA 并返回 `text/markdown`、`text/plain` 或 `application/json` 的站点通过此项。

**Accept: JSON 返回 JSON** — 我们发送 `Accept: application/json`,检查响应是否为有效 JSON。这让程序化智能体可以直接访问结构化数据。

**Accept: text 返回 text** — 我们发送 `Accept: text/plain`,检查响应是否是纯文本或 markdown。这是语言模型最容易消化的格式。

**Accept: markdown 返回 markdown** — 我们发送 `Accept: text/markdown`,检查响应是否为 markdown 内容(Content-Type 为 `text/markdown`,或正文是 markdown)。当智能体既想要结构(标题、列表、链接)又不想承受 HTML 的重量时,这是它们偏好的格式。

## 如何实现

在服务器中间件中检测智能体的 User-Agent 和 `Accept` 头:

```javascript
app.get('/', (req, res) => {
  const ua = (req.get('user-agent') || '').toLowerCase();
  const accept = req.get('accept') || '';
  const isAgent = /claude|gpt|anthropic|perplexity|gptbot/i.test(ua);

  // 显式请求时,markdown 优先
  if (accept.includes('text/markdown')) {
    return res.type('text/markdown').sendFile('[llms.txt](/kb/zh/llms-txt)');
  }

  if (accept.includes('application/json')) {
    return res.json({ name: 'My Service', api: '/openapi.json' });
  }

  if (isAgent || accept.includes('text/plain')) {
    return res.type('text/plain').sendFile('llms.txt');
  }

  res.sendFile('index.html');
});
```

### markdown 细节

`Accept: text/markdown` 是较新的约定(由 llms.txt 生态推广),尚未被普遍实现。被请求时返回 markdown 意味着:

- 正文是有效的 markdown(标题、列表、链接 — 没有 HTML 标签)
- Content-Type 头是 `text/markdown`(或者正文为 markdown 的 `text/plain`)
- 同一个 URL 可以对浏览器返回 HTML、对智能体返回 markdown — 路径不变,只是表示形式不同

对于文档页面、博客文章和内容页,你通常已经有一份 markdown 源文件。当收到 `Accept: text/markdown` 时,直接提供该源文件,而不是先转换为 HTML。

## 规范成熟度

**已建立。** 内容协商在 HTTP 本身就有定义 ([RFC 9110](https://www.rfc-editor.org/rfc/rfc9110))。基于 User-Agent 或 Accept 返回对智能体友好格式的做法,被 AI 友好的站点广泛采用。

## 了解更多

- [RFC 9110 §12: Content Negotiation](https://www.rfc-editor.org/rfc/rfc9110#name-content-negotiation)
- [llmstxt.org](https://llmstxt.org/) — 面向 LLM 的 Markdown 约定

## 相关

- [OpenAPI](/kb/zh/openapi)
