Spaces:
Sleeping
Sleeping
Download rag/src/server.ts from NeonatalDAO/askneo: direct link, hf CLI and curl.
- Browser
- Download file 4.66 kB
-
https://huggingface.co/spaces/NeonatalDAO/askneo/resolve/main/rag/src/server.ts
- Command line
-
hf download hf://spaces/NeonatalDAO/askneo/rag/src/server.ts
-
curl -L -o server.ts https://huggingface.co/spaces/NeonatalDAO/askneo/resolve/main/rag/src/server.ts
4.66 kB
| import http from "node:http"; | |
| import { ask } from "./pipeline.js"; | |
| import { VectorStore } from "./store.js"; | |
| import type { ChatMessage } from "./types.js"; | |
| /** | |
| * Dev server for the RAG pipeline (zero extra dependencies). | |
| * | |
| * GET /health -> { ok, index: manifest | null } | |
| * POST /ask -> RagAnswer JSON | |
| * body: { question: string, history?: ChatMessage[], rerank?: boolean } | |
| * POST /ask?stream=1 -> SSE: `delta` events with text, final `result` event | |
| * | |
| * The index is loaded once at startup and kept warm. If no index exists yet | |
| * the server still starts and /ask answers 503 with instructions. | |
| */ | |
| const PORT = Number(process.env.RAG_PORT ?? 8787); | |
| let index: VectorStore | null = null; | |
| let indexError = ""; | |
| async function loadIndex(): Promise<void> { | |
| try { | |
| index = await VectorStore.connect(); | |
| console.log(`Connected to Pinecone: ${index.size} vectors (${index.manifest.dims} dims).`); | |
| } catch (err) { | |
| indexError = err instanceof Error ? err.message : String(err); | |
| console.warn(`No usable index: ${indexError}`); | |
| } | |
| } | |
| function readBody(req: http.IncomingMessage): Promise<string> { | |
| return new Promise((resolve, reject) => { | |
| let data = ""; | |
| req.on("data", (c) => { | |
| data += c; | |
| if (data.length > 1_000_000) reject(new Error("body too large")); | |
| }); | |
| req.on("end", () => resolve(data)); | |
| req.on("error", reject); | |
| }); | |
| } | |
| function json(res: http.ServerResponse, status: number, body: unknown): void { | |
| res.writeHead(status, { | |
| "content-type": "application/json", | |
| "access-control-allow-origin": "*", | |
| }); | |
| res.end(JSON.stringify(body)); | |
| } | |
| interface AskBody { | |
| question?: string; | |
| history?: ChatMessage[]; | |
| rerank?: boolean; | |
| } | |
| const server = http.createServer(async (req, res) => { | |
| const url = new URL(req.url ?? "/", `http://localhost:${PORT}`); | |
| if (req.method === "OPTIONS") { | |
| res.writeHead(204, { | |
| "access-control-allow-origin": "*", | |
| "access-control-allow-methods": "GET, POST, OPTIONS", | |
| "access-control-allow-headers": "content-type", | |
| }); | |
| res.end(); | |
| return; | |
| } | |
| if (req.method === "GET" && url.pathname === "/health") { | |
| json(res, 200, { ok: true, index: index?.manifest ?? null, indexError: indexError || undefined }); | |
| return; | |
| } | |
| if (req.method === "POST" && url.pathname === "/ask") { | |
| if (!index) { | |
| json(res, 503, { | |
| error: `Vector store unavailable (${indexError}). Check PINECONE_API_KEY, then restart.`, | |
| }); | |
| return; | |
| } | |
| let body: AskBody; | |
| try { | |
| body = JSON.parse((await readBody(req)) || "{}") as AskBody; | |
| } catch { | |
| json(res, 400, { error: "Invalid JSON body" }); | |
| return; | |
| } | |
| const question = body.question?.trim(); | |
| if (!question) { | |
| json(res, 400, { error: 'Body must include { "question": "..." }' }); | |
| return; | |
| } | |
| const stream = url.searchParams.get("stream") === "1"; | |
| try { | |
| if (stream) { | |
| res.writeHead(200, { | |
| "content-type": "text/event-stream", | |
| "cache-control": "no-cache", | |
| connection: "keep-alive", | |
| "access-control-allow-origin": "*", | |
| }); | |
| const result = await ask(index, question, { | |
| history: body.history, | |
| rerank: body.rerank ?? true, | |
| onDelta: (t) => res.write(`event: delta\ndata: ${JSON.stringify({ text: t })}\n\n`), | |
| }); | |
| res.write(`event: result\ndata: ${JSON.stringify(result)}\n\n`); | |
| res.end(); | |
| } else { | |
| const result = await ask(index, question, { | |
| history: body.history, | |
| rerank: body.rerank ?? true, | |
| }); | |
| json(res, 200, result); | |
| } | |
| } catch (err) { | |
| const msg = err instanceof Error ? err.message : String(err); | |
| console.error(`[server] /ask failed: ${msg}`); | |
| if (stream) { | |
| res.write(`event: error\ndata: ${JSON.stringify({ error: msg })}\n\n`); | |
| res.end(); | |
| } else { | |
| json(res, 500, { error: msg }); | |
| } | |
| } | |
| return; | |
| } | |
| json(res, 404, { error: "Not found. Routes: GET /health, POST /ask[?stream=1]" }); | |
| }); | |
| await loadIndex(); | |
| // Bind to loopback only: the backend reaches this over 127.0.0.1 (same | |
| // container in production), and it has no auth of its own, so it must never | |
| // listen on a public interface. Override with RAG_HOST if a setup needs it. | |
| const HOST = process.env.RAG_HOST ?? "127.0.0.1"; | |
| server.listen(PORT, HOST, () => { | |
| console.log(`AskNeo RAG dev server on http://${HOST}:${PORT}`); | |
| console.log(` GET /health`); | |
| console.log(` POST /ask {"question": "..."}`); | |
| console.log(` POST /ask?stream=1 (SSE)`); | |
| }); | |