# 百行脚本把客户的 OpenAPI 文件变成 Agent 工具草稿

> 脚本解析 $ref，同时输出 Claude 与 OpenAI 格式；挑端点、写描述仍归前线部署工程师（FDE）。

原文: https://fdetimes.net/zh/guides/python-openapi-to-llm-tool-definitions/

到客户现场的第一天，拿到的往往是一个 `openapi.json` 文件链接，里面有几百个端点，外加一句“让 Agent 能用上这套系统”。手写每个工具定义要花一周，还容易出错。一个百行左右的 Python 脚本，一条命令就能生成草稿。

但草稿不是成品。Anthropic Engineering 的一篇文章提醒，常见错误是把现有 API 端点原样包装成工具。因此本文的脚本只承担重复劳动：展开 `$ref`、汇总参数、给工具命名。省下的时间留给挑选端点和撰写描述。

**要做什么：**一个脚本 `gen_tools.py`。它读取 JSON 格式的 OpenAPI 3.x 规范，输出两份工具列表：一份是 Claude 格式（`name`、`description`、`input_schema`），一份是 OpenAI 函数调用格式（`type`、`name`、`description`、`parameters`）。**需要准备：**Python 3 和一份规范文件。YAML 格式的规范先转成 JSON。脚本只用标准库。

## 第 1–2 步：读取规范，去掉所有 $ref

按 OpenAPI 3.1.0 规范，`$ref` 是指向被引用值的 URI。LLM 无法沿着这个指针去查找，发给模型的 schema 必须“拍平”，所以第一步是解析引用。

```python
import json, re, sys

HTTP_METHODS = {"get", "post", "put", "patch", "delete"}

def load_spec(path):
    with open(path, encoding="utf-8") as f:
        return json.load(f)

def resolve(node, spec, seen=()):
    # 简化版：只处理 "#/components/..." 形式的内部 $ref
    if isinstance(node, dict):
        ref = node.get("$ref")
        if isinstance(ref, str) and ref.startswith("#/"):
            if ref in seen:
                return {"description": f"（递归 schema，位于 {ref}）"}
            target = spec
            for part in ref[2:].split("/"):
                target = target[part.replace("~1", "/").replace("~0", "~")]
            return resolve(target, spec, seen + (ref,))
        return {k: resolve(v, spec, seen) for k, v in node.items()}
    if isinstance(node, list):
        return [resolve(x, spec, seen) for x in node]
    return node
```

**检查：**解析后打印一个请求体较复杂的操作。如果还残留 `"$ref"` 字符串，那就是指向其他文件的相对引用。规范允许这类引用，但这个精简版不处理。

`seen` 变量用来防止 schema 自引用时陷入死循环，比如 `Category` 的 `children` 列表元素也是 `Category`。

## 第 3 步：把多处参数合并成一个 schema

OpenAPI 把参数放在四个位置：`query`、`header`、`path` 和 `cookie`。上传的数据则单独放在 `requestBody` 里。Claude 只有一个 `input_schema`，即描述工具所需参数的单个 JSON Schema，所以脚本要把这些全部汇总到一个对象中。

```python
SKIP_IN = {"header", "cookie"}  # 鉴权由你的代码附加，不要让模型来填

def build_input_schema(op, path_item):
    props, required = {}, []
    params = path_item.get("parameters", []) + op.get("parameters", [])
    for p in params:
        if p.get("in") in SKIP_IN:
            continue
        schema = dict(p.get("schema", {}))
        if p.get("description"):
            schema["description"] = p["description"]
        props[p["name"]] = schema
        if p.get("required"):
            required.append(p["name"])
    body = op.get("requestBody", {})
    content = body.get("content", {}).get("application/json", {})
    if "schema" in content:
        props["body"] = content["schema"]
        if body.get("required"):
            required.append("body")
    return {"type": "object", "properties": props, "required": required}
```

这里有两个决定，面对真实系统时值得重新审视。跳过 header 和 cookie 是有意为之：鉴权 token 应由你的代码附加，而不是让模型填写。

第二个决定是如何处理重名。设想端点 `PATCH /orders/{id}`，路径里有 `id`，请求体里也有一个 `id` 字段：把请求体包在 `body` 键下，两者就不会互相覆盖。Anthropic Engineering 建议参数名要清晰、无歧义，如果规范里用的是 `q`、`p1` 这类名字，就在这一步改掉。

## 第 4 步：工具名必须合法，描述不能为空

Claude 要求 `name` 匹配正则 `^[a-zA-Z0-9_-]{1,128}$`。按 OpenAPI 3.1.0 规范，`operationId` 在整个 API 中必须唯一，因此是工具名的天然候选。不过 Redocly 指出，各类工具依赖 `operationId` 识别操作，而现实中的规范常常漏写或重复这个字段，所以脚本需要兜底方案。

```python
NAME_RE = re.compile(r"^[a-zA-Z0-9_-]{1,128}$")

def tool_name(op, method, path, used, prefix):
    raw = op.get("operationId") or f"{method}_{path}"
    name = (prefix + re.sub(r"[^a-zA-Z0-9_-]+", "_", raw).strip("_"))[:128]
    base, i = name, 2
    while name in used:
        suffix = f"_{i}"
        name = base[:128 - len(suffix)] + suffix
        i += 1
    assert NAME_RE.match(name), name
    used.add(name)
    return name

def tool_description(op, method, path):
    text = " ".join(s.strip() for s in (op.get("summary"), op.get("description")) if s)
    return text or f"调用 {method.upper()} {path}。NEEDS DESCRIPTION."
```

`prefix` 遵循 Anthropic 的建议：按服务给工具加前缀，例如 `crm_` 或 `billing_`，这样 Agent 同时连接多个系统时，模型能分清各个工具。关于描述，Anthropic 文档称其是影响工具效果最重要的因素，没有之一，并建议每个工具至少写 3–4 句。

客户的规范很少能达到这个水平。埋下 `NEEDS DESCRIPTION` 字符串，是为了方便 grep，避免误把描述为空的工具发布到生产环境。

**要点:** 草稿可以交给机器生成，但保留哪些工具、如何描述它们，仍是工程师的活。

## 第 5 步：一份数据，两种输出格式

OpenAI 函数调用使用 `type`、`name`、`description`、`parameters` 和 `strict`。上面准备好的同一个 schema 可以直接输出成两种格式，无需重新计算。

```python
def main(spec_path, prefix="", allow=None):
    spec = load_spec(spec_path)
    used, claude, openai, strict_candidates = set(), [], [], []
    for path, item in spec.get("paths", {}).items():
        item = resolve(item, spec)
        for method, op in item.items():
            if method not in HTTP_METHODS:
                continue
            if allow and op.get("operationId") not in allow:
                continue
            name = tool_name(op, method, path, used, prefix)
            desc = tool_description(op, method, path)
            schema = build_input_schema(op, item)
            claude.append({"name": name, "description": desc, "input_schema": schema})
            openai.append({"type": "function", "name": name,
                           "description": desc, "parameters": schema})
            # 部分检查：只看最外层，不检查请求体内嵌套的 schema
            if set(schema["required"]) == set(schema["properties"]):
                strict_candidates.append(name)
    json.dump({"claude": claude, "openai": openai}, sys.stdout,
              ensure_ascii=False, indent=2)
    print("strict 候选工具，需进一步检查：", strict_candidates, file=sys.stderr)

if __name__ == "__main__":
    allow = set(sys.argv[3].split(",")) if len(sys.argv) > 3 else None
    main(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "", allow)
```

```bash
python3 gen_tools.py openapi.json crm_ listOrders,getOrder,updateOrder > tools.json
```

**检查：**统计 `tools.json` 中的工具数、被标记为缺少描述的数量，以及打印到 stderr 的 strict 候选列表。下一步看一个具体工具长什么样。

## 第 6 步：跟踪一个操作从规范到 JSON 的全过程

拿一份假设的规范来试。端点 `PATCH /orders/{id}` 的 `operationId` 是 `updateOrder`，有一个路径参数，请求体指向 `OrderPatch` schema：

```json
"/orders/{id}": {
  "patch": {
    "operationId": "updateOrder",
    "summary": "Update an order.",
    "description": "Changes the status or adds an internal note.",
    "parameters": [
      {"name": "id", "in": "path", "required": true,
       "description": "Order ID", "schema": {"type": "string"}},
      {"name": "X-Api-Key", "in": "header", "required": true,
       "schema": {"type": "string"}}
    ],
    "requestBody": {"required": true, "content": {"application/json": {
      "schema": {"$ref": "#/components/schemas/OrderPatch"}}}}
  }
}
```

假设在 `components/schemas` 中，`OrderPatch` 是一个对象，有两个可选字段：`status`（字符串，枚举值 `pending`、`shipped`、`refunded`）和 `note`（字符串）。用前缀 `crm_` 运行脚本，`claude` 数组中对应的元素是：

```json
{
  "name": "crm_updateOrder",
  "description": "Update an order. Changes the status or adds an internal note.",
  "input_schema": {
    "type": "object",
    "properties": {
      "id": {"type": "string", "description": "Order ID"},
      "body": {
        "type": "object",
        "properties": {
          "status": {"type": "string", "enum": ["pending", "shipped", "refunded"]},
          "note": {"type": "string"}
        }
      }
    },
    "required": ["id", "body"]
  }
}
```

`openai` 数组中的元素有相同的 `name`、`description` 和 schema，只是外层结构不同：多了 `"type": "function"`，schema 放在 `parameters` 键下，而不是 `input_schema`。

从这份输出可以核对四点。`$ref` 已经消失，`OrderPatch` 被直接复制进 `body`。`X-Api-Key` header 没有出现，符合预期。`id` 参数的描述已移入它的 schema。

第四点是，工具描述只有两句，达不到 Anthropic 建议的 3–4 句。好的改写应当说明何时调用这个工具、每个 `status` 值会带来什么结果，以及这个工具做不到什么。

## 为什么脚本不自动开启 strict

上面这个工具进入了 strict 候选列表，因为在最外层，`required` 与 `properties` 完全一致。但在 `body` 内部，`status` 和 `note` 都不在 `required` 中，而 OpenAI 的 strict 模式要求 `properties` 中的每个字段都标为 `required`。代码里的比较只看最外层，发现不了这个问题。

所以候选列表只是起点。

`note` 这类可选字段要先手动转换，然后再手动加上 `"strict": true`。

Claude 更简单：在工具定义上设置 `strict: true` 即可开启 schema 校验。如果想用规范中的 `example` 字段生成 `input_examples`，发送前要逐个对照 `input_schema` 校验，因为无效示例会让 API 返回 400 错误。

## 最大的坑是生成太多工具

在一份上百个端点的规范上不加白名单直接运行，就会得到上百个工具。OpenAI 建议每轮开始时函数数量保持在 20 个以内。这是软性建议，但有其道理：Anthropic 同样认为，工具更少、每个工具承担更多，模型在选择时就更不容易犹豫。

因此 `allow` 参数不是附属功能，而是核心工作。设想客户需要一个处理退款请求的 Agent：查询订单、查看详情、更新订单这三个操作就够了；如果流程总是按固定顺序走，再加一个合并后的工具。

还有几个常见错误：有人让鉴权 header 混进了 schema；有人发布了描述为空的工具；有人想当然地认为 `operationId` 总是唯一，从不运行检查。

在客户现场，写代码之前先问清楚：规范由谁维护，它和实际运行的 API 是否一致。用 Redocly 这类 linter 检查重复的 operationId，很快就能知道这份规范有多可信。

如果想把这项技能写进简历，别写“将 OpenAPI 与 LLM 集成”。要写你把一份数百个端点的规范精简成一小套工具，描述由你亲自撰写，并配有 schema 测试集；再把脚本放到 GitHub 上，针对一份公开规范运行。

在 FDE 面试中，多谈你砍掉了哪些工具、为什么砍，而不是炫耀生成了多少工具。

运行脚本只需一条命令。客户真正付费购买的，是之后那个下午：决定保留哪些工具。

**本周动手试试:**

- 在一份公开的 OpenAPI 规范上运行脚本，统计有多少工具被标记为 NEEDS DESCRIPTION。
- 挑出最多 10 个服务于真实用例的操作，为每个工具亲自撰写描述，至少 3–4 句。
- 查看脚本建议可用 OpenAI strict 模式的工具，对照 OpenAI 文档中 strict 模式的完整要求逐一检查，包括请求体内嵌套的 schema。

## 信源

- [Define tools (Claude Platform docs)](https://platform.claude.com/docs/en/docs/agents-and-tools/tool-use/implement-tool-use)

- [Function calling (OpenAI API docs)](https://developers.openai.com/api/docs/guides/function-calling)

- [OpenAPI Specification v3.1.0](https://spec.openapis.org/oas/v3.1.0.html)

- [operation-operationId-unique (Redocly CLI)](https://redocly.com/docs/cli/rules/oas/operation-operationId-unique)

- [Writing effective tools for agents: with agents](https://www.anthropic.com/engineering/writing-tools-for-agents)
