@skyphusion/create-prism 0.1.0 → 0.175.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/index.js +4 -2
- package/package.json +1 -1
- package/template/CONTRIBUTING.md +6 -2
- package/template/README.md +45 -33
- package/template/docs/legal/README.md +1 -0
- package/template/migrations/0002_auth_public_mode.sql +32 -0
- package/template/package.json +6 -6
- package/template/public/app.js +44 -16
- package/template/public/index.html +47 -4
- package/template/src/auth-kdf.ts +7 -4
- package/template/src/auth.ts +11 -2
- package/template/src/control-plane.ts +254 -0
- package/template/src/env.ts +15 -0
- package/template/src/gateway-credentials.ts +23 -4
- package/template/src/health-schema.ts +4 -0
- package/template/src/index.ts +65 -3982
- package/template/src/longrun-params.ts +4 -2
- package/template/src/models.ts +65 -19
- package/template/src/output-extract.ts +58 -8
- package/template/src/parsers/openai-sse.ts +43 -14
- package/template/src/providers/anthropic.ts +105 -0
- package/template/src/providers/openai-image.ts +66 -0
- package/template/src/providers/openai.ts +79 -13
- package/template/src/providers/xai.ts +91 -0
- package/template/src/proxied-image-params.ts +29 -16
- package/template/src/routes/artifacts.ts +51 -0
- package/template/src/routes/chat.ts +1709 -0
- package/template/src/routes/conversations.ts +212 -0
- package/template/src/routes/documents.ts +262 -0
- package/template/src/routes/health.ts +105 -0
- package/template/src/routes/history.ts +92 -0
- package/template/src/routes/prefs.ts +95 -0
- package/template/src/routes/projects.ts +574 -0
- package/template/src/routes/rag.ts +657 -0
- package/template/src/routes/shared.ts +226 -0
- package/template/src/routes/workflow.ts +304 -0
- package/template/src/user-prefs.ts +10 -0
- package/template/src/zip.ts +7 -0
- package/template/tests/anthropic-binding.test.ts +181 -0
- package/template/tests/control-plane.test.ts +112 -0
- package/template/tests/gateway-credentials.test.ts +37 -0
- package/template/tests/longrun-params.test.ts +19 -0
- package/template/tests/openai-image.test.ts +47 -0
- package/template/tests/openai-responses.test.ts +78 -0
- package/template/tests/openai-sse.test.ts +28 -0
- package/template/tests/output-extract.test.ts +75 -1
- package/template/tests/proxied-image-params.test.ts +16 -7
- package/template/tests/sprint1-catalog.test.ts +27 -0
- package/template/tests/sprint2-catalog.test.ts +51 -0
- package/template/tests/sprint3-catalog.test.ts +29 -0
- package/template/tests/xai-binding.test.ts +127 -0
- package/template/tests-integration/worker.test.ts +9 -2
- package/template/wrangler.example.toml +19 -7
|
@@ -0,0 +1,657 @@
|
|
|
1
|
+
// RAG engine: document text extraction, embedding, ingestion, retrieval, and
|
|
2
|
+
// optional web search. This is a support library (no route handlers): the
|
|
3
|
+
// documents routes ingest through it, the chat routes retrieve through it, and
|
|
4
|
+
// the LongRunWorkflow re-ingests zip entries through it. Kept as one module
|
|
5
|
+
// because embedBatch and the embedding-model constants are shared by the
|
|
6
|
+
// ingestion and retrieval halves.
|
|
7
|
+
|
|
8
|
+
import { getDocumentProxy } from "unpdf";
|
|
9
|
+
import * as XLSX from "xlsx";
|
|
10
|
+
import type { Env } from "../env";
|
|
11
|
+
import { aiRun, type AiContext } from "../ai-binding";
|
|
12
|
+
import { loadGatewayCredentials, GATEWAY_NOT_CONFIGURED_MSG } from "../gateway-credentials";
|
|
13
|
+
import { chunkText } from "../chunking";
|
|
14
|
+
import { searchSearxngWeb } from "../searxng";
|
|
15
|
+
import { r2Put, r2DeleteSafe } from "./shared";
|
|
16
|
+
import type { RetrievedChunk, RetrievedWebResult } from "./shared";
|
|
17
|
+
|
|
18
|
+
// ---------- RAG: document ingestion (Pass 1) ----------
|
|
19
|
+
//
|
|
20
|
+
// Pass 1 supports text/markdown only. Uploaded files are stored in R2,
|
|
21
|
+
// chunked, embedded with @cf/baai/bge-base-en-v1.5 (768-dim), and the
|
|
22
|
+
// resulting vectors are upserted into the Vectorize index. Chunks remain
|
|
23
|
+
// in D1 keyed by their Vectorize vector_id so retrieval can look up the
|
|
24
|
+
// original text from a vector hit.
|
|
25
|
+
//
|
|
26
|
+
// Chunking is character-based with ~50 char overlap. We try to break on
|
|
27
|
+
// natural boundaries (paragraph breaks, then newlines, then sentences)
|
|
28
|
+
// before falling back to a hard cut. Target 500 chars per chunk - small
|
|
29
|
+
// enough that BGE-base does well, large enough that each chunk carries
|
|
30
|
+
// usable context.
|
|
31
|
+
//
|
|
32
|
+
// Pass 2 will add the retrieval injection path into /api/chat. Pass 1
|
|
33
|
+
// only builds the ingestion pipeline so we can validate Vectorize +
|
|
34
|
+
// chunking + embedding end-to-end before touching chat.
|
|
35
|
+
|
|
36
|
+
export const EMBED_MODEL = "@cf/baai/bge-base-en-v1.5";
|
|
37
|
+
export const EMBED_DIMENSIONS = 768;
|
|
38
|
+
export const EMBED_BATCH_SIZE = 16; // BGE accepts batches; 16 keeps requests small
|
|
39
|
+
export const DOC_MAX_BYTES = 10 * 1024 * 1024; // 10MB upload cap
|
|
40
|
+
|
|
41
|
+
// v0.25.0: ZIP import (RAG). A .zip upload is expanded and each inner file is
|
|
42
|
+
// ingested as its own document. The compressed archive still rides the 10MB
|
|
43
|
+
// DOC_MAX_BYTES cap above; these bound the decompressed expansion (zip-bomb
|
|
44
|
+
// guard) and the inner-file count.
|
|
45
|
+
export const ZIP_MAX_ENTRIES = 200;
|
|
46
|
+
export const ZIP_MAX_TOTAL_UNCOMPRESSED_BYTES = 50 * 1024 * 1024;
|
|
47
|
+
export const ZIP_MAX_FILE_BYTES = DOC_MAX_BYTES;
|
|
48
|
+
|
|
49
|
+
// Best-effort content type for a file pulled out of a zip (we only get a name,
|
|
50
|
+
// not a mime). extractChunks routes PDFs/spreadsheets by extension regardless,
|
|
51
|
+
// so this only affects the contentType stored on the R2 object.
|
|
52
|
+
export function mimeFromName(name: string): string {
|
|
53
|
+
const ext = (name.match(/\.([^.]+)$/)?.[1] ?? "").toLowerCase();
|
|
54
|
+
switch (ext) {
|
|
55
|
+
case "pdf": return "application/pdf";
|
|
56
|
+
case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
|
57
|
+
case "xls": return "application/vnd.ms-excel";
|
|
58
|
+
case "md": case "markdown": return "text/markdown";
|
|
59
|
+
case "csv": return "text/csv";
|
|
60
|
+
case "json": return "application/json";
|
|
61
|
+
case "html": case "htm": return "text/html";
|
|
62
|
+
case "xml": return "application/xml";
|
|
63
|
+
case "txt": case "log": case "yaml": case "yml": return "text/plain";
|
|
64
|
+
default: return "application/octet-stream";
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// v0.17.0: web-search retrieval limits and timeouts. Each upstream is
|
|
69
|
+
// time-bounded per source so a slow SearXNG doesn't block Wikipedia.
|
|
70
|
+
// Counts kept small to bound context-token spend when the toggle is on.
|
|
71
|
+
// v0.166.0: SearXNG replaced the retired Tavily + Brave SaaS sources.
|
|
72
|
+
export const SEARXNG_MAX_RESULTS = 5;
|
|
73
|
+
export const WIKIPEDIA_MAX_RESULTS = 3;
|
|
74
|
+
export const WEB_SEARCH_TIMEOUT_MS = 8000;
|
|
75
|
+
|
|
76
|
+
// v0.23.0: RAG document upload accepts any file type (no allowlist). PDF and
|
|
77
|
+
// XLSX/XLS get native per-page / per-sheet extraction; everything else is
|
|
78
|
+
// decoded as UTF-8 text (covers txt, md, csv, json, html, source code, logs,
|
|
79
|
+
// etc. regardless of extension or mime). extractChunks rejects only files
|
|
80
|
+
// whose bytes don't decode to usable text (binary formats like .docx/.png/.zip).
|
|
81
|
+
|
|
82
|
+
export interface DocumentRow {
|
|
83
|
+
id: number;
|
|
84
|
+
user_email: string;
|
|
85
|
+
created_at: string;
|
|
86
|
+
filename: string;
|
|
87
|
+
mime: string;
|
|
88
|
+
r2_key: string;
|
|
89
|
+
size_bytes: number;
|
|
90
|
+
total_chars: number;
|
|
91
|
+
chunk_count: number;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface ChunkRow {
|
|
95
|
+
id: number;
|
|
96
|
+
document_id: number;
|
|
97
|
+
user_email: string;
|
|
98
|
+
chunk_index: number;
|
|
99
|
+
text: string;
|
|
100
|
+
vector_id: string;
|
|
101
|
+
page: number | null;
|
|
102
|
+
sheet: string | null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Output of the per-format extractors. Each ExtractedChunk has text plus
|
|
106
|
+
// optional source-location metadata that gets persisted on the chunk row.
|
|
107
|
+
export interface ExtractedChunk {
|
|
108
|
+
text: string;
|
|
109
|
+
page?: number; // PDF: 1-indexed page number
|
|
110
|
+
sheet?: string; // XLSX/XLS: source sheet name
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ---------- RAG Phase 3A: per-format text extraction ----------
|
|
114
|
+
//
|
|
115
|
+
// For PDFs we extract per-page using unpdf (a serverless-friendly PDF.js
|
|
116
|
+
// wrapper) and tag each resulting chunk with its source page. Chunks never
|
|
117
|
+
// cross page boundaries so the source-page metadata stays meaningful.
|
|
118
|
+
//
|
|
119
|
+
// For XLSX/XLS we use SheetJS's CSV exporter per sheet and tag each chunk
|
|
120
|
+
// with its source sheet name. Same boundary rule: chunks never cross sheets.
|
|
121
|
+
//
|
|
122
|
+
// Scanned/image-only PDFs are not handled here; pdfjs extracts the empty
|
|
123
|
+
// text layer they have, which gives few or zero chunks. A future Phase 3B
|
|
124
|
+
// would render pages to PNG and run them through a vision model for OCR.
|
|
125
|
+
|
|
126
|
+
export async function extractPdfChunks(bytes: Uint8Array): Promise<ExtractedChunk[]> {
|
|
127
|
+
const pdf = await getDocumentProxy(bytes);
|
|
128
|
+
const out: ExtractedChunk[] = [];
|
|
129
|
+
for (let i = 1; i <= pdf.numPages; i++) {
|
|
130
|
+
const page = await pdf.getPage(i);
|
|
131
|
+
const content = await page.getTextContent();
|
|
132
|
+
// pdfjs's text items have a .str field; join with spaces and collapse
|
|
133
|
+
// runs of whitespace that come from rendering positioning.
|
|
134
|
+
const raw = (content.items as Array<{ str?: string }>)
|
|
135
|
+
.map((it) => (it.str ?? "").trim())
|
|
136
|
+
.filter(Boolean)
|
|
137
|
+
.join(" ")
|
|
138
|
+
.replace(/[ \t]+/g, " ")
|
|
139
|
+
.replace(/\s+\n/g, "\n")
|
|
140
|
+
.trim();
|
|
141
|
+
if (!raw) continue;
|
|
142
|
+
for (const piece of chunkText(raw)) {
|
|
143
|
+
out.push({ text: piece, page: i });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function extractXlsxChunks(bytes: Uint8Array): ExtractedChunk[] {
|
|
150
|
+
// SheetJS read accepts ArrayBuffer-ish inputs; dense=true uses a
|
|
151
|
+
// 2D-array internal layout which is faster on sparse sheets.
|
|
152
|
+
const wb = XLSX.read(bytes, { type: "array", dense: true });
|
|
153
|
+
const out: ExtractedChunk[] = [];
|
|
154
|
+
for (const sheetName of wb.SheetNames) {
|
|
155
|
+
const ws = wb.Sheets[sheetName];
|
|
156
|
+
if (!ws) continue;
|
|
157
|
+
const csv = XLSX.utils.sheet_to_csv(ws, { blankrows: false, strip: true });
|
|
158
|
+
const text = csv.trim();
|
|
159
|
+
if (!text) continue;
|
|
160
|
+
// For a small sheet, the whole CSV may be one chunk. For a large sheet,
|
|
161
|
+
// chunkText breaks on newlines (the row boundaries in CSV).
|
|
162
|
+
for (const piece of chunkText(text)) {
|
|
163
|
+
out.push({ text: piece, sheet: sheetName });
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// v0.23.0: heuristic: is a decoded string actually binary data we failed to
|
|
170
|
+
// read as text? A meaningful fraction of U+FFFD (UTF-8 replacement) or C0 control
|
|
171
|
+
// codes other than the usual whitespace (tab, LF, CR) means the source was
|
|
172
|
+
// binary (zipped office docs, images, archives). Text-based formats stay far
|
|
173
|
+
// below the threshold. Sample the head to keep this O(1)-ish on big files.
|
|
174
|
+
export function looksBinary(text: string): boolean {
|
|
175
|
+
if (!text) return true;
|
|
176
|
+
const sample = text.length > 4096 ? text.slice(0, 4096) : text;
|
|
177
|
+
let bad = 0;
|
|
178
|
+
for (let i = 0; i < sample.length; i++) {
|
|
179
|
+
const c = sample.charCodeAt(i);
|
|
180
|
+
if (c === 0xfffd) { bad++; continue; }
|
|
181
|
+
if (c < 0x20 && c !== 0x09 && c !== 0x0a && c !== 0x0d) bad++;
|
|
182
|
+
}
|
|
183
|
+
return bad / sample.length > 0.1;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Per-mime dispatcher. Returns ExtractedChunk[] regardless of input format.
|
|
187
|
+
// The caller is responsible for storing the raw bytes in R2 and persisting
|
|
188
|
+
// each chunk row with its page/sheet metadata.
|
|
189
|
+
export async function extractChunks(bytes: Uint8Array, mime: string, filename: string): Promise<ExtractedChunk[]> {
|
|
190
|
+
const ext = (filename.match(/\.([^.]+)$/)?.[1] ?? "").toLowerCase();
|
|
191
|
+
|
|
192
|
+
// PDF
|
|
193
|
+
if (mime === "application/pdf" || ext === "pdf") {
|
|
194
|
+
return await extractPdfChunks(bytes);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// XLSX or XLS
|
|
198
|
+
if (
|
|
199
|
+
mime === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
|
|
200
|
+
mime === "application/vnd.ms-excel" ||
|
|
201
|
+
ext === "xlsx" || ext === "xls"
|
|
202
|
+
) {
|
|
203
|
+
return extractXlsxChunks(bytes);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Everything else: treat as UTF-8 text. Covers txt/md plus any code, CSV,
|
|
207
|
+
// JSON, HTML, log, or other text-based format, whatever the extension.
|
|
208
|
+
// Decode with replacement on invalid bytes rather than throwing; if the
|
|
209
|
+
// result is mostly replacement/control bytes the file is binary in a format
|
|
210
|
+
// we can't extract, so reject it instead of embedding garbage.
|
|
211
|
+
const text = new TextDecoder("utf-8").decode(bytes);
|
|
212
|
+
if (looksBinary(text)) {
|
|
213
|
+
throw new Error(
|
|
214
|
+
`${filename} looks like binary data that can't be read as text. PDF and ` +
|
|
215
|
+
`XLSX/XLS are extracted natively; otherwise upload a text-based file ` +
|
|
216
|
+
`(txt, md, csv, json, html, source code, etc.).`
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
return chunkText(text).map((t) => ({ text: t }));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export async function embedBatch(env: Env, userEmail: string, texts: string[]): Promise<number[][]> {
|
|
223
|
+
if (texts.length === 0) return [];
|
|
224
|
+
const gateway = await loadGatewayCredentials(env, userEmail);
|
|
225
|
+
if (!gateway?.gatewayId) {
|
|
226
|
+
throw new Error(GATEWAY_NOT_CONFIGURED_MSG);
|
|
227
|
+
}
|
|
228
|
+
const aiCtx: AiContext = { env, gateway };
|
|
229
|
+
const result = await aiRun(aiCtx, EMBED_MODEL, { text: texts }) as {
|
|
230
|
+
shape?: [number, number];
|
|
231
|
+
data?: number[][];
|
|
232
|
+
};
|
|
233
|
+
if (!result.data || !Array.isArray(result.data)) {
|
|
234
|
+
throw new Error("Embedding model returned no data array");
|
|
235
|
+
}
|
|
236
|
+
return result.data;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// ---------- RAG: retrieval (Pass 2) ----------
|
|
240
|
+
//
|
|
241
|
+
// Embeds the user prompt, queries Vectorize for the top-K nearest chunks,
|
|
242
|
+
// then looks up source text in D1. We filter by user_email in the D1 JOIN
|
|
243
|
+
// (not in the Vectorize filter param) so this works without a metadata
|
|
244
|
+
// index on the Vectorize side - simpler for single-user deployments.
|
|
245
|
+
// Vectorize score ordering is preserved.
|
|
246
|
+
|
|
247
|
+
export const RETRIEVE_TOP_K = 5;
|
|
248
|
+
|
|
249
|
+
export async function retrieveContext(
|
|
250
|
+
env: Env,
|
|
251
|
+
userEmail: string,
|
|
252
|
+
queryText: string,
|
|
253
|
+
topK: number = RETRIEVE_TOP_K,
|
|
254
|
+
projectId?: number,
|
|
255
|
+
): Promise<{ chunks: RetrievedChunk[]; error: string | null }> {
|
|
256
|
+
if (!queryText || !queryText.trim()) {
|
|
257
|
+
return { chunks: [], error: "Empty query text" };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// 1) Embed the query. Log + surface errors instead of silently swallowing.
|
|
261
|
+
let queryVec: number[];
|
|
262
|
+
try {
|
|
263
|
+
const vectors = await embedBatch(env, userEmail, [queryText]);
|
|
264
|
+
if (vectors.length === 0) {
|
|
265
|
+
const msg = "Embed returned no vectors";
|
|
266
|
+
console.error("retrieveContext:", msg);
|
|
267
|
+
return { chunks: [], error: msg };
|
|
268
|
+
}
|
|
269
|
+
queryVec = vectors[0];
|
|
270
|
+
} catch (err) {
|
|
271
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
272
|
+
console.error("retrieveContext: embed failed:", m);
|
|
273
|
+
return { chunks: [], error: `embed failed: ${m}` };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// 2) Query Vectorize. No metadata filter - we scope by user in D1 below.
|
|
277
|
+
// When projectId is set, we overfetch (3x topK) at the Vectorize stage
|
|
278
|
+
// and filter by project membership in D1, since Vectorize doesn't know
|
|
279
|
+
// about project membership. Without overfetch, a small topK that all
|
|
280
|
+
// misses the project would return zero results even when the project
|
|
281
|
+
// has relevant chunks.
|
|
282
|
+
const vectorizeTopK = projectId !== undefined ? topK * 3 : topK;
|
|
283
|
+
let matches: { id: string; score: number }[];
|
|
284
|
+
try {
|
|
285
|
+
const q = await env.VEC.query(queryVec, { topK: vectorizeTopK });
|
|
286
|
+
matches = (q?.matches ?? []).map((m) => ({ id: m.id, score: m.score }));
|
|
287
|
+
} catch (err) {
|
|
288
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
289
|
+
console.error("retrieveContext: vectorize query failed:", m);
|
|
290
|
+
return { chunks: [], error: `vectorize query failed: ${m}` };
|
|
291
|
+
}
|
|
292
|
+
if (matches.length === 0) {
|
|
293
|
+
console.warn("retrieveContext: vectorize returned 0 matches for query");
|
|
294
|
+
return { chunks: [], error: "vectorize returned 0 matches" };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// 3) D1 lookup: join chunks to documents, scope by user_email so we
|
|
298
|
+
// never return another user's chunk even if their vector IDs would
|
|
299
|
+
// somehow collide. When projectId is set, additionally INNER JOIN
|
|
300
|
+
// project_documents so only chunks whose document is in that project's
|
|
301
|
+
// membership set come through.
|
|
302
|
+
const ids = matches.map((m) => m.id);
|
|
303
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
304
|
+
let rows;
|
|
305
|
+
try {
|
|
306
|
+
if (projectId !== undefined) {
|
|
307
|
+
rows = await env.DB.prepare(
|
|
308
|
+
`SELECT c.document_id, c.chunk_index, c.text, c.vector_id, c.page, c.sheet, d.filename
|
|
309
|
+
FROM chunks c
|
|
310
|
+
JOIN documents d ON c.document_id = d.id
|
|
311
|
+
JOIN project_documents pd ON pd.document_id = d.id
|
|
312
|
+
JOIN projects p ON p.id = pd.project_id
|
|
313
|
+
WHERE c.user_email = ?
|
|
314
|
+
AND p.user_email = ?
|
|
315
|
+
AND pd.project_id = ?
|
|
316
|
+
AND c.vector_id IN (${placeholders})`
|
|
317
|
+
)
|
|
318
|
+
.bind(userEmail, userEmail, projectId, ...ids)
|
|
319
|
+
.all<{ document_id: number; chunk_index: number; text: string; vector_id: string; filename: string; page: number | null; sheet: string | null }>();
|
|
320
|
+
} else {
|
|
321
|
+
rows = await env.DB.prepare(
|
|
322
|
+
`SELECT c.document_id, c.chunk_index, c.text, c.vector_id, c.page, c.sheet, d.filename
|
|
323
|
+
FROM chunks c
|
|
324
|
+
JOIN documents d ON c.document_id = d.id
|
|
325
|
+
WHERE c.user_email = ?
|
|
326
|
+
AND c.vector_id IN (${placeholders})`
|
|
327
|
+
)
|
|
328
|
+
.bind(userEmail, ...ids)
|
|
329
|
+
.all<{ document_id: number; chunk_index: number; text: string; vector_id: string; filename: string; page: number | null; sheet: string | null }>();
|
|
330
|
+
}
|
|
331
|
+
} catch (err) {
|
|
332
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
333
|
+
console.error("retrieveContext: D1 lookup failed:", m);
|
|
334
|
+
return { chunks: [], error: `D1 lookup failed: ${m}` };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const results = rows.results ?? [];
|
|
338
|
+
if (results.length === 0) {
|
|
339
|
+
// Vectorize had matches but D1 join returned nothing. Two causes:
|
|
340
|
+
// 1. user_email mismatch (vectors written under a different identity).
|
|
341
|
+
// 2. With projectId set: matches were real but none of the matched
|
|
342
|
+
// documents are members of the requested project.
|
|
343
|
+
const idSample = ids.slice(0, 3).join(", ");
|
|
344
|
+
const scope = projectId !== undefined ? ` project_id=${projectId},` : "";
|
|
345
|
+
const msg = `Vectorize returned ${matches.length} matches but D1 join returned 0. user_email='${userEmail}',${scope} sample vector_ids=[${idSample}]. Check whether vectors were upserted under a different user identity, or whether the project has any document members.`;
|
|
346
|
+
console.warn("retrieveContext:", msg);
|
|
347
|
+
return { chunks: [], error: msg };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// 4) Merge scores back in, preserve Vectorize ordering. When projectId
|
|
351
|
+
// is set we overfetched from Vectorize (3x topK), so cap output here to
|
|
352
|
+
// hold the chat prompt size to the caller's intended top-K.
|
|
353
|
+
const byId = new Map(results.map((r) => [r.vector_id, r]));
|
|
354
|
+
const scoreById = new Map(matches.map((m) => [m.id, m.score]));
|
|
355
|
+
const out: RetrievedChunk[] = [];
|
|
356
|
+
for (const id of ids) {
|
|
357
|
+
if (out.length >= topK) break;
|
|
358
|
+
const r = byId.get(id);
|
|
359
|
+
if (!r) continue;
|
|
360
|
+
out.push({
|
|
361
|
+
document_id: r.document_id,
|
|
362
|
+
filename: r.filename,
|
|
363
|
+
chunk_index: r.chunk_index,
|
|
364
|
+
text: r.text,
|
|
365
|
+
score: scoreById.get(id) ?? 0,
|
|
366
|
+
page: r.page,
|
|
367
|
+
sheet: r.sheet,
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
return { chunks: out, error: null };
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export function formatRetrievalForSystemPrompt(chunks: RetrievedChunk[]): string {
|
|
374
|
+
if (chunks.length === 0) return "";
|
|
375
|
+
const body = chunks
|
|
376
|
+
.map((c, i) => {
|
|
377
|
+
const loc =
|
|
378
|
+
c.page !== undefined && c.page !== null ? `, page ${c.page}` :
|
|
379
|
+
c.sheet ? `, sheet "${c.sheet}"` :
|
|
380
|
+
"";
|
|
381
|
+
return `[Excerpt ${i + 1}, from ${c.filename}${loc} (chunk ${c.chunk_index})]\n${c.text}`;
|
|
382
|
+
})
|
|
383
|
+
.join("\n\n---\n\n");
|
|
384
|
+
return [
|
|
385
|
+
"You have access to the following excerpts from the user's uploaded documents.",
|
|
386
|
+
"Use them when they are relevant to the user's query. If they don't answer the question,",
|
|
387
|
+
"say so plainly rather than guessing or hallucinating.",
|
|
388
|
+
"",
|
|
389
|
+
body,
|
|
390
|
+
].join("\n");
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// ---------- Web search (v0.17.0) ----------
|
|
394
|
+
//
|
|
395
|
+
// Optional retrieval source: SearXNG (self-hosted metasearch) for general web,
|
|
396
|
+
// Wikipedia for lore / reference. Both run in parallel; failure of one doesn't
|
|
397
|
+
// kill the other. Per-source timeouts (WEB_SEARCH_TIMEOUT_MS) prevent a slow
|
|
398
|
+
// upstream from blocking the whole turn.
|
|
399
|
+
//
|
|
400
|
+
// SearXNG requires SEARXNG_URL; when unset, that source is silently skipped.
|
|
401
|
+
// Wikipedia needs no config. (v0.166.0: SearXNG replaced the retired Tavily +
|
|
402
|
+
// Brave SaaS sources; see prism#93.)
|
|
403
|
+
//
|
|
404
|
+
// Results are persisted to the existing retrieved_context column alongside
|
|
405
|
+
// RAG chunks, with source_type discriminator. The frontend renders branches
|
|
406
|
+
// on source_type to show the source URL for web results.
|
|
407
|
+
|
|
408
|
+
export async function searchWeb(
|
|
409
|
+
env: Env,
|
|
410
|
+
query: string
|
|
411
|
+
): Promise<{ results: RetrievedWebResult[]; error: string | null }> {
|
|
412
|
+
const q = query.trim();
|
|
413
|
+
if (!q) return { results: [], error: null };
|
|
414
|
+
|
|
415
|
+
// Each upstream is wrapped in its own timeout + catch so a single failure
|
|
416
|
+
// doesn't abort the other. Partial results are better than nothing.
|
|
417
|
+
const searxngPromise: Promise<RetrievedWebResult[]> = env.SEARXNG_URL
|
|
418
|
+
? searchSearxng(env, q).catch(() => [])
|
|
419
|
+
: Promise.resolve([]);
|
|
420
|
+
const wikipediaPromise: Promise<RetrievedWebResult[]> = searchWikipedia(q).catch(() => []);
|
|
421
|
+
|
|
422
|
+
const [searxng, wikipedia] = await Promise.all([searxngPromise, wikipediaPromise]);
|
|
423
|
+
const results = [...searxng, ...wikipedia];
|
|
424
|
+
|
|
425
|
+
// Empty results is fine; it just means the query didn't match anything in
|
|
426
|
+
// any source. Real per-source failures are swallowed by the .catch above
|
|
427
|
+
// so the other source can still return its hits.
|
|
428
|
+
return { results, error: null };
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
export async function searchSearxng(env: Env, query: string): Promise<RetrievedWebResult[]> {
|
|
432
|
+
// Access service-token headers are sent only when both halves are set, so an
|
|
433
|
+
// un-gated self-hosted instance is reached with no headers.
|
|
434
|
+
const hits = await searchSearxngWeb(env.SEARXNG_URL!, query, {
|
|
435
|
+
maxResults: SEARXNG_MAX_RESULTS,
|
|
436
|
+
timeoutMs: WEB_SEARCH_TIMEOUT_MS,
|
|
437
|
+
accessClientId: env.SEARXNG_ACCESS_CLIENT_ID,
|
|
438
|
+
accessClientSecret: env.SEARXNG_ACCESS_CLIENT_SECRET,
|
|
439
|
+
});
|
|
440
|
+
return hits.map((r): RetrievedWebResult => ({
|
|
441
|
+
source_type: "web",
|
|
442
|
+
source: "searxng",
|
|
443
|
+
url: r.url,
|
|
444
|
+
title: r.title,
|
|
445
|
+
snippet: r.snippet,
|
|
446
|
+
}));
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
export async function searchWikipedia(query: string): Promise<RetrievedWebResult[]> {
|
|
450
|
+
// Wikipedia's search endpoint returns titles + HTML snippets in one call.
|
|
451
|
+
// origin=* is required for CORS, but harmless server-side too. We don't
|
|
452
|
+
// hit /page/summary per result (would be N+1 round-trips); the search
|
|
453
|
+
// snippet is enough for most creative-work queries.
|
|
454
|
+
const url = new URL("https://en.wikipedia.org/w/api.php");
|
|
455
|
+
url.searchParams.set("action", "query");
|
|
456
|
+
url.searchParams.set("list", "search");
|
|
457
|
+
url.searchParams.set("srsearch", query);
|
|
458
|
+
url.searchParams.set("srlimit", String(WIKIPEDIA_MAX_RESULTS));
|
|
459
|
+
url.searchParams.set("srprop", "snippet");
|
|
460
|
+
url.searchParams.set("format", "json");
|
|
461
|
+
url.searchParams.set("origin", "*");
|
|
462
|
+
|
|
463
|
+
const resp = await fetch(url.toString(), {
|
|
464
|
+
headers: {
|
|
465
|
+
// Wikimedia asks for a descriptive User-Agent identifying the tool.
|
|
466
|
+
// See https://meta.wikimedia.org/wiki/User-Agent_policy
|
|
467
|
+
"user-agent": "skyphusion-llm-public/0.17.0 (https://github.com/SkyPhusion/skyphusion-llm-public)",
|
|
468
|
+
},
|
|
469
|
+
signal: AbortSignal.timeout(WEB_SEARCH_TIMEOUT_MS),
|
|
470
|
+
});
|
|
471
|
+
if (!resp.ok) {
|
|
472
|
+
throw new Error(`Wikipedia ${resp.status}: ${(await resp.text()).slice(0, 200)}`);
|
|
473
|
+
}
|
|
474
|
+
const data = await resp.json() as {
|
|
475
|
+
query?: { search?: Array<{ title?: string; snippet?: string; pageid?: number }> };
|
|
476
|
+
};
|
|
477
|
+
const items = data.query?.search ?? [];
|
|
478
|
+
return items
|
|
479
|
+
.filter((r) => r.title && r.pageid !== undefined)
|
|
480
|
+
.map((r): RetrievedWebResult => ({
|
|
481
|
+
source_type: "web",
|
|
482
|
+
source: "wikipedia",
|
|
483
|
+
url: `https://en.wikipedia.org/?curid=${r.pageid}`,
|
|
484
|
+
title: r.title!,
|
|
485
|
+
// Snippet comes back as HTML with <span class="searchmatch">...</span>
|
|
486
|
+
// around matched terms. Strip tags and decode the few entities that
|
|
487
|
+
// Wikipedia commonly emits. Good enough for an LLM context block.
|
|
488
|
+
snippet: stripWikipediaSnippet(r.snippet ?? ""),
|
|
489
|
+
}));
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
export function stripWikipediaSnippet(html: string): string {
|
|
493
|
+
// Strip HTML tags to a fixpoint first, so a reassembled/nested tag (e.g.
|
|
494
|
+
// "<<script>script>") can't survive a single pass, THEN decode the handful of
|
|
495
|
+
// entities Wikipedia emits -- decoding & LAST so an encoded entity like
|
|
496
|
+
// "&lt;" stays literal text instead of being double-unescaped into "<".
|
|
497
|
+
// Output is plain text for an LLM context block (not an HTML/DOM sink).
|
|
498
|
+
let prev = "";
|
|
499
|
+
let s = html;
|
|
500
|
+
while (s !== prev) {
|
|
501
|
+
prev = s;
|
|
502
|
+
s = s.replace(/<[^>]+>/g, "");
|
|
503
|
+
}
|
|
504
|
+
return s
|
|
505
|
+
.replace(/"/g, '"')
|
|
506
|
+
.replace(/'/g, "'")
|
|
507
|
+
.replace(/</g, "<")
|
|
508
|
+
.replace(/>/g, ">")
|
|
509
|
+
.replace(/ /g, " ")
|
|
510
|
+
.replace(/&/g, "&")
|
|
511
|
+
.replace(/\s+/g, " ")
|
|
512
|
+
.trim();
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
export function webSourceSystemLabel(source: RetrievedWebResult["source"]): string {
|
|
516
|
+
switch (source) {
|
|
517
|
+
case "searxng": return "Web";
|
|
518
|
+
case "wikipedia": return "Wikipedia";
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
export function formatWebForSystemPrompt(results: RetrievedWebResult[]): string {
|
|
523
|
+
if (results.length === 0) return "";
|
|
524
|
+
const body = results
|
|
525
|
+
.map((r, i) => {
|
|
526
|
+
const sourceLabel = webSourceSystemLabel(r.source);
|
|
527
|
+
return `[${sourceLabel} ${i + 1}, "${r.title}" (${r.url})]\n${r.snippet}`;
|
|
528
|
+
})
|
|
529
|
+
.join("\n\n---\n\n");
|
|
530
|
+
return [
|
|
531
|
+
"You have access to the following snippets retrieved from web search.",
|
|
532
|
+
"Treat these as supplementary context, not authoritative fact. Quote URLs",
|
|
533
|
+
"verbatim if citing a source. If the snippets don't answer the question,",
|
|
534
|
+
"say so plainly rather than fabricating.",
|
|
535
|
+
"",
|
|
536
|
+
body,
|
|
537
|
+
].join("\n");
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// Result of ingesting a single file into the RAG store. Returned (not a
|
|
541
|
+
// Response) so both the single-file upload path and the per-entry zip-import
|
|
542
|
+
// path can compose it.
|
|
543
|
+
export type IngestResult =
|
|
544
|
+
| { ok: true; id: number; created_at: string; filename: string; mime: string; size_bytes: number; total_chars: number; chunk_count: number }
|
|
545
|
+
| { ok: false; status: number; error: string };
|
|
546
|
+
|
|
547
|
+
// Core RAG ingest for one file: extract -> store raw bytes in R2 -> insert the
|
|
548
|
+
// document row -> embed in batches and upsert vectors -> write chunk rows.
|
|
549
|
+
// Extracted from handleDocumentUpload (v0.25.0) so ZIP import can reuse it
|
|
550
|
+
// per inner file. Best-effort rollback on embedding failure.
|
|
551
|
+
export async function ingestDocument(env: Env, userEmail: string, filename: string, mime: string, bytes: Uint8Array): Promise<IngestResult> {
|
|
552
|
+
let extracted: ExtractedChunk[];
|
|
553
|
+
try {
|
|
554
|
+
extracted = await extractChunks(bytes, mime, filename);
|
|
555
|
+
} catch (err) {
|
|
556
|
+
return { ok: false, status: 400, error: `Extraction failed: ${err instanceof Error ? err.message : String(err)}` };
|
|
557
|
+
}
|
|
558
|
+
if (extracted.length === 0) {
|
|
559
|
+
return { ok: false, status: 400, error: "No chunks produced (empty, image-only/scanned PDF, or unreadable format)." };
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const totalChars = extracted.reduce((sum, c) => sum + c.text.length, 0);
|
|
563
|
+
|
|
564
|
+
// Store raw bytes in R2 for audit / future re-processing.
|
|
565
|
+
const r2Key = await r2Put(env, "in", mime, bytes, userEmail);
|
|
566
|
+
|
|
567
|
+
// Insert document row first so we have its ID for vector_id generation.
|
|
568
|
+
const docInsert = await env.DB.prepare(
|
|
569
|
+
`INSERT INTO documents
|
|
570
|
+
(user_email, filename, mime, r2_key, size_bytes, total_chars, chunk_count)
|
|
571
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
572
|
+
RETURNING id, created_at`
|
|
573
|
+
)
|
|
574
|
+
.bind(userEmail, filename, mime, r2Key, bytes.length, totalChars, extracted.length)
|
|
575
|
+
.first<{ id: number; created_at: string }>();
|
|
576
|
+
if (!docInsert) {
|
|
577
|
+
await r2DeleteSafe(env, r2Key);
|
|
578
|
+
return { ok: false, status: 500, error: "Failed to insert document row" };
|
|
579
|
+
}
|
|
580
|
+
const docId = docInsert.id;
|
|
581
|
+
|
|
582
|
+
// Embed in batches and upsert to Vectorize. We tag every vector with
|
|
583
|
+
// user_email + document_id so we can filter on retrieval and clean up on delete.
|
|
584
|
+
// Vector IDs are scoped: `${userEmail}:${docId}:${chunkIndex}`.
|
|
585
|
+
const vectorIdsWritten: string[] = [];
|
|
586
|
+
const chunkRowsToInsert: {
|
|
587
|
+
chunk_index: number;
|
|
588
|
+
text: string;
|
|
589
|
+
vector_id: string;
|
|
590
|
+
page: number | null;
|
|
591
|
+
sheet: string | null;
|
|
592
|
+
}[] = [];
|
|
593
|
+
|
|
594
|
+
try {
|
|
595
|
+
for (let b = 0; b < extracted.length; b += EMBED_BATCH_SIZE) {
|
|
596
|
+
const batch = extracted.slice(b, b + EMBED_BATCH_SIZE);
|
|
597
|
+
const vectors = await embedBatch(env, userEmail, batch.map((c) => c.text));
|
|
598
|
+
if (vectors.length !== batch.length) {
|
|
599
|
+
throw new Error(`Embedding batch returned ${vectors.length} vectors for ${batch.length} texts`);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const vectorizePayload = batch.map((c, i) => {
|
|
603
|
+
const idx = b + i;
|
|
604
|
+
const vid = `${userEmail}:${docId}:${idx}`;
|
|
605
|
+
chunkRowsToInsert.push({
|
|
606
|
+
chunk_index: idx,
|
|
607
|
+
text: c.text,
|
|
608
|
+
vector_id: vid,
|
|
609
|
+
page: c.page ?? null,
|
|
610
|
+
sheet: c.sheet ?? null,
|
|
611
|
+
});
|
|
612
|
+
vectorIdsWritten.push(vid);
|
|
613
|
+
const metadata: Record<string, string | number> = {
|
|
614
|
+
user_email: userEmail,
|
|
615
|
+
document_id: docId,
|
|
616
|
+
chunk_index: idx,
|
|
617
|
+
};
|
|
618
|
+
if (c.page !== undefined) metadata.page = c.page;
|
|
619
|
+
if (c.sheet !== undefined) metadata.sheet = c.sheet;
|
|
620
|
+
return { id: vid, values: vectors[i], metadata };
|
|
621
|
+
});
|
|
622
|
+
|
|
623
|
+
await env.VEC.upsert(vectorizePayload);
|
|
624
|
+
}
|
|
625
|
+
} catch (err) {
|
|
626
|
+
// Rollback: best-effort cleanup of partially-written state.
|
|
627
|
+
if (vectorIdsWritten.length) {
|
|
628
|
+
try { await env.VEC.deleteByIds(vectorIdsWritten); } catch { /* swallow */ }
|
|
629
|
+
}
|
|
630
|
+
await env.DB.prepare(`DELETE FROM documents WHERE id = ?`).bind(docId).run();
|
|
631
|
+
await r2DeleteSafe(env, r2Key);
|
|
632
|
+
return { ok: false, status: 502, error: `Embedding failed: ${err instanceof Error ? err.message : String(err)}` };
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
// Now write all chunk rows in a single batched D1 statement.
|
|
636
|
+
if (chunkRowsToInsert.length) {
|
|
637
|
+
const stmts = chunkRowsToInsert.map((c) =>
|
|
638
|
+
env.DB.prepare(
|
|
639
|
+
`INSERT INTO chunks (document_id, user_email, chunk_index, text, vector_id, page, sheet)
|
|
640
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
|
641
|
+
).bind(docId, userEmail, c.chunk_index, c.text, c.vector_id, c.page, c.sheet)
|
|
642
|
+
);
|
|
643
|
+
await env.DB.batch(stmts);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
return {
|
|
647
|
+
ok: true,
|
|
648
|
+
id: docId,
|
|
649
|
+
created_at: docInsert.created_at,
|
|
650
|
+
filename,
|
|
651
|
+
mime,
|
|
652
|
+
size_bytes: bytes.length,
|
|
653
|
+
total_chars: totalChars,
|
|
654
|
+
chunk_count: extracted.length,
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
|