Agent Build智能体搭建 Tutor教程
Map地图 / Module模块 2 / labs/m02_*

API and gatewayAPI 与网关

One contract for every caller, with keys, scopes, limits, and a single public door.所有调用方共用一套接口契约,配上密钥、权限范围、限额,以及唯一的对外入口。

What it is and why it exists它是什么,为什么需要它

What是什么

The API is the contract callers use: the OpenAI-compatible chat endpoint. The gateway is the process in front of the engine that authenticates each caller and decides what that caller may do.API 是调用方使用的契约,即 OpenAI 兼容的 chat 接口。网关是挡在引擎前面的进程,负责验证每个调用方的身份,并决定它能做什么。

Why为什么

The engine has no authentication. Every outside caller needs an identity that can be limited and revoked without affecting the others. A stable contract also lets you replace everything behind it.引擎没有身份验证。每个外部调用方都需要一个身份,可以单独限流、单独吊销,而不影响其他调用方。稳定的契约也让你可以替换它背后的一切。

How it works工作原理

Where it sits in the build order它在搭建顺序中的位置

Needs first前置模块

  • Inference engineering推理工程A gateway forwards to an engine. Its timeouts and limits are set from measured load times and generation rates.网关要把请求转发给引擎。它的超时和限额根据测得的加载时间和生成速率来设定。Build out of order不按顺序搭建 Stand in with:可用以下替代: The fake model. The lab gateway uses it whenever LAB_BASE_URL is unset.假模型。未设置 LAB_BASE_URL 时,lab 网关就用它。

Unlocks解锁

  • Tools and MCP工具与 MCPTool calling rides on the chat contract: schemas go in the request and tool calls come back in the response. Key scope decides who gets tools.工具调用建立在 chat 契约之上:schema 随请求发出,工具调用随响应返回。密钥的权限范围决定谁能用工具。
  • Harness engineeringHarness 工程The harness sits behind the gateway contract. Keys carry scopes, and the harness reads the scope to decide whether a caller gets tools.Harness 位于网关契约之后。密钥带有权限范围,Harness 根据它决定调用方能否使用工具。
  • SDKs and frameworksSDK 与框架SDKs need an endpoint. The gateway gives every SDK the same OpenAI-compatible base URL, so the model is held constant while the loop changes.SDK 需要一个端点。网关为每个 SDK 提供同一个 OpenAI 兼容的 base URL,这样在更换循环时模型保持不变。

In the reference build在参考系统中

Path路径Role作用
apps/agent-server/auth.pyKey validation, scopes, rate limits, quotas.密钥验证、权限范围、限流、配额。
apps/agent-server/keys_admin.pyIssue, list, and revoke keys.签发、列出、吊销密钥。
apps/agent-server/main.pyThe HTTP endpoints.HTTP 接口。
apps/claude-code-gateway/Translation proxy so a coding client can use local models.协议转换代理,让编程客户端可以使用本地模型。

Process map流程图

One request through the gateway一个请求如何通过网关

  1. 1
    Bearer token arrives收到 Bearer 令牌The caller sends its secret in the Authorization header.调用方在 Authorization 头里发送密钥。
  2. 2
    Hash and look up哈希并查找The secret is hashed and matched against stored hashes. The plain secret is never stored.对密钥做哈希,与存储的哈希比对。明文密钥从不保存。
  3. 3
    Scope权限范围Does this key have the scope the endpoint needs?该密钥是否具备此接口所需的权限?
  4. 4
    Rate and quota速率与配额Count this key's recent calls. Refuse with 429 when over.统计该密钥近期的调用次数。超限则返回 429。
  5. 5
    Shape the request调整请求Remove tools for keys without the tools scope. Apply the model router.对没有 tools 权限的密钥去掉工具定义。应用模型路由。
  6. 6
    Forward转发Send to the engine on localhost and return its response unchanged.发给 localhost 上的引擎,并原样返回响应。

Build steps搭建步骤

Follow them in order the first time. Each step names what it uses from earlier steps and what it leaves for later ones. Code is read from the lab files, and output is what the lab printed when it was run.第一次请按顺序做。每一步都写明它用到前面步骤的什么成果,又为后面的步骤留下什么。代码直接读取自 lab 文件,输出是 lab 实际运行时打印的内容。

  1. 1Decide the public surface确定对外接口
  2. 2Build the key store建立密钥库
  3. 3Write the gateway handler编写网关处理函数
  4. 4Prove each rule with a request用请求逐条验证规则
  5. 5Issue one key per application每个应用签发一个密钥
  6. 6Apply the model router in the gateway在网关里应用模型路由
  7. 7Open one public door只开一个对外入口
01Decide the public surface确定对外接口
Why this step is here为什么这一步排在这里The surface is what callers depend on. Fix it first, because every later change behind it is free and every change to it breaks someone.对外接口是调用方依赖的东西。要先把它定下来,因为之后改它背后的东西没有代价,而改接口本身一定会影响到别人。
Uses用到

Do this操作

  1. Expose exactly two paths: `POST /v1/chat/completions` and `GET /health`.只暴露两个路径:`POST /v1/chat/completions` 和 `GET /health`。
  2. Accept and return the OpenAI chat format unchanged, so existing SDKs and editors work.原样接受和返回 OpenAI chat 格式,这样现有的 SDK 和编辑器都能直接用。
  3. Write down what a key carries: app name, scopes, rate, quota.写下每个密钥附带的信息:应用名、权限范围、速率、配额。
You are done when完成标志You can list every path, and for each one say which scope it needs.你能列出每个路径,并说出它需要哪种权限。
Produces产出A written contract: two paths, one format, four key attributes.一份书面契约:两个路径、一种格式、四个密钥属性。
Feeds供给
02Build the key store建立密钥库
Why this step is here为什么这一步排在这里Identity comes before the handler, because the handler's first act is to ask who is calling.身份在处理函数之前,因为处理函数做的第一件事就是问“谁在调用”。
Uses用到

Do this操作

  1. Create a table with a hash column and no column for the plain secret.建一张表,只有哈希列,不存明文密钥。
  2. `issue()` returns the secret once. `authenticate()` hashes what it receives and compares.`issue()` 只返回一次密钥。`authenticate()` 对收到的密钥做哈希再比对。
  3. Record each accepted call so rate and quota can be counted.记录每次通过的调用,用来统计速率和配额。
  4. Raise an error that carries the HTTP status: 401 unknown, 403 wrong scope, 429 over limit.抛出带 HTTP 状态码的错误:401 未知密钥,403 权限不符,429 超限。
labs/m02_gateway/keys.py · keys
class KeyStore:
    def __init__(self, path: Path):
        self.db = sqlite3.connect(str(path), check_same_thread=False)
        self.db.execute("""CREATE TABLE IF NOT EXISTS keys (
            key_id TEXT PRIMARY KEY, app TEXT NOT NULL, hash TEXT NOT NULL UNIQUE,
            scopes TEXT NOT NULL, rate_per_min INTEGER NOT NULL, daily_quota INTEGER NOT NULL,
            revoked INTEGER NOT NULL DEFAULT 0)""")
        self.db.execute("CREATE TABLE IF NOT EXISTS hits (key_id TEXT, ts REAL)")
        self.db.commit()

    @staticmethod
    def _hash(secret: str) -> str:
        return hashlib.sha256(secret.encode()).hexdigest()

    def issue(self, app: str, scopes: str = "chat", rate_per_min: int = 30, daily_quota: int = 1000) -> str:
        """Create a key. The plain secret is returned once and never stored."""
        secret = "lab_" + secrets.token_urlsafe(24)
        key_id = "k_" + secrets.token_hex(4)
        self.db.execute("INSERT INTO keys VALUES (?,?,?,?,?,?,0)",
                        (key_id, app, self._hash(secret), scopes, rate_per_min, daily_quota))
        self.db.commit()
        return secret

    def revoke(self, app: str) -> None:
        self.db.execute("UPDATE keys SET revoked = 1 WHERE app = ?", (app,))
        self.db.commit()

    def authenticate(self, header: Optional[str], scope: str = "chat", now: Optional[float] = None) -> dict:
        """Return the key row, or raise PermissionError carrying an HTTP status."""
        now = now or time.time()
        if not header or not header.startswith("Bearer "):
            raise PermissionError(401, "missing bearer token")
        row = self.db.execute("SELECT key_id, app, scopes, rate_per_min, daily_quota, revoked "
                              "FROM keys WHERE hash = ?", (self._hash(header[7:].strip()),)).fetchone()
        if not row or row[5]:
            raise PermissionError(401, "unknown or revoked key")
        key_id, app, scopes, rate, quota, _ = row
        if scope not in scopes.split(","):
            raise PermissionError(403, f"key lacks scope '{scope}'")
        minute = self.db.execute("SELECT count(*) FROM hits WHERE key_id=? AND ts>?", (key_id, now - 60)).fetchone()[0]
        if minute >= rate:
            raise PermissionError(429, "rate limit reached")
        day = self.db.execute("SELECT count(*) FROM hits WHERE key_id=? AND ts>?", (key_id, now - 86400)).fetchone()[0]
        if day >= quota:
            raise PermissionError(429, "daily quota reached")
        self.db.execute("INSERT INTO hits VALUES (?,?)", (key_id, now))
        self.db.commit()
        return {"key_id": key_id, "app": app, "scopes": scopes.split(",")}
You are done when完成标志Open the database file. No secret appears in it.打开数据库文件,里面看不到任何明文密钥。
Produces产出`KeyStore` with issue, revoke, and authenticate.`KeyStore`:签发、吊销、验证。
Feeds供给
03Write the gateway handler编写网关处理函数
Why this step is here为什么这一步排在这里It needs the key store to exist and the engine contract to forward to. It is the first piece that joins two modules.它需要密钥库已经存在,也需要引擎的契约作为转发目标。这是第一个把两个模块连起来的部件。

Do this操作

  1. On POST: authenticate with scope `chat`, strip `tools` if the key lacks scope `tools`, forward, return.POST 时:用 `chat` 权限验证;如果密钥没有 `tools` 权限就去掉 `tools`;转发;返回。
  2. On GET /health with no key: answer liveness only.无密钥访问 GET /health 时:只回答是否存活。
  3. On GET /health with a key: add detail.带密钥访问 GET /health 时:附加详情。
  4. Keep the upstream call behind one function so the engine can be swapped.把上游调用收在一个函数后面,方便更换引擎。
labs/m02_gateway/gateway.py · gateway
def make_handler(keys: KeyStore, upstream: Optional[Callable] = None):
    upstream = upstream or (lambda body: llm.chat(body.get("messages", []), body.get("tools"),
                                                  body.get("model"), body.get("max_tokens", 512)))

    class Gateway(BaseHTTPRequestHandler):
        def _send(self, status: int, obj: dict) -> None:
            data = json.dumps(obj).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)

        def do_GET(self):  # noqa: N802
            if self.path != "/health":
                return self._send(404, {"error": "not found"})
            auth = self.headers.get("Authorization")
            if not auth:                                   # a supervisor needs no key
                return self._send(200, {"status": "ok", "authenticated": False})
            try:
                row = keys.authenticate(auth)
            except PermissionError as e:
                return self._send(e.args[0], {"error": e.args[1]})
            return self._send(200, {"status": "ok", "authenticated": True, "app": row["app"], "scopes": row["scopes"]})

        def do_POST(self):  # noqa: N802
            if self.path != "/v1/chat/completions":
                return self._send(404, {"error": "not found"})
            try:
                row = keys.authenticate(self.headers.get("Authorization"), "chat")
            except PermissionError as e:
                return self._send(e.args[0], {"error": e.args[1]})
            body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}")
            if body.get("tools") and "tools" not in row["scopes"]:
                body.pop("tools")                          # scope decides who gets tools
            return self._send(200, upstream(body))

        def log_message(self, *args):
            return

    return Gateway


def serve(keys: KeyStore, port: int = 0, upstream: Optional[Callable] = None):
    """Start in a background thread. Returns (server, base_url)."""
    server = ThreadingHTTPServer(("127.0.0.1", port), make_handler(keys, upstream))
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return server, f"http://127.0.0.1:{server.server_address[1]}"
You are done when完成标志The handler has no code path that reaches the engine without `authenticate` succeeding.处理函数里不存在绕过 `authenticate` 就能到达引擎的代码路径。
Produces产出`serve()`: a running gateway and its base URL.`serve()`:一个运行中的网关及其 base URL。
04Prove each rule with a request用请求逐条验证规则
Why this step is here为什么这一步排在这里A gateway is a list of refusals. Each one is tested before anything is built on top.网关本质上是一组拒绝规则。在其上构建任何东西之前,要逐条测试。

Do this操作

  1. Run the demo. It issues two keys with different scopes and makes eight calls.运行 demo。它签发两个不同权限的密钥,并发出八次调用。
  2. Match each output line to the rule that produced it.把每行输出对应到产生它的规则。
run
python3 -m labs.m02_gateway.demo
Recorded output / 记录的输出 · m02.demo
1 liveness, no key      -> (200, {'status': 'ok', 'authenticated': False})
2 chat, no key          -> (401, {'error': 'missing bearer token'})
3 chat, website key     -> 200 (fake model) You said: hello
4 tools, website key    -> 200 False (tools stripped: no scope)
5 tools, agent key      -> 200 search_policy
6 4th call in a minute  -> (429, {'error': 'rate limit reached'})
7 revoked agent key     -> (401, {'error': 'unknown or revoked key'})
8 website key unaffected-> 429 (still rate limited, and still valid)
You are done when完成标志You see 200, 401, 429, and 401 after revoke, and line 4 shows tools removed for the website key.你能看到 200、401、429,以及吊销后的 401;第 4 行显示网站密钥的工具被去掉了。
Produces产出Evidence that authentication, scope, rate, and revoke each work alone.身份验证、权限、限流、吊销各自独立生效的证据。
Feeds供给
05Issue one key per application每个应用签发一个密钥
Why this step is here为什么这一步排在这里Now that the rules hold, give every caller its own identity. Doing this before building callers means none of them ever shares a key.规则都成立之后,给每个调用方一个独立身份。在开发调用方之前就这么做,就不会出现共用密钥的情况。
Uses用到

Do this操作

  1. Issue a key for each caller you have: the website, a coding agent, an eval job.为现有的每个调用方签发密钥:网站、编程智能体、评估任务。
  2. Give the public website `chat` only, a low rate, and a quota.公开网站只给 `chat` 权限、较低的速率和一个配额。
  3. Store each secret in that caller's own secret store. Never in a repository.把每个密钥存到对应调用方自己的密钥存储里。绝不放进代码仓库。
python
from pathlib import Path
from labs.m02_gateway.keys import KeyStore

keys = KeyStore(Path("keys.db"))
print(keys.issue("website", scopes="chat", rate_per_min=6, daily_quota=400))
print(keys.issue("coding-agent", scopes="chat,tools", rate_per_min=60))
# later: keys.revoke("website")   # the other callers are unaffected
You are done when完成标志Revoking one application's key leaves the others working.吊销一个应用的密钥后,其他应用照常工作。
Produces产出One key per caller. The harness reads the scope to decide who gets tools.每个调用方一个密钥。Harness 读取权限范围来决定谁能用工具。
Feeds供给
06Apply the model router in the gateway在网关里应用模型路由
Why this step is here为什么这一步排在这里The gateway is the one place every request passes, so model choice belongs here and callers stay unaware of it.网关是所有请求的必经之路,所以选模型的逻辑放在这里,调用方不需要知道。

Do this操作

  1. Before forwarding, call the router from the inference module.转发之前,调用推理模块里的路由函数。
  2. If it returns a model tag, set `model`. If it returns a base URL, forward there. If it returns nothing, change nothing.返回模型 tag 就设置 `model`;返回 base URL 就转发到那里;返回空就什么都不改。
labs/m02_gateway/route.py · route
def upstream(body: dict) -> dict:
    choice = resolve_for_request(body) or {}
    if "model" in choice:
        body["model"] = choice["model"]
    base = choice.get("base_url")          # None means the default engine
    return forward(body, base)
run
python3 -m labs.m02_gateway.route
Recorded output / 记录的输出 · m02.route
1 text, no model    -> 200 {'model': 'workhorse-35b', 'base_url': 'default engine'}
  image, no model   -> 200 {'model': 'vision-27b', 'base_url': 'default engine'}
  short, no model   -> 200 {'model': None, 'base_url': 'http://127.0.0.1:8082/v1'}
  text, model=mine  -> 200 {'model': 'mine', 'base_url': 'default engine'}
2 explicit model untouched: True
You are done when完成标志A text request goes to the default model, an image to the vision model, a short request to the fast runtime, and a request that names its model is forwarded untouched.文本请求发往默认模型,图片请求发往视觉模型,短请求发往快速运行时,指定了模型的请求原样转发。
Produces产出Callers send no model name and still reach the right model.调用方不写模型名,也能到达正确的模型。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
07Open one public door只开一个对外入口Not executed in the labslab 中未执行
Why this step is here为什么这一步排在这里Exposure is last. Only a gateway that already refuses correctly should be reachable from outside.对外暴露放在最后。只有已经能正确拒绝请求的网关,才应该从外部可达。
Uses用到

Do this操作

  1. Run the gateway on localhost.让网关运行在 localhost 上。
  2. Publish only the gateway port through an encrypted tunnel. Forward no router port.只通过加密隧道发布网关端口。不要在路由器上做端口转发。
  3. From outside, confirm the gateway answers and the engine port does not.从外部确认网关有响应,而引擎端口没有。
bash
# One option: Tailscale Funnel. Check the flags with: tailscale funnel --help
tailscale funnel --bg 8000

# From a phone on mobile data:
curl https://<your-funnel-host>/health          # {"status":"ok","authenticated":false}
curl https://<your-funnel-host>:11434/          # must fail

Tunnel commands change between versions. Confirm the flags on your machine.隧道命令在不同版本间会变化。请在你的机器上确认参数。

This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。

Checked on the reference machine在参考机器上的检查结果Not checked on a machine yet. On your own machine run the command below. It only reads, and it writes the result here when you add --write.还没有在机器上检查过。在你自己的机器上运行下面的命令。它只做读取操作;加上 --write 后会把结果写到这里。
run
python3 labs/machine/check.py --write
You are done when完成标志The public URL returns liveness without a key and 401 on chat without a key.公网 URL 不带密钥返回存活状态;不带密钥访问 chat 返回 401。
Produces产出A public base URL that other machines and hosted apps can call.一个公网 base URL,供其他机器和托管应用调用。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。

How it works with the other parts它如何与其他部分协作

What went wrong in the real build真实搭建中踩过的坑

2026-09

Sixteen thousand log lines from one probe一个探针产生了一万六千行日志

What happened发生了什么
The health endpoint required a key. The watchdog sent none, so 58 percent of the server log was 401 responses and the supervisor could not tell healthy from sick.健康检查接口要求密钥,而看门狗没有带。结果服务日志的 58% 都是 401,监管进程也分不清服务是否健康。
Fix修复
Answer liveness without a key and with no configuration detail. Keep detail behind a key.无密钥时只回答是否存活,不带任何配置细节。详情仍需密钥。
Lesson教训
Separate liveness from detail, and keep noise out of logs that other jobs read.把存活检查和详情分开,别让噪音进入其他任务要读的日志。
2026-08

A 401 that was a typo一个由笔误造成的 401

What happened发生了什么
A client sent two spaces after the word Bearer. The gateway rejected it and the outage was blamed on the gateway.客户端在 Bearer 后面多打了一个空格。网关拒绝了请求,故障却被归咎于网关。
Fix修复
Trim the token, and log the reason for every refusal.去掉令牌首尾空白,并记录每次拒绝的原因。
Lesson教训
A refusal without a logged reason costs an afternoon.不记录原因的拒绝,会浪费一个下午。

The same idea on other platforms同样的思路在其他平台上

Platform平台How this module maps本模块如何对应
DatabricksUnity Gateway (formerly AI Gateway) governs access to models, MCP servers, and skills, with guardrails, rate limits, and usage tracking. Identity comes from workspace OAuth and service principals. Deployed agents are queried with an OAuth token.Unity Gateway(原 AI Gateway)统一管控对模型、MCP 服务和技能的访问,提供护栏、限流和用量追踪。身份来自工作区 OAuth 和服务主体。调用已部署的智能体需要 OAuth 令牌。
IBM watsonxwatsonx.ai exposes inference endpoints behind IAM keys. A model gateway routes to third-party providers. Orchestrate exposes agent endpoints.watsonx.ai 的推理端点由 IAM 密钥保护。模型网关可路由到第三方供应商。Orchestrate 提供智能体端点。
CodexCodex is a client. It needs a provider base URL and key. If you point it at your gateway, issue it its own key.Codex 是客户端,需要供应商的 base URL 和密钥。如果让它连你的网关,就给它单独签发一个密钥。
CursorA client. Give it a key of its own and a base URL override where supported.也是客户端。给它单独的密钥,并在支持的地方覆盖 base URL。
Claude Code / Agent SDKA client. A base URL setting can route it through your gateway. Issue a separate key per machine.也是客户端。通过 base URL 设置可以让它走你的网关。每台机器签发一个独立密钥。
Another machineA small web app or an off-the-shelf LLM proxy does the same job on any host. The lab gateway is standard library only.任何主机上,一个小型 Web 应用或现成的 LLM 代理都能完成同样的工作。lab 网关只用了标准库。

Step-by-step guides per platform各平台的分步指南

Explain it back讲给自己听

Answer aloud first. Then open the answer and compare.先自己说一遍答案,再展开对照。

Why one key per application?为什么每个应用一个密钥?
A strong answer参考答案So you can limit and revoke one integration without touching the others, and so logs attribute every request.这样可以单独限制和吊销某一个集成而不影响其他,而且日志能把每个请求归到具体的调用方。
Why is liveness unauthenticated while detail is not?为什么存活检查不需要认证,而详情需要?
A strong answer参考答案A supervisor has to tell healthy from sick without holding a key. Detail reveals configuration, so it stays behind one.监管进程不持有密钥,也必须能分辨服务是否健康。详情会暴露配置,所以要放在密钥之后。
Why does the gateway strip tools instead of rejecting the request?为什么网关是去掉工具,而不是直接拒绝请求?
A strong answer参考答案The caller still gets a useful chat answer, and capability is decided in one place by the key. A public key can never reach a tool, whatever the client sends.调用方仍然能得到有用的聊天回答,而能力由密钥在一个地方统一决定。无论客户端发什么,公开密钥都碰不到工具。
In what order did you build this module, and why that order?这个模块你是按什么顺序搭建的?为什么?
A strong answer参考答案Surface, keys, handler, proof, issue, routing, exposure. Each step uses the one before, and the public door opens only after every refusal has been tested.接口、密钥、处理函数、验证、签发、路由、对外暴露。每一步都依赖上一步,而且只有在每条拒绝规则都测试过之后才对外开放。

Terms术语

Scope权限范围(Scope)A named capability attached to a key, such as chat or tools.附在密钥上的一项具名能力,例如 chat 或 tools。
Quota配额A cap on total calls over a longer period, here one day.较长周期内的调用总量上限,这里是一天。
Liveness存活检查The answer to one question: is this process serving?只回答一个问题:这个进程在提供服务吗?

From the live build来自实时构建

Recent changes and files the sync job filed under this module. These lines are in English as written in the build.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。

Ask the tutor about this module就本模块向导师提问