|
| 1 | +import type { IncomingMessage } from "node:http"; |
| 2 | +import { createServer, ServerResponse } from "node:http"; |
| 3 | +import type { AddressInfo } from "node:net"; |
| 4 | +import { z } from "zod"; |
| 5 | +import type { Agent } from "../index"; |
| 6 | +import { ANSI } from "./utils"; |
| 7 | +import { stdout } from "node:process"; |
| 8 | +import type { ChatCompletionStreamOutput } from "@huggingface/tasks"; |
| 9 | + |
| 10 | +const REQUEST_ID_HEADER = "X-Request-Id"; |
| 11 | + |
| 12 | +const ChatCompletionInputSchema = z.object({ |
| 13 | + messages: z.array( |
| 14 | + z.object({ |
| 15 | + role: z.enum(["user", "assistant"]), |
| 16 | + content: z.string().or( |
| 17 | + z.array( |
| 18 | + z |
| 19 | + .object({ |
| 20 | + type: z.literal("text"), |
| 21 | + text: z.string(), |
| 22 | + }) |
| 23 | + .or( |
| 24 | + z.object({ |
| 25 | + type: z.literal("image_url"), |
| 26 | + image_url: z.object({ |
| 27 | + url: z.string(), |
| 28 | + }), |
| 29 | + }) |
| 30 | + ) |
| 31 | + ) |
| 32 | + ), |
| 33 | + }) |
| 34 | + ), |
| 35 | + /// Only allow stream: true |
| 36 | + stream: z.literal(true), |
| 37 | +}); |
| 38 | +function getJsonBody(req: IncomingMessage) { |
| 39 | + return new Promise((resolve, reject) => { |
| 40 | + let data = ""; |
| 41 | + req.on("data", (chunk) => (data += chunk)); |
| 42 | + req.on("end", () => { |
| 43 | + try { |
| 44 | + resolve(JSON.parse(data)); |
| 45 | + } catch (e) { |
| 46 | + reject(e); |
| 47 | + } |
| 48 | + }); |
| 49 | + req.on("error", reject); |
| 50 | + }); |
| 51 | +} |
| 52 | +class ServerResp extends ServerResponse { |
| 53 | + error(statusCode: number, reason: string) { |
| 54 | + this.writeHead(statusCode).end(JSON.stringify({ error: reason })); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +export function startServer(agent: Agent): void { |
| 59 | + const server = createServer({ ServerResponse: ServerResp }, async (req, res) => { |
| 60 | + res.setHeader(REQUEST_ID_HEADER, crypto.randomUUID()); |
| 61 | + res.setHeader("Content-Type", "application/json"); |
| 62 | + if (req.method === "POST" && req.url === "/v1/chat/completions") { |
| 63 | + let body: unknown; |
| 64 | + let requestBody: z.infer<typeof ChatCompletionInputSchema>; |
| 65 | + try { |
| 66 | + body = await getJsonBody(req); |
| 67 | + } catch { |
| 68 | + return res.error(400, "Invalid JSON"); |
| 69 | + } |
| 70 | + try { |
| 71 | + requestBody = ChatCompletionInputSchema.parse(body); |
| 72 | + } catch (err) { |
| 73 | + if (err instanceof z.ZodError) { |
| 74 | + return res.error(400, "Invalid ChatCompletionInput body \n" + JSON.stringify(err)); |
| 75 | + } |
| 76 | + return res.error(400, "Invalid ChatCompletionInput body"); |
| 77 | + } |
| 78 | + /// Ok, from now on we will send a SSE (Server-Sent Events) response. |
| 79 | + res.setHeaders( |
| 80 | + new Headers({ |
| 81 | + "Content-Type": "text/event-stream", |
| 82 | + "Cache-Control": "no-cache", |
| 83 | + Connection: "keep-alive", |
| 84 | + }) |
| 85 | + ); |
| 86 | + |
| 87 | + /// Prepend the agent's prompt |
| 88 | + const messages = [ |
| 89 | + { |
| 90 | + role: "system", |
| 91 | + content: agent.prompt, |
| 92 | + }, |
| 93 | + ...requestBody.messages, |
| 94 | + ]; |
| 95 | + |
| 96 | + for await (const chunk of agent.run(messages)) { |
| 97 | + if ("choices" in chunk) { |
| 98 | + res.write(`data: ${JSON.stringify(chunk)}\n\n`); |
| 99 | + } else { |
| 100 | + /// Tool call info |
| 101 | + /// /!\ We format it as a regular chunk of role = "tool" |
| 102 | + const chunkToolcallInfo = { |
| 103 | + choices: [ |
| 104 | + { |
| 105 | + index: 0, |
| 106 | + delta: { |
| 107 | + role: "tool", |
| 108 | + content: `Tool[${chunk.name}] ${chunk.tool_call_id}\n` + chunk.content, |
| 109 | + }, |
| 110 | + }, |
| 111 | + ], |
| 112 | + created: Math.floor(Date.now() / 1000), |
| 113 | + id: chunk.tool_call_id, |
| 114 | + model: "", |
| 115 | + system_fingerprint: "", |
| 116 | + } satisfies ChatCompletionStreamOutput; |
| 117 | + |
| 118 | + res.write(`data: ${JSON.stringify(chunkToolcallInfo)}\n\n`); |
| 119 | + } |
| 120 | + } |
| 121 | + res.end(); |
| 122 | + } else { |
| 123 | + res.error(404, "Route or method not found, try POST /v1/chat/completions"); |
| 124 | + } |
| 125 | + }); |
| 126 | + server.listen(process.env.PORT ? parseInt(process.env.PORT) : 9_999, () => { |
| 127 | + stdout.write(ANSI.BLUE); |
| 128 | + stdout.write(`Agent loaded with ${agent.availableTools.length} tools:\n`); |
| 129 | + stdout.write(agent.availableTools.map((t) => `- ${t.function.name}`).join("\n")); |
| 130 | + stdout.write(ANSI.RESET); |
| 131 | + stdout.write("\n"); |
| 132 | + console.log(ANSI.GRAY + `listening on http://localhost:${(server.address() as AddressInfo).port}` + ANSI.RESET); |
| 133 | + }); |
| 134 | +} |
0 commit comments