@neon/skills 2.3.0 → 3.0.0

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.
@@ -1,6 +1,6 @@
1
1
  # Hybrid Search
2
2
 
3
- Use hybrid search when either semantic similarity or exact vocabulary can identify a relevant document. Lakebase Search does not provide a built-in hybrid function: run vector and BM25 retrieval separately, then combine their results with a fusion strategy suited to the workload.
3
+ Use hybrid search when either semantic similarity or exact vocabulary can identify a relevant document. Run vector and full-text search separately, then combine their results with fusion or reranking.
4
4
 
5
5
  Lakebase Search requires Postgres 16 or later. Hybrid search uses both extensions:
6
6
 
@@ -28,13 +28,140 @@ The 1024-dimensional column is an example. Set it to the output dimension of you
28
28
 
29
29
  Create and validate each retriever independently before combining them. Follow [Vector search](vector-search.md) and [Full-text search](full-text-search.md) for their indexes, query operators, and tuning.
30
30
 
31
- Reciprocal Rank Fusion (RRF) is the approach in the Lakebase Search get-started guide and a useful default because it combines ranks instead of incomparable raw distances and scores. It is not the only option: weighted rank fusion, normalized score fusion, or a reranker may fit applications with different relevance signals.
31
+ Choose how to order the combined results:
32
+
33
+ - **Jev reranking:** retrieve vector and full-text search candidates, deduplicate by document ID, score each candidate with Jev, and take the final top results.
34
+ - **Reciprocal Rank Fusion (RRF):** fuse the retrievers' ranks instead of their incomparable vector distances and BM25 scores, with no additional model call.
35
+
36
+ Jev can score the deduplicated candidate pool directly. RRF is optional when you want to prioritize or trim a larger pool before reranking, or provide a model-free fallback. Measure relevance and added latency on your corpus to choose a path.
37
+
38
+ ## Rerank with Jev
39
+
40
+ Retrieve up to 40 candidates per retriever and deduplicate with `UNION`. Bind the query embedding as `$1` and the original query text as `$2`:
41
+
42
+ ```sql
43
+ WITH vector_candidates AS (
44
+ SELECT id
45
+ FROM documents
46
+ WHERE embedding IS NOT NULL
47
+ ORDER BY embedding <=> $1::vector
48
+ LIMIT 40
49
+ ),
50
+ keyword_candidates AS (
51
+ SELECT id
52
+ FROM (
53
+ SELECT
54
+ id,
55
+ body_tsv <@> to_bm25query(
56
+ to_tsvector('english', $2),
57
+ 'documents_body_bm25'::regclass
58
+ ) AS score
59
+ FROM documents
60
+ ) AS keyword_scored
61
+ WHERE score < 0
62
+ ORDER BY score, id
63
+ LIMIT 40
64
+ ),
65
+ candidate_ids AS (
66
+ SELECT id FROM vector_candidates
67
+ UNION
68
+ SELECT id FROM keyword_candidates
69
+ )
70
+ SELECT d.id, d.title, d.body
71
+ FROM candidate_ids AS c
72
+ JOIN documents AS d ON d.id = c.id
73
+ ORDER BY d.id;
74
+ ```
75
+
76
+ Apply the same access-control and tenant filters inside both retrievers, before their limits. Take the final top results only after Jev scoring.
77
+
78
+ Batch yes/no relevance questions with the query shared in `state` and each candidate in its own question's `instructions`. Sort the returned probabilities in descending order; equal probabilities keep the input order.
79
+
80
+ Use Neon's provider with the Vercel AI SDK. Requirements:
81
+
82
+ - Install the tested versions: `npm install @neon/ai-sdk-provider@1.1.0 ai@7.0.133`. Decision models require AI SDK 7.0.133+; pin versions and retest upgrades while `experimental_decide` is experimental.
83
+ - Load the same `NEON_AI_GATEWAY_TOKEN` and `NEON_AI_GATEWAY_BASE_URL` used for [embeddings](vector-search.md#prepare-embeddings); the provider handles the endpoint and credentials.
84
+ - The AI Gateway, for both Jev and embeddings, requires a paid Neon plan with prepaid AI Gateway credits. Without them, embed documents and queries with one model from another provider and use [RRF](#rrf-example).
85
+
86
+ ```typescript
87
+ import { neon } from "@neon/ai-sdk-provider";
88
+ import { experimental_decide as decide } from "ai";
89
+
90
+ type Candidate = { id: string; title: string; body: string };
91
+
92
+ async function rerankWithJev(
93
+ queryText: string,
94
+ candidates: Candidate[], // deduplicated, authorized rows in a stable order
95
+ limit = 10,
96
+ batchSize = 80,
97
+ ): Promise<Candidate[]> {
98
+ if (!Number.isInteger(limit) || limit < 1) {
99
+ throw new Error("limit must be a positive integer");
100
+ }
101
+ if (!Number.isInteger(batchSize) || batchSize < 1) {
102
+ throw new Error("batchSize must be a positive integer");
103
+ }
104
+ if (candidates.length === 0) return [];
105
+
106
+ const model = neon.decisionModel("typesafeai-jev-1-14-0");
107
+ const criteria = {
108
+ true: "The candidate states the specific facts or steps the query asks for.",
109
+ false:
110
+ "The candidate only shares keywords or a topic with the query, answers a different question, or lacks the requested information.",
111
+ };
112
+ const abortSignal = AbortSignal.timeout(10_000); // whole reranking budget
113
+ const scored: { doc: Candidate; index: number; probability: number }[] = [];
114
+ for (let start = 0; start < candidates.length; start += batchSize) {
115
+ const batch = candidates.slice(start, start + batchSize);
116
+ const { answers } = await decide({
117
+ model,
118
+ state: { query: queryText }, // original text, without embedding instructions
119
+ questions: Object.fromEntries(
120
+ batch.map((doc, offset) => [
121
+ `d${start + offset}`, // response key only; the candidate goes in instructions
122
+ {
123
+ type: "boolean" as const,
124
+ instructions: {
125
+ question:
126
+ "Given the search query in state.query, does this candidate passage supply the specific information the user is looking for?",
127
+ candidate: { title: doc.title, body: doc.body },
128
+ },
129
+ criteria,
130
+ },
131
+ ]),
132
+ ),
133
+ maxRetries: 0, // propagate errors to the caller without retrying
134
+ abortSignal,
135
+ });
136
+ for (const [offset, doc] of batch.entries()) {
137
+ const index = start + offset;
138
+ const answer = answers[`d${index}`];
139
+ if (answer.type !== "boolean") {
140
+ throw new Error(`Missing relevance probability for d${index}`);
141
+ }
142
+ scored.push({ doc, index, probability: answer.probability });
143
+ }
144
+ }
145
+ return scored
146
+ .sort((a, b) => b.probability - a.probability || a.index - b.index)
147
+ .slice(0, limit)
148
+ .map(({ doc }) => doc);
149
+ }
150
+ ```
151
+
152
+ The SDK's `boolean` answer exposes the probability of yes as `answer.probability` (TypeSafe calls it `noul`). This is a probability that the passage answers the query, not a degree of completeness. Calibrate a threshold on judged no-match queries if the application must return "no answer."
153
+
154
+ `batchSize = 80` matches the maximum candidate pool above. Each request must fit Jev 1.14's 65,536-token context window, including all candidate text and questions; reduce the batch size for longer passages. Tune the shared timeout to the request's latency budget.
155
+
156
+ The caller can catch reranking errors and use [RRF](#rrf-example) as a fallback.
32
157
 
33
158
  ## RRF Example
34
159
 
35
- For rank `r` and constant `k`, each retriever contributes `1 / (k + r)`. The documented starting point uses 40 candidates per retriever and `k = 60`; tune both for the corpus and workload.
160
+ Use this query on its own when you want hybrid search without an additional model call.
161
+
162
+ For rank `r` and constant `k`, each retriever contributes `1 / (k + r)`. Start with a target of 40 candidates per retriever and `k = 60`; vector cutoff ties can exceed that target. Tune both for the corpus and workload.
36
163
 
37
- Embed the query text through the same gateway model used for the stored documents, then bind that vector as `$1`, the original query text as `$2`, and the final result count as `$3`:
164
+ Embed the query text with the same embedding model used for the stored documents, then bind that vector as `$1`, the original query text as `$2`, and the final result count as `$3`:
38
165
 
39
166
  ```sql
40
167
  WITH vector_ranked AS (
@@ -42,6 +169,7 @@ WITH vector_ranked AS (
42
169
  FROM (
43
170
  SELECT id, embedding <=> $1::vector AS distance
44
171
  FROM documents
172
+ WHERE embedding IS NOT NULL
45
173
  ORDER BY distance
46
174
  FETCH FIRST 40 ROWS WITH TIES
47
175
  ) AS vector_candidates
@@ -84,11 +212,12 @@ Vector retrieval preserves cutoff ties and can exceed 40 candidates. `lakebase_b
84
212
  ## Adapt the Hybrid Search
85
213
 
86
214
  - Retrieve more candidates from each source than the final result count; otherwise one retriever can dominate before fusion has enough overlap. Keep `lakebase_bm25.default_limit` at least as large as the BM25 candidate target.
87
- - Keep each retriever's operator and index configuration correct independently before tuning RRF.
215
+ - Keep each retriever's operator and index configuration correct independently before tuning fusion or reranking.
88
216
  - Tune candidate counts and the RRF constant with judged or behavioral relevance data, plus latency measurements.
217
+ - Compare vector-only, BM25-only, RRF-only, the deduplicated union plus Jev, and optional RRF plus Jev on the same judged queries to isolate each stage's contribution. Measure recall before reranking and nDCG@10 or MRR after it, alongside p95 latency, input-token cost, and fallback rate.
89
218
  - Add weights only when product evidence shows one retriever should contribute more. Weight the reciprocal-rank contributions, not the raw vector distance and negative BM25 score.
90
219
  - Apply the same access-control and tenant filters to both candidate CTEs. If BM25 filters are strict and cheap, evaluate whether `lakebase_bm25.prefilter` improves the filtered query.
91
220
 
92
- Source: [Lakebase Search get-started guide][lakebase-search-guide].
221
+ Sources: [Lakebase Search get-started guide][lakebase-search-guide] and [TypeSafe reranking cookbook](https://docs.typesafe.ai/cookbooks/rerank_typesafe).
93
222
 
94
223
  [lakebase-search-guide]: https://neon.com/docs/ai/lakebase-search-get-started#combine-results-with-hybrid-search
@@ -225,7 +225,7 @@ const rows = await db.execute(sql`
225
225
 
226
226
  Filter `score < 0` before the candidate cutoff: scalar BM25 scoring returns zero for non-matches, which must not become keyword hits. Partial query-term matches remain eligible.
227
227
 
228
- Run the [hybrid search](hybrid-search.md) RRF query the same way: raw SQL through `db.execute`.
228
+ Run either [hybrid search](hybrid-search.md) SQL query the same way: raw SQL through `db.execute`. For reranking with AI Gateway decision models, retrieve the deduplicated union of vector and full-text search candidates, including document bodies, and pass those rows directly to `rerankWithJev` before the final result cutoff. Use the RRF query as the alternative that needs no additional model call; RRF is optional before model-based reranking.
229
229
 
230
230
  ## Tune Per Query
231
231
 
@@ -35,6 +35,8 @@ CREATE TABLE documents (
35
35
  );
36
36
  ```
37
37
 
38
+ The AI Gateway is available on paid Neon plans only (Launch and Scale) and draws down prepaid AI Gateway credits. If a model shows `enabled: false` in `GET /v1/models`, the branch's AI Gateway page in the Neon Console lists the reason and the fix. See the `neon-ai-gateway` skill.
39
+
38
40
  Enable the AI Gateway on the branch and get `NEON_AI_GATEWAY_TOKEN` and the bare-host `NEON_AI_GATEWAY_BASE_URL`:
39
41
 
40
42
  - With `neon.ts`, declare `aiGateway: true`, run `neon deploy`, then run `neon env pull --file .env`.
@@ -1,4 +1,4 @@
1
- <!-- Generated by scripts/sync-skill-docs.mjs from website@thruflo/realtime-2-docs:24a2fd708 (docs/realtime/guides/queries). Do not edit: change the docs and run npm run sync:docs. sha256:d93bfa0e827dc447fc6108960e0dc3941c2126c9cfe5dc7ca3df6e662485f9f4 -->
1
+ <!-- Generated by scripts/sync-skill-docs.mjs from website@docs/neon-auth-package-rename:bf3595986 (docs/realtime/guides/queries). Do not edit: change the docs and run npm run sync:docs. sha256:ece6ed71de561220661f3b36acb1c6721884a650d2229d65f96afd305b1afcfd -->
2
2
  Canonical page: https://neon.com/docs/realtime/guides/queries.md
3
3
 
4
4
  > Summary: Define live queries in your backend with raw SQL or Drizzle, fill in their parameters from the authenticated request, and seal them so clients can subscribe without being able to read or change them.
@@ -52,7 +52,7 @@ npm install @neon/realtime @neon/realtime-drizzle
52
52
  Install the [Managed Better Auth](https://neon.com/docs/auth/overview.md) client for the frontend:
53
53
 
54
54
  ```bash filename="Terminal"
55
- npm install @neondatabase/auth
55
+ npm install @neon/auth
56
56
  ```
57
57
 
58
58
  Add a `neon.ts` file that enables Managed Better Auth and [Realtime](https://neon.com/docs/realtime/quickstart.md#enable-realtime) on your branch:
@@ -306,7 +306,7 @@ This is where **sealing** comes in. Sealing signs and encrypts the exact query,
306
306
 
307
307
  **Warning: Keep your Realtime secret on the server**
308
308
 
309
- Anyone with `NEON_REALTIME_SECRET` can seal any query. Treat it like your `DATABASE_URL`, and never ship it in a browser bundle. In a Vite app, that means never giving it a `VITE_` prefix.
309
+ Anyone with `NEON_REALTIME_SECRET` can seal any query. Treat it like your `DATABASE_URL`, and never ship it in a browser bundle. In a Vite app, that means never giving it a `VITE_` prefix. To replace it, run [`neon realtime rotate-secret`](https://neon.com/docs/cli/realtime.md#rotate-secret).
310
310
 
311
311
  To seal a query you pass your query instance, e.g.:
312
312
 
@@ -1,4 +1,4 @@
1
- <!-- Generated by scripts/sync-skill-docs.mjs from website@thruflo/realtime-3-integration:f26c1f629 (docs/realtime/guides/reactivity). Do not edit: change the docs and run npm run sync:docs. sha256:f6b3f6d6112f189444e30239f81d46c9e1431a61c2242286807d01190137ab87 -->
1
+ <!-- Generated by scripts/sync-skill-docs.mjs from website@docs/neon-auth-package-rename:bf3595986 (docs/realtime/guides/reactivity). Do not edit: change the docs and run npm run sync:docs. sha256:8af3b50922c0df744e30924ee5065e06209115ee44b509cdbdea1ac6c005eb7a -->
2
2
  Canonical page: https://neon.com/docs/realtime/guides/reactivity.md
3
3
 
4
4
  > Summary: Bind live queries to React component state with useLiveQuery, change their parameters and handle errors, or sync a broader live query into a TanStack DB collection and derive instant, local queries from it.
@@ -347,7 +347,7 @@ if (!session) {
347
347
  }
348
348
  ```
349
349
 
350
- Sign-in isn't part of these guides: build the page with Neon's [Managed Better Auth UI components](https://neon.com/docs/auth/reference/ui-components.md), as the [running example](https://github.com/neondatabase/examples/tree/main/realtime/guides-chat-app) does by rendering `AuthView` on `/auth/*` before it checks the session.
350
+ Sign-in isn't part of these guides: build the page with [Better Auth UI](https://neon.com/docs/auth/reference/ui-components.md), as the [running example](https://github.com/neondatabase/examples/tree/main/realtime/guides-chat-app) does by rendering `<Auth>` on `/auth/*` before it checks the session.
351
351
 
352
352
  Then read from the collection with TanStack's own `useLiveQuery()`. It shares a name with the Realtime hook, so import it under an alias that won't clash in an app that uses both. This view shows one channel, newest first:
353
353
 
@@ -1,4 +1,4 @@
1
- <!-- Generated by scripts/sync-skill-docs.mjs from website@thruflo/realtime-2-docs:24a2fd708 (docs/realtime/guides/ssr). Do not edit: change the docs and run npm run sync:docs. sha256:55d466b2446614f5b3ce667589f4dfe9606324c21f578c044ec6fa722f6696ba -->
1
+ <!-- Generated by scripts/sync-skill-docs.mjs from website@docs/neon-auth-package-rename:bf3595986 (docs/realtime/guides/ssr). Do not edit: change the docs and run npm run sync:docs. sha256:706192b0e9baf22373be7c09fa4e264a0ef62a5fd829043e2fae0691a52da93a -->
2
2
  Canonical page: https://neon.com/docs/realtime/guides/ssr.md
3
3
 
4
4
  > Summary: Server-render pages that use live queries. Read and seal the same query for each request, send both to the browser, render the initial rows straight away and let the first result bring the page live.
@@ -176,12 +176,12 @@ Or with [TanStack Start](https://neon.com/docs/realtime/examples/tanstack.md), [
176
176
 
177
177
  <summary>Read the Managed Better Auth session in TanStack Start</summary>
178
178
 
179
- This setup is built on the beta Managed Better Auth server toolkit, `@neondatabase/auth/server`. Swap in the official adapter when it ships.
179
+ This setup is built on the beta Managed Better Auth server toolkit, `@neon/auth/server`. Swap in the official adapter when it ships.
180
180
 
181
181
  Create the auth server. It reads and sets the session cookies through TanStack Start's request helpers:
182
182
 
183
183
  ```ts filename="src/backend/auth.ts"
184
- import { createAuthServer, extractNeonAuthCookies } from "@neondatabase/auth/server"
184
+ import { createAuthServer, extractNeonAuthCookies } from "@neon/auth/server"
185
185
  import { getRequest, setCookie } from "@tanstack/react-start/server"
186
186
 
187
187
  export const authConfig = {
@@ -214,7 +214,7 @@ printf '\nNEON_AUTH_COOKIE_SECRET=%s\n' "$(openssl rand -base64 32)" >> .env.loc
214
214
  Mount the Managed Better Auth proxy at `/api/auth`, so the session cookie lives on your app's origin:
215
215
 
216
216
  ```ts filename="src/routes/api/auth/$.ts"
217
- import { handleAuthProxyRequest } from "@neondatabase/auth/server"
217
+ import { handleAuthProxyRequest } from "@neon/auth/server"
218
218
  import { createFileRoute } from "@tanstack/react-router"
219
219
 
220
220
  import { authConfig } from "../../../backend/auth"
@@ -258,7 +258,7 @@ export const getSessionUser = createServerFn({ method: "GET" }).handler(async ()
258
258
  Point the auth client at the proxy. An empty URL makes it use `/api/auth` on the page's origin:
259
259
 
260
260
  ```ts filename="src/frontend/auth.ts"
261
- import { createAuthClient } from "@neondatabase/auth"
261
+ import { createAuthClient } from "@neon/auth"
262
262
 
263
263
  export const authClient = createAuthClient("") // same origin: /api/auth
264
264
  ```
@@ -1,4 +1,4 @@
1
- <!-- Generated by scripts/sync-skill-docs.mjs from website@thruflo/realtime-2-docs:24a2fd708 (docs/realtime/guides/subscribing). Do not edit: change the docs and run npm run sync:docs. sha256:6d28cb355161f30b463590c44edc4e95dce5a899544807f30530cf4093bc074c -->
1
+ <!-- Generated by scripts/sync-skill-docs.mjs from website@docs/neon-auth-package-rename:bf3595986 (docs/realtime/guides/subscribing). Do not edit: change the docs and run npm run sync:docs. sha256:daef4cc4851b540a8fbc1fb5f2e9169fd4f8326fac759460fc3281a830c6f524 -->
2
2
  Canonical page: https://neon.com/docs/realtime/guides/subscribing.md
3
3
 
4
4
  > Summary: Subscribe to live queries from trusted backend code or the browser. Fetch sealed queries from your API, handle every callback and renew sealed queries before they expire.
@@ -83,7 +83,7 @@ Most queries depend on who's asking and what they're asking for.
83
83
  If you've [exposed your sealed query via an API endpoint](queries.md#exposing-an-endpoint), you can provide this context via the request data using your standard auth machinery, such as Neon's [Managed Better Auth](https://neon.com/docs/auth/overview.md):
84
84
 
85
85
  ```ts filename="frontend/auth.ts"
86
- import { createAuthClient } from "@neondatabase/auth"
86
+ import { createAuthClient } from "@neon/auth"
87
87
 
88
88
  export const authClient = createAuthClient(import.meta.env.VITE_NEON_AUTH_URL)
89
89
  ```