第 9 章 · 02 openaiserver.py OpenAI 兼容服务 本节摘要:本节深潜 ——一个零依赖的 OpenAI 兼容 HTTP 网关。 启动它后,任何 OpenAI 客户端都能直接对接 Colibrì 引擎:端点 、流式 SSE 响应、 、 (Anthropic 兼容)、 、 、 、 。本节还会把引擎侧的几条机制——continuous batching( )、grammar 约束输出( / )、speculative decoding、kvprefix 跨请求复用——串成"全栈如何工作"的完整图景。 内容来源:原项目源码 、 、 、 、 ⚠️ 注意: 故意"零依赖"——只用 Python 标准库( / / / )。这意味着无需 ,任何装了 Python 的机器都能跑。
本节摘要:本节深潜
c/openai_server.py——一个零依赖的 OpenAI 兼容 HTTP 网关。coli serve启动它后,任何 OpenAI 客户端都能直接对接 Colibrì 引擎:端点/v1/chat/completions、流式 SSE 响应、/v1/completions、/v1/messages(Anthropic 兼容)、/v1/models、/health、/profile、/experts。本节还会把引擎侧的几条机制——continuous batching(decode_batch.h)、grammar 约束输出(grammar.h/schema_gbnf.h)、speculative decoding、kv_prefix 跨请求复用——串成"全栈如何工作"的完整图景。
内容来源:原项目源码
c/openai_server.py、c/decode_batch.h、c/grammar.h、c/schema_gbnf.h、docs/serve_protocol.md
⚠️ 注意:
openai_server.py故意"零依赖"——只用 Python 标准库(http.server/threading/json/select)。这意味着无需pip install fastapi/uvicorn,任何装了 Python 的机器都能跑。代价是手写 HTTP/SSE,源码偏长(2600+ 行)。
openai_server.py 的全部端点及各自语义。decode_batch.h)如何把多请求合并到一次 decode。grammar.h/schema_gbnf.h)与 speculative decoding 的关系。default_engine():从源码旁找引擎二进制源码顶部 23-31 行的 default_engine() 把"引擎在哪"的检测逻辑明示出来:
def default_engine(): """The engine next to this file. Since #391 it is built as `colibri`; `glm` stays as a fallback so an old tree (or an old hand-built binary) still starts. Reported by @RDouglasSharp in #488: the default still said `glm`, so `python3 openai_server.py` on a clean checkout looked for a file the build no longer produces.""" for name in ("colibri", "colibri.exe", "glm", "glm.exe"): candidate = HERE / name if candidate.exists(): return candidate return HERE / "colibri"
要点:
colibri,老的 glm 名字保留作 fallback;colibri → colibri.exe → glm → glm.exe,匹配即返回;glm,导致 clean checkout 跑 python3 openai_server.py 找不到二进制。这种"先列后选"的写法是 Colibrì 处理"老布局兼容"的典型风格。
do_GET / do_POSTAPIHandler 继承 BaseHTTPRequestHandler,把所有端点分到 do_GET / do_POST / do_OPTIONS 三个方法里。GET 路径:
2076 def do_GET(self): 2080 path = urlsplit(self.path).path 2081 if path == "/health": # 健康检查(read-only, no auth) 2104 if path == "/profile": # per-turn PROF 快照,滚动 120 窗口 2122 if path == "/v1/models": # OpenAI 兼容模型列表 2125 elif path.startswith("/v1/models/") and ...: # 单个模型详情
POST 路径:
2145 def do_POST(self): 2152 path = urlsplit(self.path).path 2153 if path == "/v1/chat/completions": # OpenAI chat 主端点 2155 elif path == "/v1/completions": # OpenAI 旧 completions 2157 elif path == "/v1/messages": # Anthropic 兼容(翻译层,不是第二条引擎路径)
关键端点语义:
/health:read-only,无 auth,coli chat 在等模型加载时会轮询它判断引擎是否就绪;/profile:返回最近 120 turn 的 PROF(per-turn profile)快照,供 dashboard 实时绘图;/experts:专家热图数据(配合第 6 章 route_trace);/v1/chat/completions:OpenAI chat 主端点,支持 stream=true 走 SSE;/v1/messages:Anthropic 兼容——源码 863 行注释明说"A translation layer, NOT a second engine path",它把 Anthropic 形状的请求重写成 OpenAI 形状再走同一条引擎路径。stream=true 时,/v1/chat/completions 走 Server-Sent Events。每个生成的 token 被包成一个 data: {...}\n\n 帧,客户端逐帧解析、逐 token 渲染。源码用 select + 非阻塞读引擎 stdout 实现:
END 哨兵字节 b"\x01\x01END\x01\x01\n");openai_server.py 解析这行,转成 OpenAI 的 chat.completion.chunk 对象;Content-Type: text/event-stream,每帧 data: {json}\n\n,结束帧 data: [DONE]\n\n。这套协议就是 docs/serve_protocol.md 描述的"引擎 ↔ 服务"协议。引擎侧不感知 OpenAI 协议,只输出 (token, prof_snapshot, done?) 三元组;协议适配完全在 Python 侧——这又一次体现"厚 C 内核 + 薄 Python 粘合层"。
decode_batch.h服务端常常有多个并发请求(多用户 / 多会话)。decode_batch.h 让引擎把它们的 decode 步合并到一次大 batch:
收益:
/v1/chat/completions 路径里(源码 2223 行注释)说明:对话型端点会让调度器把同一 conversation 钉到同一 slot(配合 kv_prefix 复用),/v1/completions 则让调度器自由选 free slot。
grammar.h / schema_gbnf.hgrammar.h 实现 GBNF(类 BNF)语法约束——客户端可以传一个 grammar,引擎保证输出严格符合该语法。典型用法:
schema_gbnf.h 把 JSON Schema 翻译成 GBNF,引擎只能产出合法 JSON;tool_call 形状。机制上,grammar 在每一步采样前"剪枝"词表——只保留 grammar 当前状态允许的 token,再做温度采样。这是"语法正确性硬约束",和 token-exact forward validation 的精神一致:绝不让随机采样破坏结构。
openai_server.py 还串联了 speculative decoding(推测解码)。Colibrì 的实现:
源码注释明确写:speculative 可禁用,当 acceptance 不 repay verification——这是 Colibrì "诚实研究"心法在加速技巧上的落地。一个看起来该快的优化,如果实测 A/B 没收益就关掉,绝不"为了用而上"。
第 7 章 02 节的 kv_prefix 在服务端被自然利用:
/v1/chat/completions 把同一 conversation_id 钉到同一 slot,正是为了让 kv_prefix 命中。后果:多轮对话服务的"第二轮开始"延迟显著低于首轮,因为绝大部分 prompt 已经在 slot 里。
openai_server.py 是零依赖(只用 Python 标准库)的 OpenAI 兼容网关,端点包括 /v1/chat/completions(主)、/v1/completions、/v1/messages(Anthropic 翻译层)、/v1/models、/health、/profile、/experts。default_engine() 按 colibri → glm 顺序找引擎二进制(#391 改名、#488 修过 default bug)。(token, prof, done) 三元组,协议适配在 Python 侧——"厚 C 内核 + 薄 Python 粘合"。decode_batch.h)把多请求 decode 合并,共享专家读取和 GPU 算力;对话型端点把同一 conversation 钉同一 slot 配合 kv_prefix。grammar.h/schema_gbnf.h)在采样前剪枝词表保证结构正确;speculative decoding(MTP + grammar-forced)端到端测,acceptance 不够就关。下一节是全书最后一节:Web/Desktop/Docker 全栈,以及九章机制深潜的整体回顾。