chatBridgeService.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
  2. import {
  3. chatResponseToResponses,
  4. responsesRequestToChat,
  5. ResponsesSseTranslator,
  6. type BridgeSseEvent,
  7. type DiagnosticFn,
  8. type ResponsesCreateParams,
  9. } from './chatBridgeTranslate';
  10. /**
  11. * 内置 Responses→Chat 桥接:给只会 /chat/completions 的端点(老 Ollama / vLLM / Xinference)
  12. * 套一层本地翻译代理。Codex 连这里的 /v1/responses,桥接翻译后转发上游。
  13. *
  14. * 安全边界:只绑 127.0.0.1 随机端口;不持有任何密钥(incoming Authorization 原样透传,
  15. * key 由 Codex 侧 env_key 注入);只接受 POST /v1/responses,其余一律 404。
  16. * 消息格式转换全部在 chatBridgeTranslate.ts,这里只管 HTTP 与生命周期。
  17. */
  18. export interface ChatBridgeOptions {
  19. /** 上游 chat 端点 API 根(形如 http://host:11434/v1) */
  20. upstreamBaseUrl: string;
  21. /** 额外转发头(来自模型配置的 headersJson) */
  22. headers?: Record<string, string> | null;
  23. onDiagnostic?: DiagnosticFn;
  24. }
  25. export interface ChatBridgeInfo {
  26. url: string;
  27. port: number;
  28. upstreamBaseUrl: string;
  29. }
  30. function readBody(req: IncomingMessage): Promise<string> {
  31. return new Promise((resolve, reject) => {
  32. const chunks: Buffer[] = [];
  33. req.on('data', (chunk: Buffer) => chunks.push(chunk));
  34. req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
  35. req.on('error', reject);
  36. });
  37. }
  38. function writeSseEvents(res: ServerResponse, events: BridgeSseEvent[]): void {
  39. for (const item of events) {
  40. res.write(`event: ${item.event}\ndata: ${JSON.stringify(item.data)}\n\n`);
  41. }
  42. }
  43. export class ChatBridgeService {
  44. #server: Server | null = null;
  45. #info: ChatBridgeInfo | null = null;
  46. #options: ChatBridgeOptions | null = null;
  47. /** 诊断里区分同一轮里的多次上游请求 */
  48. #seq = 0;
  49. /** 装配层(index.ts)注入的诊断出口;start 时的 onDiagnostic 优先 */
  50. #diagnostic: DiagnosticFn | null = null;
  51. get info(): ChatBridgeInfo | null {
  52. return this.#info;
  53. }
  54. setDiagnostic(fn: DiagnosticFn | null): void {
  55. this.#diagnostic = fn;
  56. }
  57. #diag(line: string): void {
  58. (this.#options?.onDiagnostic ?? this.#diagnostic)?.(line);
  59. }
  60. async start(options: ChatBridgeOptions): Promise<ChatBridgeInfo> {
  61. await this.stop();
  62. this.#options = options;
  63. const server = createServer((req, res) => {
  64. void this.#handle(req, res);
  65. });
  66. this.#server = server;
  67. await new Promise<void>((resolve, reject) => {
  68. server.once('error', reject);
  69. server.listen(0, '127.0.0.1', () => resolve());
  70. });
  71. const address = server.address();
  72. const port = typeof address === 'object' && address ? address.port : 0;
  73. this.#info = { url: `http://127.0.0.1:${port}/v1`, port, upstreamBaseUrl: options.upstreamBaseUrl };
  74. this.#diag(`chat-bridge: 已启动 ${this.#info.url} → ${options.upstreamBaseUrl}`);
  75. return this.#info;
  76. }
  77. async stop(): Promise<void> {
  78. const server = this.#server;
  79. this.#server = null;
  80. this.#info = null;
  81. this.#options = null;
  82. if (!server) return;
  83. await new Promise<void>((resolve) => server.close(() => resolve()));
  84. }
  85. #forwardHeaders(req: IncomingMessage): Record<string, string> {
  86. const headers: Record<string, string> = {
  87. 'content-type': 'application/json',
  88. // 上游 gzip 会把 SSE 行切碎,显式要求不压缩
  89. 'accept-encoding': 'identity',
  90. };
  91. const authorization = req.headers.authorization;
  92. if (authorization) headers.authorization = authorization;
  93. for (const [key, value] of Object.entries(this.#options?.headers ?? {})) {
  94. if (value) headers[key.toLowerCase()] = value;
  95. }
  96. return headers;
  97. }
  98. #failJson(res: ServerResponse, status: number, message: string): void {
  99. if (res.headersSent) {
  100. res.end();
  101. return;
  102. }
  103. res.writeHead(status, { 'content-type': 'application/json' });
  104. res.end(JSON.stringify({ error: { message, type: 'bridge_error' } }));
  105. }
  106. async #handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
  107. if (req.method !== 'POST' || req.url !== '/v1/responses') {
  108. this.#failJson(res, 404, 'not found');
  109. return;
  110. }
  111. let responsesReq: ResponsesCreateParams;
  112. try {
  113. responsesReq = JSON.parse(await readBody(req)) as ResponsesCreateParams;
  114. } catch {
  115. this.#failJson(res, 400, '请求体不是合法 JSON');
  116. return;
  117. }
  118. const options = this.#options;
  119. if (!options) {
  120. this.#failJson(res, 503, '桥接未配置上游');
  121. return;
  122. }
  123. const chatReq = responsesRequestToChat(responsesReq, (line) => this.#diag(line));
  124. const upstream = `${options.upstreamBaseUrl.replace(/\/+$/u, '')}/chat/completions`;
  125. const id = ++this.#seq;
  126. const t0 = Date.now();
  127. const secs = (at: number = Date.now()): string => `${((at - t0) / 1000).toFixed(1)}s`;
  128. const inputText = typeof responsesReq.input === 'string' ? responsesReq.input : JSON.stringify(responsesReq.input ?? '');
  129. const messages = Array.isArray(chatReq.messages) ? chatReq.messages : [];
  130. this.#diag(
  131. `chat-bridge: #${id} 起 round model=${responsesReq.model ?? '?'} stream=${chatReq.stream ? 'Y' : 'N'} ` +
  132. `tools=${Array.isArray(chatReq.tools) ? chatReq.tools.length : 0} messages=${messages.length} 输入≈${inputText.length}字 → ${upstream}`,
  133. );
  134. /**
  135. * Codex 拿不到响应就会挂断重来,而自部署的多是单槽推理:
  136. * 不取消上游的话,被放弃的那次生成会继续占着槽,下一次请求排在它后面 —— 越重试越慢。
  137. */
  138. const controller = new AbortController();
  139. let clientGone = false;
  140. res.once('close', () => {
  141. if (res.writableEnded) return;
  142. clientGone = true;
  143. controller.abort();
  144. this.#diag(`chat-bridge: #${id} Codex 提前断开(${secs()}),已取消上游请求`);
  145. });
  146. /**
  147. * 流式请求先把 SSE 开起来再等上游:单槽自部署服务光 prefill 就要几分钟,
  148. * 那期间 Codex 一个字节都收不到就会掐断重发(重发又把同一个 prompt 重新排一遍队)。
  149. */
  150. const translator = chatReq.stream ? new ResponsesSseTranslator(responsesReq, (line) => this.#diag(line)) : null;
  151. let events = 0;
  152. const write = (items: BridgeSseEvent[]): void => {
  153. events += items.length;
  154. writeSseEvents(res, items);
  155. };
  156. if (translator) {
  157. res.writeHead(200, {
  158. 'content-type': 'text/event-stream',
  159. 'cache-control': 'no-cache',
  160. connection: 'keep-alive',
  161. });
  162. write(translator.begin());
  163. }
  164. let upstreamRes: Response;
  165. try {
  166. upstreamRes = await fetch(upstream, {
  167. method: 'POST',
  168. headers: this.#forwardHeaders(req),
  169. body: JSON.stringify(chatReq),
  170. signal: controller.signal,
  171. });
  172. } catch (error) {
  173. if (clientGone) return;
  174. const message = error instanceof Error ? error.message : String(error);
  175. this.#diag(`chat-bridge: #${id} 上游不可达(${secs()}):${message}`);
  176. if (translator) {
  177. write(translator.fail(`桥接上游不可达:${message}`));
  178. res.end();
  179. return;
  180. }
  181. this.#failJson(res, 502, `桥接上游不可达:${message}`);
  182. return;
  183. }
  184. if (!upstreamRes.ok) {
  185. const text = await upstreamRes.text().catch(() => '');
  186. if (clientGone) return;
  187. const detail = `桥接上游返回 HTTP ${upstreamRes.status}:${text.slice(0, 500)}`;
  188. this.#diag(`chat-bridge: #${id} 上游 HTTP ${upstreamRes.status}(${secs()}):${text.slice(0, 300)}`);
  189. if (translator) {
  190. write(translator.fail(detail));
  191. res.end();
  192. return;
  193. }
  194. this.#failJson(res, upstreamRes.status, detail);
  195. return;
  196. }
  197. if (!translator) {
  198. try {
  199. const chatJson = (await upstreamRes.json()) as Parameters<typeof chatResponseToResponses>[0];
  200. if (clientGone) return;
  201. res.writeHead(200, { 'content-type': 'application/json' });
  202. res.end(JSON.stringify(chatResponseToResponses(chatJson, responsesReq)));
  203. this.#diag(`chat-bridge: #${id} 非流式完成(${secs()})`);
  204. } catch (error) {
  205. if (clientGone) return;
  206. this.#diag(`chat-bridge: #${id} 非流式解析失败(${secs()})`);
  207. this.#failJson(res, 502, `桥接解析上游响应失败:${error instanceof Error ? error.message : String(error)}`);
  208. }
  209. return;
  210. }
  211. // 流式:边收边翻边发(SSE 已在请求到达时就开好,translator 此时必定存在)
  212. let bytes = 0;
  213. try {
  214. if (!upstreamRes.body) throw new Error('上游响应没有 body');
  215. const reader = upstreamRes.body.getReader();
  216. const decoder = new TextDecoder();
  217. for (;;) {
  218. const { done, value } = await reader.read();
  219. if (done) break;
  220. bytes += value?.byteLength ?? 0;
  221. write(translator.push(decoder.decode(value, { stream: true })));
  222. }
  223. write(translator.push(decoder.decode()));
  224. write(translator.finish());
  225. this.#diag(`chat-bridge: #${id} 转发完成(${secs()},上游 ${bytes}B → ${events} 个事件)`);
  226. } catch (error) {
  227. // 客户端已走 = 我们自己主动 abort,不该再当成上游故障去报告警
  228. if (clientGone) return;
  229. const message = error instanceof Error ? error.message : String(error);
  230. this.#diag(`chat-bridge: #${id} 流式转发中断(${secs()}):${message}`);
  231. write(translator.fail(message));
  232. }
  233. res.end();
  234. }
  235. }
  236. /** 模块级单例:providerService 应用/清除模型时启停,装配层退出时兜底 stop */
  237. export const chatBridge = new ChatBridgeService();