File size: 4,661 Bytes
c6dfde3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0abca2
 
 
 
 
 
c6dfde3
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
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)`);
});