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工作原理
- Keys are stored as hashes. Each key has an app name, scopes, a per-minute rate, and a daily quota.密钥以哈希形式存储。每个密钥对应一个应用名、权限范围、每分钟速率和每日配额。
- The gateway validates the key, checks scope and limits, then forwards. The engine stays on localhost.网关验证密钥、检查权限和限额,然后转发。引擎只监听 localhost。
- Scope decides capability. A key without the tools scope has tool definitions removed from its requests.权限范围决定能力。没有 tools 权限的密钥,请求里的工具定义会被去掉。
- Health has two levels: an unauthenticated liveness answer, and detail that needs a key.健康检查分两级:无需认证的存活应答,以及需要密钥才能看的详情。
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.py | Key validation, scopes, rate limits, quotas.密钥验证、权限范围、限流、配额。 |
| apps/agent-server/keys_admin.py | Issue, list, and revoke keys.签发、列出、吊销密钥。 |
| apps/agent-server/main.py | The HTTP endpoints.HTTP 接口。 |
| apps/claude-code-gateway/ | Translation proxy so a coding client can use local models.协议转换代理,让编程客户端可以使用本地模型。 |
Process map流程图
One request through the gateway一个请求如何通过网关
- 1Bearer token arrives收到 Bearer 令牌The caller sends its secret in the Authorization header.调用方在 Authorization 头里发送密钥。
- 2Hash and look up哈希并查找The secret is hashed and matched against stored hashes. The plain secret is never stored.对密钥做哈希,与存储的哈希比对。明文密钥从不保存。
- 3Scope权限范围Does this key have the scope the endpoint needs?该密钥是否具备此接口所需的权限?
- 4Rate and quota速率与配额Count this key's recent calls. Refuse with 429 when over.统计该密钥近期的调用次数。超限则返回 429。
- 5Shape the request调整请求Remove tools for keys without the tools scope. Apply the model router.对没有 tools 权限的密钥去掉工具定义。应用模型路由。
- 6Forward转发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 实际运行时打印的内容。
- 1Decide the public surface确定对外接口
- 2Build the key store建立密钥库
- 3Write the gateway handler编写网关处理函数
- 4Prove each rule with a request用请求逐条验证规则
- 5Issue one key per application每个应用签发一个密钥
- 6Apply the model router in the gateway在网关里应用模型路由
- 7Open one public door只开一个对外入口
01Decide the public surface确定对外接口
- the request and response format to preserve需要保持不变的请求和响应格式 ← Inference engineering推理工程 4: Call the endpoint the way every later layer will用后续各层都会用的方式调用端点
Do this操作
- Expose exactly two paths: `POST /v1/chat/completions` and `GET /health`.只暴露两个路径:`POST /v1/chat/completions` 和 `GET /health`。
- Accept and return the OpenAI chat format unchanged, so existing SDKs and editors work.原样接受和返回 OpenAI chat 格式,这样现有的 SDK 和编辑器都能直接用。
- Write down what a key carries: app name, scopes, rate, quota.写下每个密钥附带的信息:应用名、权限范围、速率、配额。
02Build the key store建立密钥库
Do this操作
- Create a table with a hash column and no column for the plain secret.建一张表,只有哈希列,不存明文密钥。
- `issue()` returns the secret once. `authenticate()` hashes what it receives and compares.`issue()` 只返回一次密钥。`authenticate()` 对收到的密钥做哈希再比对。
- Record each accepted call so rate and quota can be counted.记录每次通过的调用,用来统计速率和配额。
- Raise an error that carries the HTTP status: 401 unknown, 403 wrong scope, 429 over limit.抛出带 HTTP 状态码的错误:401 未知密钥,403 权限不符,429 超限。
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(",")}- API and gatewayAPI 与网关 3: Write the gateway handler编写网关处理函数 (authenticate()authenticate())
- Memory记忆 1: Fix the partition rule确定分区规则 (an authenticated identity to derive the partition from用于推导分区的已认证身份)
- SDKs and frameworksSDK 与框架 2: Give every SDK the same endpoint给每个 SDK 同一个端点 (a key with the tools scope带 tools 权限的密钥)
- Operations and deployment运维与部署 6: Back up what cannot be reproduced, and test the restore备份无法重新生成的东西,并测试恢复 (the key store, which is irreplaceable密钥库,它是不可替代的)
03Write the gateway handler编写网关处理函数
- authenticate()authenticate() ← API and gatewayAPI 与网关 2: Build the key store建立密钥库
- chat() as the upstream作为上游的 chat() ← Inference engineering推理工程 5: Write one client function and use it everywhere写一个客户端函数,全系统共用
Do this操作
- On POST: authenticate with scope `chat`, strip `tools` if the key lacks scope `tools`, forward, return.POST 时:用 `chat` 权限验证;如果密钥没有 `tools` 权限就去掉 `tools`;转发;返回。
- On GET /health with no key: answer liveness only.无密钥访问 GET /health 时:只回答是否存活。
- On GET /health with a key: add detail.带密钥访问 GET /health 时:附加详情。
- Keep the upstream call behind one function so the engine can be swapped.把上游调用收在一个函数后面,方便更换引擎。
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]}"- API and gatewayAPI 与网关 4: Prove each rule with a request用请求逐条验证规则 (the running gateway运行中的网关)
- API and gatewayAPI 与网关 6: Apply the model router in the gateway在网关里应用模型路由 (the upstream function to wrap要包装的上游函数)
- SDKs and frameworksSDK 与框架 2: Give every SDK the same endpoint给每个 SDK 同一个端点 (serve()serve())
- Operations and deployment运维与部署 1: List every service, its port, and its interpreter列出每个服务、它的端口和解释器 (the gateway process网关进程)
- Operations and deployment运维与部署 3: Write one status command写一条状态命令 (the unauthenticated health path无认证的健康检查路径)
04Prove each rule with a request用请求逐条验证规则
Do this操作
- Run the demo. It issues two keys with different scopes and makes eight calls.运行 demo。它签发两个不同权限的密钥,并发出八次调用。
- Match each output line to the rule that produced it.把每行输出对应到产生它的规则。
python3 -m labs.m02_gateway.demo1 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)- API and gatewayAPI 与网关 5: Issue one key per application每个应用签发一个密钥 (confidence that scopes and revoke work对权限和吊销机制的信心)
05Issue one key per application每个应用签发一个密钥
- confidence that scopes and revoke work对权限和吊销机制的信心 ← API and gatewayAPI 与网关 4: Prove each rule with a request用请求逐条验证规则
Do this操作
- Issue a key for each caller you have: the website, a coding agent, an eval job.为现有的每个调用方签发密钥:网站、编程智能体、评估任务。
- Give the public website `chat` only, a low rate, and a quota.公开网站只给 `chat` 权限、较低的速率和一个配额。
- Store each secret in that caller's own secret store. Never in a repository.把每个密钥存到对应调用方自己的密钥存储里。绝不放进代码仓库。
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- API and gatewayAPI 与网关 7: Open one public door只开一个对外入口 (keys for the outside callers给外部调用方的密钥)
06Apply the model router in the gateway在网关里应用模型路由
- resolve_for_request()resolve_for_request() ← Inference engineering推理工程 8: Route by task type, and fail safe按任务类型路由,并且失败时不出错
- the upstream function to wrap要包装的上游函数 ← API and gatewayAPI 与网关 3: Write the gateway handler编写网关处理函数
Do this操作
- Before forwarding, call the router from the inference module.转发之前,调用推理模块里的路由函数。
- 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 就转发到那里;返回空就什么都不改。
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)python3 -m labs.m02_gateway.route1 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: True07Open one public door只开一个对外入口Not executed in the labslab 中未执行
- keys for the outside callers给外部调用方的密钥 ← API and gatewayAPI 与网关 5: Issue one key per application每个应用签发一个密钥
- an engine that is not reachable directly一个无法被直接访问的引擎 ← Inference engineering推理工程 10: Keep the engine private让引擎保持私有
Do this操作
- Run the gateway on localhost.让网关运行在 localhost 上。
- Publish only the gateway port through an encrypted tunnel. Forward no router port.只通过加密隧道发布网关端口。不要在路由器上做端口转发。
- From outside, confirm the gateway answers and the engine port does not.从外部确认网关有响应,而引擎端口没有。
# 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 failTunnel 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 时没有运行这些命令。
python3 labs/machine/check.py --writeHow it works with the other parts它如何与其他部分协作
- Inference engineering推理工程The gateway forwards to the engine and applies the model router.网关把请求转发给引擎,并应用模型路由。
- Harness engineeringHarness 工程The harness sits behind the same contract and reads key scope to decide whether to offer tools.Harness 位于同一契约之后,并读取密钥权限来决定是否提供工具。
- Operations and deployment运维与部署The watchdog probes the unauthenticated health path. Keys and quotas are backed up.看门狗探测无需认证的健康检查路径。密钥和配额要备份。
- SDKs and frameworksSDK 与框架Any SDK that speaks the OpenAI format can use the gateway as its base URL.任何支持 OpenAI 格式的 SDK 都可以把网关当作 base URL。
What went wrong in the real build真实搭建中踩过的坑
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.把存活检查和详情分开,别让噪音进入其他任务要读的日志。
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本模块如何对应 |
|---|---|
| Databricks | Unity 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 watsonx | watsonx.ai exposes inference endpoints behind IAM keys. A model gateway routes to third-party providers. Orchestrate exposes agent endpoints.watsonx.ai 的推理端点由 IAM 密钥保护。模型网关可路由到第三方供应商。Orchestrate 提供智能体端点。 |
| Codex | Codex 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 和密钥。如果让它连你的网关,就给它单独签发一个密钥。 |
| Cursor | A client. Give it a key of its own and a base URL override where supported.也是客户端。给它单独的密钥,并在支持的地方覆盖 base URL。 |
| Claude Code / Agent SDK | A client. A base URL setting can route it through your gateway. Issue a separate key per machine.也是客户端。通过 base URL 设置可以让它走你的网关。每台机器签发一个独立密钥。 |
| Another machine | A 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?为什么每个应用一个密钥?
Why is liveness unauthenticated while detail is not?为什么存活检查不需要认证,而详情需要?
Why does the gateway strip tools instead of rejecting the request?为什么网关是去掉工具,而不是直接拒绝请求?
In what order did you build this module, and why that order?这个模块你是按什么顺序搭建的?为什么?
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.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。
- the spending dataset collector: fiscal-year scope never starts later than FY2021
- Answer guard: vendor names, answers given without a tool call, streaming gate; FINANCE on Qwen3 embeddings; wiki watcher batch cap, lock and wait; downloads script
- SOP — Operating the Local LLM Server
- Claude Code → your own models
- Bug Fixes — 2026-08-20, post-update
- Dynamic Gateway + Full-Capability Model Lineup
- 00 — Project Timeline: How build-host Got Built
- Stage 0 patches — ready to apply, deliberately NOT applied
- sandbox test suite for Step 5.7 (streaming + latency). Run: python3 test_streaming.py Tests against a REAL stub Ollama HTTP server (a live uvicorn process on a real port, speaking real SSE), not mocks — same discipline every prior step in this codebase used.
- Agent Server — apps/agent-server/main.py ========================================= STEP 2 of the "mini Claude Code" build (see AGENT_SERVER_GUIDE_v2.md). Step 1 — bare passthrough, plaintext-key auth. Built/tested 2026-07-27.
- end-to-end test through main.py's REAL FastAPI app. test_streaming.py proves agent_loop's streaming logic.
- what the chat box actually does (2026-10-06). chat_eval.py and agent_quiz.py call agent_loop.run(), the non-streaming path. The chat box streams.
- run the agent-server regression scripts (2026-09-30). Each is a plain script that exits non-zero on failure. Writes logs/tests.status.json. Safe: the brain test uses a throwaway <db>_test database and the endpoint tests use /tmp and stub model servers.
- measures the streaming win instead of asserting it. Replays THIS server's own real production numbers (from logs/agents/requests.jsonl: p50 26.3s, p90 88.7s, 72 tok/s effective) against a stub that generates at that same measured rate, and reports time-to-first- token vs total ...
- LocalAPI-Claude.command rev 2026-08-22b The one command for the Claude Code local API. Start, restart, or re-run after pulling a model. Idempotent.
- QUICKSTART-10-MIN.command Double-click this. It does everything: 1. installs litellm (if missing) 2. generates a key 3. writes a minimal config pointed at whichever model you actually have 4. starts the proxy in the background 5. tests it end to end 6.