@skyphusion/create-prism 1.2.0 → 1.3.1
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 +3 -4
- package/index.js +2 -2
- package/package.json +1 -1
- package/template/MIGRATIONS.md +30 -0
- package/template/README.md +29 -36
- package/template/docs/legal/INSTANCE-PRIVACY.md +11 -10
- package/template/public/app.js +2 -2
- package/template/public/url-safety.js +6 -6
- package/template/src/env.ts +27 -10
- package/template/src/routes/chat.ts +13 -6
- package/template/src/routes/projects.ts +5 -4
- package/template/src/routes/rag.ts +146 -65
- package/template/src/routes/shared.ts +5 -2
- package/template/src/skyphusion-search.ts +108 -0
- package/template/src/vector-id.ts +27 -0
- package/template/src/version.ts +1 -1
- package/template/tests/log-identity-guard.test.ts +88 -0
- package/template/tests/rag-retrieval-diagnostic.test.ts +89 -80
- package/template/tests/rag-vector-id.test.ts +154 -0
- package/template/tests/skyphusion-search.test.ts +144 -0
- package/template/tests/vectorize-rekey-vector-ids.test.ts +141 -0
- package/template/wrangler.example.toml +14 -9
- package/template/src/searxng.ts +0 -75
- package/template/tests/searxng.test.ts +0 -51
package/README.md
CHANGED
|
@@ -64,10 +64,9 @@ template `wrangler.example.toml`.
|
|
|
64
64
|
|
|
65
65
|
**Optional**
|
|
66
66
|
|
|
67
|
-
- `
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
runs.
|
|
67
|
+
- `SEARCH` service binding (`service = "skyphusion-search"`, `entrypoint = "SearchEntrypoint"`) enables the opt-in
|
|
68
|
+
web-search source. Delete the block if you have no such worker: the source then
|
|
69
|
+
reports `absent`, and keyless Wikipedia still runs.
|
|
71
70
|
|
|
72
71
|
## Auth: two modes, one identity seam (`AUTH_MODE`)
|
|
73
72
|
|
package/index.js
CHANGED
|
@@ -131,8 +131,8 @@ Next steps:
|
|
|
131
131
|
5. Set the worker secrets (access mode, the default):
|
|
132
132
|
npx wrangler secret put GATEWAY_ID (your AI Gateway slug)
|
|
133
133
|
npx wrangler secret put CF_AIG_TOKEN (AI Gateway Run token, for paid models)
|
|
134
|
-
Optional web search:
|
|
135
|
-
the
|
|
134
|
+
Optional web search: the SEARCH service binding to skyphusion-search
|
|
135
|
+
(entrypoint SearchEntrypoint; delete the block if you have no such worker). See the README.
|
|
136
136
|
6. Verify, then deploy:
|
|
137
137
|
npm run typecheck
|
|
138
138
|
npm test
|
package/package.json
CHANGED
package/template/MIGRATIONS.md
CHANGED
|
@@ -247,3 +247,33 @@ var.
|
|
|
247
247
|
bytes would share an index entry. The D1 join still scopes their results correctly, so the worst case
|
|
248
248
|
for those users is the old global behaviour, not a disclosure.
|
|
249
249
|
|
|
250
|
+
|
|
251
|
+
## Vector ids without identity (prism#232)
|
|
252
|
+
|
|
253
|
+
**Why.** Before prism#232, ingest minted each Vectorize vector id as `<identity>:<document id>:<chunk
|
|
254
|
+
index>`. In access mode the identity is the raw email address, so every id in the index carried it.
|
|
255
|
+
Vector ids are visible outside D1: in the index, in query results, and in any tool that lists or
|
|
256
|
+
exports ids. New ingests mint a random id (`c_` plus 32 hex digits, `src/vector-id.ts`). Ownership
|
|
257
|
+
stays in the vector's `user_email` metadata and the D1 `chunks` row.
|
|
258
|
+
|
|
259
|
+
**Nothing breaks if you do nothing.** Every reader (retrieval, document delete, account delete) looks
|
|
260
|
+
ids up through D1 `chunks.vector_id`, so old ids keep working next to new ones. Public-mode ids carry
|
|
261
|
+
the opaque `usr_` id, not an email, and are left alone.
|
|
262
|
+
|
|
263
|
+
**To remove the emails from existing ids** (access-mode deployments only), re-key them. The script
|
|
264
|
+
selects the D1 rows whose `vector_id` contains `@`, writes each vector under a new random id with the
|
|
265
|
+
same values and metadata (nothing is re-embedded), points the D1 row at the new id, then deletes the old
|
|
266
|
+
id. It prints counts only, never an id or a value, and is safe to re-run.
|
|
267
|
+
|
|
268
|
+
```bash
|
|
269
|
+
CLOUDFLARE_API_TOKEN=... CLOUDFLARE_ACCOUNT_ID=... \
|
|
270
|
+
node scripts/vectorize-rekey-vector-ids.mjs --index skyphusion-llm-vec --d1 <D1 database uuid> --dry-run
|
|
271
|
+
CLOUDFLARE_API_TOKEN=... CLOUDFLARE_ACCOUNT_ID=... \
|
|
272
|
+
node scripts/vectorize-rekey-vector-ids.mjs --index skyphusion-llm-vec --d1 <D1 database uuid>
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
The token needs Vectorize Edit and D1 Edit. `legacy` in the dry-run output is the number of
|
|
276
|
+
email-bearing ids. Exit 0 means every one was re-keyed. Exit 1 means some D1 ids had no vector (`gaps`)
|
|
277
|
+
or a row changed during the run (`conflicts`). Exit 2 means it refused or could not read. Vectorize
|
|
278
|
+
applies writes asynchronously, so retrieval for a re-keyed chunk can miss for a few seconds after its
|
|
279
|
+
batch; run it in a quiet window.
|
package/template/README.md
CHANGED
|
@@ -231,7 +231,7 @@ One Worker, no framework, no build step beyond TypeScript. The interesting parts
|
|
|
231
231
|
|
|
232
232
|
**Discord ingestion (v0.20.3+):** import a [DiscordChatExporter](https://github.com/Tyrrrz/DiscordChatExporter) JSON export into a project. The worker parses the export, groups messages into conversation-aware chunks (by author, time gap, and channel), and embeds them into the project's retrieval scope, so you can ask questions across an archived Discord channel's history. Import is a file picker in the project's "manage documents" modal.
|
|
233
233
|
|
|
234
|
-
**Web search (v0.17.0):** opt-in retrieval source that queries
|
|
234
|
+
**Web search (v0.17.0):** opt-in retrieval source that queries the `skyphusion-search` Worker (service binding `SEARCH`) and Wikipedia (reference and lore) in parallel. Snippets folded into the system prompt the same way RAG chunks are. Per-turn toggle. Without the `SEARCH` binding that source reports absent; Wikipedia needs no setup. See [Web search](#web-search) below.
|
|
235
235
|
|
|
236
236
|
**Streaming (v0.13.0+):** `POST /api/chat/stream` returns SSE for any chat model flagged `streaming: true` in the catalog. Token deltas surface as `{ type: "delta", text: "..." }` events, terminal completion as `{ type: "done", ... }` with token counts and conversation IDs. Client disconnect aborts the upstream model call immediately.
|
|
237
237
|
|
|
@@ -395,22 +395,18 @@ For an open, self-serve **public service**, do not use Cloudflare Access at all:
|
|
|
395
395
|
|
|
396
396
|
Do **not** use a **Bypass** policy on the main app URL. Bypass skips login, so the worker never receives a user email and everyone shares the `anonymous` bucket.
|
|
397
397
|
|
|
398
|
-
### 7. Optional: web search
|
|
398
|
+
### 7. Optional: web search
|
|
399
399
|
|
|
400
|
-
|
|
400
|
+
Web search calls the `skyphusion-search` Worker through a service binding. The committed template already declares it:
|
|
401
401
|
|
|
402
|
-
```
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
```
|
|
409
|
-
npx wrangler secret put SEARXNG_ACCESS_CLIENT_ID
|
|
410
|
-
npx wrangler secret put SEARXNG_ACCESS_CLIENT_SECRET
|
|
402
|
+
```toml
|
|
403
|
+
[[services]]
|
|
404
|
+
binding = "SEARCH"
|
|
405
|
+
service = "skyphusion-search"
|
|
406
|
+
entrypoint = "SearchEntrypoint"
|
|
411
407
|
```
|
|
412
408
|
|
|
413
|
-
|
|
409
|
+
Copy that block into your `wrangler.toml`. If you do not run a worker with that script name, delete the block instead: `wrangler deploy` fails when the service does not exist. With the binding absent, the response says that source is `absent` and Wikipedia still runs. Wikipedia needs no config. See [Web search](#web-search) below.
|
|
414
410
|
|
|
415
411
|
### 8. Local development
|
|
416
412
|
|
|
@@ -464,7 +460,7 @@ npx wrangler secret put GATEWAY_ID
|
|
|
464
460
|
npx wrangler secret put CF_AIG_TOKEN
|
|
465
461
|
```
|
|
466
462
|
|
|
467
|
-
For local dev, leave those keys out of `.dev.vars` as well.
|
|
463
|
+
For local dev, leave those keys out of `.dev.vars` as well. Web search is the `SEARCH` service binding, not a secret. Omit that block when you have no `skyphusion-search` worker; Wikipedia still runs. Most public demos omit gateway secrets so visitors rely on their own gateway for paid models.
|
|
468
464
|
|
|
469
465
|
Do **not** create a Cloudflare Access application for a public-mode worker: the app has its own signup, and an Access gate in front would add a second login before it.
|
|
470
466
|
|
|
@@ -542,7 +538,7 @@ For D1 **schema** changes, see [Migrating an existing deployment](#migrating-an-
|
|
|
542
538
|
|
|
|
543
539
|
+---+---+
|
|
544
540
|
| |
|
|
545
|
-
|
|
541
|
+
SEARCH Wikipedia (web search)
|
|
546
542
|
```
|
|
547
543
|
|
|
548
544
|
The worker is the only public surface. R2 is private; the worker streams objects through `GET /api/artifact/*` after verifying ownership via `customMetadata.user_email` on the R2 object.
|
|
@@ -624,7 +620,7 @@ Workers AI billing is per-token / per-image / per-minute depending on model. Fre
|
|
|
624
620
|
|
|
625
621
|
D1 is roughly $0.75/GB-month for storage. R2 is roughly $0.015/GB-month with no egress fees inside Cloudflare. Free tiers on D1 and R2 cover small personal use indefinitely.
|
|
626
622
|
|
|
627
|
-
Anthropic (Claude), xAI (Grok), OpenAI chat, Google Gemini, and proxied image / video / music models bill against your Cloudflare account via Unified Billing.
|
|
623
|
+
Anthropic (Claude), xAI (Grok), OpenAI chat, Google Gemini, and proxied image / video / music models bill against your Cloudflare account via Unified Billing. Web search through the `SEARCH` service binding stays on your Cloudflare account (no third-party search API). Wikipedia is free. See per-provider sections below.
|
|
628
624
|
|
|
629
625
|
## Anthropic models (Unified Billing)
|
|
630
626
|
|
|
@@ -941,48 +937,45 @@ DiscordChatExporter.Cli export -t <TOKEN> -c <CHANNEL_ID> -f Json \
|
|
|
941
937
|
|
|
942
938
|
## Web search
|
|
943
939
|
|
|
944
|
-
An opt-in retrieval source (v0.17.0) that
|
|
940
|
+
An opt-in retrieval source (v0.17.0) that retrieves at request time and folds the snippets into the system prompt. Runs in parallel with RAG, so a single turn can pull from your uploaded docs, the skyphusion-search corpus, and Wikipedia. The corpus half is Skyphusion public repos, not the open web. Wikipedia is the reference half.
|
|
945
941
|
|
|
946
942
|
### How it works
|
|
947
943
|
|
|
948
944
|
When you check the "search the web" toggle next to the run button (chat models only), the worker fires two parallel queries on each turn:
|
|
949
945
|
|
|
950
|
-
1. **
|
|
951
|
-
2. **Wikipedia** for reference and lore. No API key needed. Returns titles + HTML-stripped snippets via the public MediaWiki search endpoint.
|
|
946
|
+
1. **skyphusion-search** for corpus hits. A service binding (`SEARCH`, entrypoint `SearchEntrypoint`) calls `search(question)` on the `skyphusion-search` Worker and reads `{ chunks }`. With the binding absent, the chat response reports `sources.web.status` `absent`. A thrown call reports `failed`. When the RPC throws `empty_question`, `question_too_long`, `rate_limited`, or `search_unavailable`, the error string is that code. An empty `chunks` array reports `ok` and count 0. Those three are different.
|
|
947
|
+
2. **Wikipedia** for reference and lore. No API key needed. Returns titles + HTML-stripped snippets via the public MediaWiki search endpoint. Unchanged: it still answers when the web source fails or is absent.
|
|
952
948
|
|
|
953
|
-
Both have an 8-second per-source timeout. If one fails or times out, the other still returns its hits. Results are persisted in the same `retrieved_context` column alongside any RAG chunks from the same turn, with a `source_type` discriminator so the UI can render web results (title + clickable URL + snippet) distinctly from doc chunks.
|
|
949
|
+
Both have an 8-second per-source timeout. If one fails or times out, the other still returns its hits. The chat JSON (and the stream `done` event) includes `sources.web` and `sources.wikipedia`, each `{ status, count, error? }`. `web_search_error` is set only when the web source failed. Results are persisted in the same `retrieved_context` column alongside any RAG chunks from the same turn, with a `source_type` discriminator so the UI can render web results (title + clickable URL + snippet) distinctly from doc chunks.
|
|
954
950
|
|
|
955
951
|
Per-turn opt-in: the toggle is not sticky across turns. Each turn decides independently whether to search. Web search and RAG can be on simultaneously; the model sees both in the system prompt.
|
|
956
952
|
|
|
957
953
|
### Setup
|
|
958
954
|
|
|
959
|
-
|
|
955
|
+
Add the service binding to your `wrangler.toml` (already in `wrangler.example.toml`) and redeploy. Wikipedia needs no config.
|
|
960
956
|
|
|
961
|
-
```
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
```
|
|
968
|
-
npx wrangler secret put SEARXNG_ACCESS_CLIENT_ID
|
|
969
|
-
npx wrangler secret put SEARXNG_ACCESS_CLIENT_SECRET
|
|
957
|
+
```toml
|
|
958
|
+
[[services]]
|
|
959
|
+
binding = "SEARCH"
|
|
960
|
+
service = "skyphusion-search"
|
|
961
|
+
entrypoint = "SearchEntrypoint"
|
|
970
962
|
```
|
|
971
963
|
|
|
972
|
-
The
|
|
964
|
+
The binding calls the named entrypoint, not `POST /ask`. There is no Origin header and no Turnstile token. The search worker's script must export `SearchEntrypoint` (search-mcp). Delete the `[[services]]` block if that worker is not on your account.
|
|
973
965
|
|
|
974
966
|
### Caveats worth knowing
|
|
975
967
|
|
|
976
|
-
- **Token budget.** Each turn with web search on adds roughly 2000-4000 tokens to the system prompt (up to 5
|
|
977
|
-
- **
|
|
968
|
+
- **Token budget.** Each turn with web search on adds roughly 2000-4000 tokens to the system prompt (up to 5 corpus snippets and 3 Wikipedia snippets). Long campaigns or document-heavy RAG turns may push against your model's context window.
|
|
969
|
+
- **Same-account call.** The binding does not leave your Cloudflare account and does not use a third-party search API. Search-every-turn would still burn context tokens, so the per-turn toggle is intentional.
|
|
970
|
+
- **The search worker can still refuse the call.** `search` throws `empty_question`, `question_too_long`, `rate_limited`, or `search_unavailable`. A refusal comes back as `sources.web.status` `failed` with that error code, and Wikipedia hits stay. An empty `chunks` array is `ok` with count 0.
|
|
978
971
|
- **No fact-checking.** Web snippets are supplementary context, not authoritative. The system prompt tells the model so. Verify anything that matters before quoting it.
|
|
979
972
|
- **Wikipedia User-Agent.** The worker identifies itself per Wikimedia's policy. If you fork to a different repo name, update the UA string in `searchWikipedia` so you're not lumped in with anonymous scrapers.
|
|
980
973
|
|
|
981
974
|
### When it shines
|
|
982
975
|
|
|
983
976
|
- **Worldbuilding lore**: "Norse trickster mythology," "Edo period yokai," "Welsh place name etymology." Wikipedia alone covers most of this.
|
|
984
|
-
- **
|
|
985
|
-
- **Mixed RAG + web**: your campaign uses a setting bible (uploaded as a doc) plus
|
|
977
|
+
- **This org's own docs**: how a Skyphusion repo is put together. That is what the corpus index holds. It is not a news search.
|
|
978
|
+
- **Mixed RAG + web**: your campaign uses a setting bible (uploaded as a doc) plus Wikipedia. Toggle both; the model sees both context blocks.
|
|
986
979
|
- **Niche reference**: "17th-century apothecary daily routine," "Victorian funeral customs," anything where you want flavor without writing it yourself.
|
|
987
980
|
|
|
988
981
|
### When to leave it off
|
|
@@ -1077,7 +1070,7 @@ See [SECURITY.md](SECURITY.md) for vulnerability reporting.
|
|
|
1077
1070
|
|
|
1078
1071
|
Built and maintained by [SkyPhusion](https://x.com/rockrockenhaus).
|
|
1079
1072
|
|
|
1080
|
-
Built on Cloudflare Workers, Workers AI, AI Gateway, D1, R2, Vectorize, Workflows, and Cloudflare Access. Image generation models courtesy of Black Forest Labs and Leonardo.Ai. Text-to-speech via Deepgram. Speech-to-text via OpenAI Whisper. Web search via
|
|
1073
|
+
Built on Cloudflare Workers, Workers AI, AI Gateway, D1, R2, Vectorize, Workflows, and Cloudflare Access. Image generation models courtesy of Black Forest Labs and Leonardo.Ai. Text-to-speech via Deepgram. Speech-to-text via OpenAI Whisper. Web search via the skyphusion-search Worker and Wikipedia.
|
|
1081
1074
|
|
|
1082
1075
|
## Hosted instance policies (play.skyphusion.org)
|
|
1083
1076
|
|
|
@@ -172,20 +172,21 @@ if you have entered a control-plane client key, chat through play-proxy as descr
|
|
|
172
172
|
through play-proxy" above.
|
|
173
173
|
|
|
174
174
|
**Web search is opt-in and does not use any third-party search API.** Prism has a per-turn web search
|
|
175
|
-
toggle. When you switch it on for a turn, the text of that one query is sent to
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
175
|
+
toggle. When you switch it on for a turn, the text of that one query is sent to two places, and nowhere
|
|
176
|
+
else. One is Wikipedia (the public MediaWiki search endpoint), which needs no key. The other is the
|
|
177
|
+
`skyphusion-search` Worker, a Skyphusion Labs Worker on the same Cloudflare account, reached by a
|
|
178
|
+
service binding named `SEARCH` (not over the public internet, and not with an API key). That Worker
|
|
179
|
+
searches Skyphusion's public corpus. If the binding is not configured, that half does not run and the
|
|
180
|
+
response says so (`sources.web.status` is `absent`). If the call fails, the response says `failed`
|
|
181
|
+
rather than pretending the corpus had nothing. Wikipedia still answers in both cases. The snippets
|
|
181
182
|
that come back are stored with the turn as retrieved context, the same way your RAG chunks are. Your
|
|
182
183
|
chat history, your uploaded documents, and your generated media are never sent out for search. Leave
|
|
183
184
|
the toggle off and no query leaves the instance.
|
|
184
185
|
|
|
185
|
-
**Correction (2026-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
186
|
+
**Correction (2026-11-12).** Earlier versions of this notice said the query also went to a self-hosted
|
|
187
|
+
search service at search.skyphusion.org, and then that the hosted instance had no such service. That
|
|
188
|
+
host is gone. This version sends the query to the `skyphusion-search` Worker as described above. The
|
|
189
|
+
hosted worker has no search secret to remove.
|
|
189
190
|
|
|
190
191
|
## Deleting your data
|
|
191
192
|
|
package/template/public/app.js
CHANGED
|
@@ -880,7 +880,7 @@ function renderRetrievedChunksHTML(chunks) {
|
|
|
880
880
|
if (c.source_type === "web") {
|
|
881
881
|
const score = (typeof c.score === "number") ? ` \u00b7 score ${c.score.toFixed(3)}` : "";
|
|
882
882
|
const sourceLabel =
|
|
883
|
-
c.source === "searxng" ? "web" :
|
|
883
|
+
c.source === "searxng" || c.source === "skyphusion-search" ? "web" :
|
|
884
884
|
c.source === "wikipedia" ? "wikipedia" : "web";
|
|
885
885
|
return `
|
|
886
886
|
<details class="retrieved-chunk retrieved-web">
|
|
@@ -1438,7 +1438,7 @@ async function run() {
|
|
|
1438
1438
|
if (m.type === "chat" && useDocsCheckbox.checked && state.documentCount > 0) {
|
|
1439
1439
|
requestBody.use_docs = true;
|
|
1440
1440
|
}
|
|
1441
|
-
// v0.17.0: web search. Chat models only;
|
|
1441
|
+
// v0.17.0: web search. Chat models only; skyphusion-search + Wikipedia when toggled.
|
|
1442
1442
|
if (m.type === "chat" && useWebSearchCheckbox.checked) {
|
|
1443
1443
|
requestBody.use_web_search = true;
|
|
1444
1444
|
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// URL safety for values this app did not construct.
|
|
2
2
|
//
|
|
3
|
-
// Web-search
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
3
|
+
// Web-search rows reach the transcript carrying a `url` field that is
|
|
4
|
+
// persisted in retrieved_context and replayed on every later render.
|
|
5
|
+
// Current rows use a URL this worker built (src/skyphusion-search.ts).
|
|
6
|
+
// Older rows carry a URL from an upstream engine that the worker stored
|
|
7
|
+
// after a truthiness check only. Either way the href is replayed from D1,
|
|
8
|
+
// so the string is not trusted at render time.
|
|
9
9
|
//
|
|
10
10
|
// WHY ESCAPING IS THE WRONG TOOL HERE. escapeHtml() replaces & < > " ' and is
|
|
11
11
|
// exactly right for stopping attribute injection. It does nothing whatever to
|
package/template/src/env.ts
CHANGED
|
@@ -12,6 +12,26 @@
|
|
|
12
12
|
// secret runtime paths surface meaningful errors instead of TypeScript
|
|
13
13
|
// telling deployers they need fields they may legitimately not have set.
|
|
14
14
|
|
|
15
|
+
// Subset of search-mcp AiSearchChunk that SearchEntrypoint.search returns.
|
|
16
|
+
// Extra fields on the wire are ignored. The mapper lives in
|
|
17
|
+
// src/skyphusion-search.ts.
|
|
18
|
+
export interface SearchChunk {
|
|
19
|
+
score?: number;
|
|
20
|
+
text?: string;
|
|
21
|
+
item?: {
|
|
22
|
+
key?: string;
|
|
23
|
+
metadata?: { repo?: string; path?: string };
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Named RPC entrypoint on the skyphusion-search Worker. The binding
|
|
28
|
+
// field in wrangler is `entrypoint = "SearchEntrypoint"`. The method
|
|
29
|
+
// is search(question), not POST /ask.
|
|
30
|
+
// https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/#named-entrypoints
|
|
31
|
+
export interface SearchEntrypoint extends Rpc.WorkerEntrypointBranded {
|
|
32
|
+
search(question: string): Promise<{ chunks: SearchChunk[] }>;
|
|
33
|
+
}
|
|
34
|
+
|
|
15
35
|
export interface Env {
|
|
16
36
|
AI: Ai;
|
|
17
37
|
DB: D1Database;
|
|
@@ -68,14 +88,11 @@ export interface Env {
|
|
|
68
88
|
// stay on Unified Billing and render opaque. No other provider reads a
|
|
69
89
|
// deployer key.
|
|
70
90
|
OPENAI_API_KEY?: string;
|
|
71
|
-
//
|
|
72
|
-
//
|
|
73
|
-
//
|
|
74
|
-
//
|
|
75
|
-
|
|
76
|
-
//
|
|
77
|
-
|
|
78
|
-
// both are set; a self-hoster running an un-gated instance leaves them unset.
|
|
79
|
-
SEARXNG_ACCESS_CLIENT_ID?: string;
|
|
80
|
-
SEARXNG_ACCESS_CLIENT_SECRET?: string;
|
|
91
|
+
// Service binding to the skyphusion-search Worker, named entrypoint
|
|
92
|
+
// SearchEntrypoint. Optional: when the binding is absent, web search
|
|
93
|
+
// reports that source as "absent" and Wikipedia still runs. Declared
|
|
94
|
+
// in wrangler.example.toml as [[services]] binding = "SEARCH",
|
|
95
|
+
// service = "skyphusion-search", entrypoint = "SearchEntrypoint".
|
|
96
|
+
// search(question) returns { chunks }. This is not POST /ask.
|
|
97
|
+
SEARCH?: Service<SearchEntrypoint>;
|
|
81
98
|
}
|
|
@@ -43,9 +43,11 @@ import {
|
|
|
43
43
|
retrieveContext,
|
|
44
44
|
RETRIEVE_TOP_K,
|
|
45
45
|
searchWeb,
|
|
46
|
+
noWebSearch,
|
|
46
47
|
formatRetrievalForSystemPrompt,
|
|
47
48
|
formatWebForSystemPrompt,
|
|
48
49
|
looksBinary,
|
|
50
|
+
type WebSearchOutcome,
|
|
49
51
|
} from "./rag";
|
|
50
52
|
import { resolveProjectForChat } from "./projects";
|
|
51
53
|
import type { LongRunParams } from "./workflow";
|
|
@@ -237,10 +239,10 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
|
|
|
237
239
|
// v0.17.0: web search runs in parallel with RAG retrieval and the
|
|
238
240
|
// attachment walk. Per-source timeouts + catches inside searchWeb bound
|
|
239
241
|
// the worst-case latency to WEB_SEARCH_TIMEOUT_MS.
|
|
240
|
-
const webSearchPromise: Promise<
|
|
242
|
+
const webSearchPromise: Promise<WebSearchOutcome> =
|
|
241
243
|
body.use_web_search
|
|
242
244
|
? searchWeb(env, body.user_input)
|
|
243
|
-
: Promise.resolve(
|
|
245
|
+
: Promise.resolve(noWebSearch());
|
|
244
246
|
|
|
245
247
|
// Walk inputs: write images / video frames to R2, transcribe audio via
|
|
246
248
|
// Whisper. Build three parallel structures used after the loop:
|
|
@@ -360,7 +362,7 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
|
|
|
360
362
|
const { chunks: retrievedChunks, error: retrievalError } = await retrievePromise;
|
|
361
363
|
|
|
362
364
|
// v0.17.0: web-search retrieval, same parallelism pattern as RAG.
|
|
363
|
-
const { results: webResults, error: webSearchError } = await webSearchPromise;
|
|
365
|
+
const { results: webResults, error: webSearchError, sources: webSources } = await webSearchPromise;
|
|
364
366
|
const allRetrieved: RetrievedItem[] = [...retrievedChunks, ...webResults];
|
|
365
367
|
|
|
366
368
|
// Build the effective system prompt: user-supplied prompt, optional compact
|
|
@@ -522,6 +524,9 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
|
|
|
522
524
|
effective_system_prompt: (body.use_docs || body.use_web_search) ? effectiveSystemPrompt : undefined,
|
|
523
525
|
retrieval_error: body.use_docs ? retrievalError : undefined,
|
|
524
526
|
web_search_error: body.use_web_search ? webSearchError : undefined,
|
|
527
|
+
// Per-source status. "ok" with count 0 is zero hits. "failed" is a
|
|
528
|
+
// broken web source. "absent" means the SEARCH binding is not configured.
|
|
529
|
+
sources: body.use_web_search ? webSources : undefined,
|
|
525
530
|
});
|
|
526
531
|
}
|
|
527
532
|
|
|
@@ -1274,10 +1279,10 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
|
|
|
1274
1279
|
: Promise.resolve({ chunks: [], error: null });
|
|
1275
1280
|
|
|
1276
1281
|
// v0.17.0: web search runs in parallel with RAG retrieval, same as runChat.
|
|
1277
|
-
const webSearchPromise: Promise<
|
|
1282
|
+
const webSearchPromise: Promise<WebSearchOutcome> =
|
|
1278
1283
|
body.use_web_search
|
|
1279
1284
|
? searchWeb(env, body.user_input)
|
|
1280
|
-
: Promise.resolve(
|
|
1285
|
+
: Promise.resolve(noWebSearch());
|
|
1281
1286
|
|
|
1282
1287
|
// Attachment walk. Reach completion before any bytes flow back; streaming
|
|
1283
1288
|
// helps with time-to-last-token, not time-to-first-token on multimodal turns.
|
|
@@ -1374,7 +1379,7 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
|
|
|
1374
1379
|
}
|
|
1375
1380
|
|
|
1376
1381
|
const { chunks: retrievedChunks } = await retrievePromise;
|
|
1377
|
-
const { results: webResults } = await webSearchPromise;
|
|
1382
|
+
const { results: webResults, error: webSearchError, sources: webSources } = await webSearchPromise;
|
|
1378
1383
|
const allRetrieved: RetrievedItem[] = [...retrievedChunks, ...webResults];
|
|
1379
1384
|
|
|
1380
1385
|
const userSystemPrompt = body.system_prompt?.trim() ?? "";
|
|
@@ -1497,6 +1502,8 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
|
|
|
1497
1502
|
tokens_out: usageOut,
|
|
1498
1503
|
conversation_id: conversationId,
|
|
1499
1504
|
turn_index: turnIndex,
|
|
1505
|
+
web_search_error: body.use_web_search ? webSearchError : undefined,
|
|
1506
|
+
sources: body.use_web_search ? webSources : undefined,
|
|
1500
1507
|
});
|
|
1501
1508
|
} catch (err) {
|
|
1502
1509
|
// Self-triggered AbortError (we aborted because client disconnected)
|
|
@@ -8,6 +8,7 @@ import { parseDiscordExport, chunkDiscordMessages } from "../discord";
|
|
|
8
8
|
import { json, getUserEmail, r2Put, r2DeleteSafe } from "./shared";
|
|
9
9
|
import type { ChatRequest } from "./shared";
|
|
10
10
|
import { embedBatch, DOC_MAX_BYTES, EMBED_BATCH_SIZE } from "./rag";
|
|
11
|
+
import { mintVectorId } from "../vector-id";
|
|
11
12
|
|
|
12
13
|
// v0.20.0: project + project_documents join. A project groups documents
|
|
13
14
|
// (and in v0.20.1, conversations) under a shared system_prompt and
|
|
@@ -121,7 +122,7 @@ export async function resolveProjectForChat(
|
|
|
121
122
|
.first<ProjectRow>();
|
|
122
123
|
if (!project) {
|
|
123
124
|
console.warn(
|
|
124
|
-
`Chat referenced unknown project_id=${body.project_id} for
|
|
125
|
+
`Chat referenced unknown project_id=${body.project_id} (not found for this caller); ` +
|
|
125
126
|
`falling back to no-project semantics (no system prompt fallback, no retrieval scoping).`
|
|
126
127
|
);
|
|
127
128
|
} else {
|
|
@@ -483,8 +484,8 @@ export async function handleDiscordImport(request: Request, env: Env, projectId:
|
|
|
483
484
|
await env.DB.batch(stmts);
|
|
484
485
|
}
|
|
485
486
|
|
|
486
|
-
// Embed chunks and upsert to Vectorize.
|
|
487
|
-
//
|
|
487
|
+
// Embed chunks and upsert to Vectorize. Vector ids are random and carry no
|
|
488
|
+
// identity, the same as documents (src/vector-id.ts, prism#232).
|
|
488
489
|
const vectorIdsWritten: string[] = [];
|
|
489
490
|
const chunkRowsToInsert: {
|
|
490
491
|
chunk_index: number;
|
|
@@ -505,7 +506,7 @@ export async function handleDiscordImport(request: Request, env: Env, projectId:
|
|
|
505
506
|
}
|
|
506
507
|
const payload = batch.map((c, i) => {
|
|
507
508
|
const idx = b + i;
|
|
508
|
-
const vid =
|
|
509
|
+
const vid = mintVectorId();
|
|
509
510
|
chunkRowsToInsert.push({
|
|
510
511
|
chunk_index: idx,
|
|
511
512
|
text: c.text,
|