开源项目

API 文档
Agent 时代

将你的 OpenAPI 规范转换为三种输出:为 AI Agent 优化 token 的 llms.txt、为开发者准备的完整 markdown,以及语义化 HTML 落地页。一条命令搞定。

$ npm install swagent

你的文档是为人类构建的。
现在谁在读它们?

LLM Agent 也在消费你的 API 文档。Swagger UI、Redoc 和传统文档在导航栏、重复的 schema 和冗长的格式上浪费了数千个 token。你的 AI 集成正在为此买单。

之前: OpenAPI JSON
openapi.json ~65 KB
{
  "openapi": "3.0.2",
  "info": {
    "title": "Swagger Petstore",
    "version": "1.0.27"
  },
  "paths": {
    "/pet": {
      "put": {
        "tags": ["pet"],
        "summary": "Update an existing pet",
        "operationId": "updatePet",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/Pet"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful operation",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Pet"
                }
              }
            }
          },
          "400": {
            "description": "Invalid ID"
          },
          "404": {
            "description": "Pet not found"
          },
          "422": {
            "description": "Validation exception"
          }
        },
        "security": [
          { "petstore_auth": ["write:pets"] }
        ]
      }
    }
  }
}
之后: SWAGENT llms.txt
llms.txt ~16 KB
# Swagger Petstore - OpenAPI 3.0 v1.0.27

> A sample Pet Store Server based
> on the OpenAPI 3.0 specification.

Base: /api/v3

## Auth
- OAuth2: petstore_auth
- KEY: `api_key` in header

## Conventions
- `*` after field name = required
- All fields string unless noted
- Auth: JWT = Bearer, KEY = API Key
- Common errors: 400/401/404/500

---

## pet

### PUT /pet - Update an existing pet | OAuth2
Body: `{id:integer, name*, category:{id:integer, name},
  photoUrls*:[string], tags:[{id:integer, name}],
  status:available|pending|sold}`
200: `{id:integer, name*, category:{id:integer, name},
  photoUrls*:[string], tags:[{id:integer, name}],
  status:available|pending|sold}`
65 KB 16 KB 减少约 75% 的 token

One URL. Right format.

LLM agents just read your base URL. No special paths to discover, no extra configuration. Standard HTTP content negotiation delivers the right format automatically, HTML for browsers and token-optimized docs for agents.

> Tell your AI agent: "Learn https://api.example.com"
terminal
# Browser gets HTML
curl https://api.example.com/

# LLM agent gets token-optimized docs, same URL
curl -H "Accept: text/markdown" https://api.example.com/

# Check token count before downloading
curl -I -H "Accept: text/markdown" https://api.example.com/
# x-markdown-tokens: 1842

Content negotiation

Send Accept: text/markdown and GET / returns llms.txt instead of HTML. Agents read the same URL humans visit. Standard HTTP, zero discovery overhead.

#

Token budgeting

A HEAD request with Accept: text/markdown returns the x-markdown-tokens header with estimated token count. Agents check cost before downloading.

CDN-ready caching

Vary: accept ensures CDNs cache HTML and markdown variants separately. ETags are per-variant. No stale responses, no cache collisions.

什么是 llms.txt?

一种新兴规范,为 AI 代理提供机器可读的 API 文档入口,就像 robots.txt 为搜索引擎所做的那样。

?

它是什么

一个位于 /llms.txt 的纯文本文件,以紧凑、节省 token 的格式描述你的 API。AI 代理查找它的方式,与浏览器查找 favicon.ico 一样。

>_

为什么重要

LLMs 在解析 HTML 文档、Swagger UI 界面和重复的 JSON schema 时浪费了数千个 token。llms.txt 以极低的成本为它们提供所需的一切。

/

SWAGENT 如何帮助

SWAGENT 读取你的 OpenAPI 规范并自动生成 llms.txt,采用紧凑格式:类型内联、必填字段标记、认证缩写。零人工操作。

llmstxt.org 提出,作为 AI 可读网页内容的标准。

服务于 所有人

llms.txt 面向 AI Agent

Token 优化的紧凑标记。深度解析 $refallOfoneOf schema 引用。认证简写(JWTKEYOAuth2)。内置 ETag 缓存和 Cache-Control 头。

to-humans.md 面向开发者

完整的 markdown 参考文档,包含目录、参数表、响应 schema 和认证指南。读取 OpenAPI 2.0 (Swagger) 和 3.x,JSON 或 YAML。

index.html 面向发现

语义化 HTML 落地页,支持暗色、亮色或自动主题。零 JavaScript,纯 CSS 交互。展示端点、认证方式和所有格式的链接。

为发布 API 的团队 量身打造

AI

AI 优先的 SaaS

让你的 API 对 Agent 开放。添加 llms.txt,让 AI 集成以最低的 token 成本发现并使用你的端点。

MCP

MCP & Tool-use

正在构建 MCP 服务器或 Tool-use 集成?SWAGENT 生成 Agent 理解你的工具所需的紧凑 schema。

API

API Marketplaces

让你的 API 能被搜索能力的 AI Agent 发现。llms.txt 充当端点的机器可读展示窗口。

DX

Developer Experience

API 接口多?从一份 OpenAPI 规范生成 markdown 文档、HTML 落地页和 AI 优化格式。保持一切同步。

工作 原理

1

安装适配器

npm install @swagent/fastify
2

注册插件

import { swagentFastify } from '@swagent/fastify';

app.register(swagentFastify, {
  baseUrl: 'https://api.example.com'
});
3

Five routes, content negotiation

GET /              → HTML landing page (default)
GET /              → llms.txt (Accept: text/markdown)
GET /llms.txt      → AI-optimized docs
GET /to-humans.md  → Markdown reference
GET /openapi.json  → Raw OpenAPI spec

Headers: Vary: accept, ETag (per-variant), x-markdown-tokens

效果 llms.txt 展示

llms.txt
# Pet Store API

> A sample API for managing pets and orders.

Base: https://api.petstore.io
Docs: [HTML](/) | [OpenAPI JSON](/openapi.json)

## Auth Methods
- JWT: `Authorization: Bearer <token>` via POST /auth/login
- API Key: `X-API-Key: <key>` header

## Conventions
- Auth: JWT = Bearer token, KEY = API Key, NONE = no auth
- `*` after field name = required, all fields string unless noted
- Common errors: 400/401/404 return `{success:false, error}`

---

## Auth

### POST /auth/login - Login | NONE
Body: `{email*, password*}`
200: `{token, expiresIn:number}`

## Pets

### GET /pets - List pets | JWT
Query: ?page:integer ?limit:integer ?species
200: `{data:[{id, name, species, age:number}], total:number}`

### POST /pets - Create pet | JWT
Body: `{name*, species*, age:number, vaccinated:boolean}`
200: `{id, name}`

紧凑标记:* = 必填,:type = 非字符串,{...} = 对象。LLM 以最少的 token 消耗读取它,即刻了解每个端点。

亲自 试试看

粘贴 OpenAPI 规范 URL,即时预览生成的 llms.txt 输出。

试试样例:
llms.txt
# 您的 API 文档将在此显示...

> 在上方输入 OpenAPI 规范 URL 或粘贴 JSON,
> 然后点击生成来预览 llms.txt 输出。

适配你的 技术栈

Fastify

基于 fastify-plugin 的插件。自动从 @fastify/swagger 读取规范。启动时即时生成。

npm install @swagent/fastify

Express

Router 中间件。传入 OpenAPI 规范,挂载到任意路径。首次请求时懒加载缓存。

npm install @swagent/express

Hono

子应用实例。原生 c.html()c.text()c.json()。轻量且快速。

npm install @swagent/hono

Elysia

Elysia 的 Bun 原生插件。使用原生 Response 对象和正确的内容类型。首次请求时懒加载缓存。

bun add @swagent/elysia

Koa

返回 @koa/router 实例。可挂载到任意前缀,懒加载缓存。支持 Koa 2+。

npm install @swagent/koa

h3 Nitro / Nuxt

兼容 Nitro 和 Nuxt 服务器路由的 h3 路由器。懒加载缓存,使用 setResponseHeader 设置内容类型。

npm install @swagent/h3

NestJS

完整的 NestJS 支持:SwagentModule.forRoot() 配合 DI 或 setup() 模式。支持 NestJS 10+。

npm install @swagent/nestjs

Core

独立的 generate() 函数。可在任何 Node.js 环境、无服务器函数或构建脚本中使用。

npm install @swagent/core

CLI

从任意 OpenAPI JSON/YAML 文件或 URL 生成。支持 --watch 实时重新生成。输出到磁盘。

npx swagent generate ./spec.json

常见 问题

是否支持 OpenAPI 2.0 (Swagger) 和 3.x?

是的。SWAGENT 同时支持 OpenAPI 2.0 (Swagger) 和 OpenAPI 3.x 规范。解析器透明地处理 swagger: "2.0"openapi: "3.x" 格式。

当我的 API 规范发生变化时会怎样?

输出会自动重新生成。使用框架适配器时,文档在服务器重启时更新。使用 CLI 时,重新运行生成命令即可。无需手动编辑。

支持哪些认证方案?

所有 OpenAPI 安全方案:Bearer (JWT)API Key(header、query、cookie)、OAuth2(所有流程)、OpenID ConnectHTTP Basic/Digest。每种都映射为 llms.txt 中的紧凑缩写。

可以自定义 HTML 落地页主题吗?

HTML 输出是一个包含内联 CSS 的自包含单文件。你可以覆盖样式或使用自己的模板。暗色主题开箱即用,零配置。

性能开销是多少?

几乎为零。框架适配器在启动时即时生成文档并缓存结果。后续请求直接提供静态内容。CLI 将文件生成到磁盘,无运行时成本。

可以禁用单个输出吗?

可以。每个适配器接受配置来启用或禁用特定输出(llms.txt、markdown、HTML、OpenAPI JSON)。只生成你需要的。

可以不使用框架适配器单独使用 @swagent/core 吗?

可以。@swagent/core 是一个独立的包,接收 OpenAPI 规范对象并以字符串形式返回所有输出。可在任何 Node.js 环境、Serverless 函数或构建脚本中使用。

What is content negotiation and how does SWAGENT use it?

Content negotiation is a standard HTTP mechanism where the client tells the server what format it wants via the Accept header. With SWAGENT, GET / serves HTML by default, but when an LLM agent sends Accept: text/markdown, the same URL returns the llms.txt content. No special paths to discover, agents just read your base URL.

How does token estimation work?

Send a HEAD request with Accept: text/markdown to your root URL. The response includes an x-markdown-tokens header with the estimated token count, powered by estimateTokens from @swagent/core. Agents can check the cost before downloading the full document.

准备让你的 API
对 Agent 可读?

$ npm install swagent