@convex-dev/rag 0.7.0 → 0.7.2

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.
Files changed (55) hide show
  1. package/dist/client/hybridRank.d.ts +1 -1
  2. package/dist/client/hybridRank.js +1 -1
  3. package/dist/client/index.d.ts +35 -3
  4. package/dist/client/index.d.ts.map +1 -1
  5. package/dist/client/index.js +32 -16
  6. package/dist/client/index.js.map +1 -1
  7. package/dist/component/_generated/api.d.ts +2 -0
  8. package/dist/component/_generated/api.d.ts.map +1 -1
  9. package/dist/component/_generated/api.js.map +1 -1
  10. package/dist/component/_generated/component.d.ts +6 -1
  11. package/dist/component/_generated/component.d.ts.map +1 -1
  12. package/dist/component/_generated/server.d.ts.map +1 -1
  13. package/dist/component/chunks.d.ts +21 -14
  14. package/dist/component/chunks.d.ts.map +1 -1
  15. package/dist/component/chunks.js +67 -64
  16. package/dist/component/chunks.js.map +1 -1
  17. package/dist/component/entries.d.ts +18 -54
  18. package/dist/component/entries.d.ts.map +1 -1
  19. package/dist/component/entries.js +21 -64
  20. package/dist/component/entries.js.map +1 -1
  21. package/dist/component/helpers.d.ts +70 -0
  22. package/dist/component/helpers.d.ts.map +1 -0
  23. package/dist/component/helpers.js +83 -0
  24. package/dist/component/helpers.js.map +1 -0
  25. package/dist/component/namespaces.d.ts +45 -73
  26. package/dist/component/namespaces.d.ts.map +1 -1
  27. package/dist/component/namespaces.js +10 -48
  28. package/dist/component/namespaces.js.map +1 -1
  29. package/dist/component/schema.d.ts +34 -34
  30. package/dist/component/schema.d.ts.map +1 -1
  31. package/dist/component/schema.js +0 -1
  32. package/dist/component/schema.js.map +1 -1
  33. package/dist/component/search.d.ts +45 -2
  34. package/dist/component/search.d.ts.map +1 -1
  35. package/dist/component/search.js +188 -17
  36. package/dist/component/search.js.map +1 -1
  37. package/dist/shared.d.ts +2 -0
  38. package/dist/shared.d.ts.map +1 -1
  39. package/dist/shared.js +1 -0
  40. package/dist/shared.js.map +1 -1
  41. package/package.json +31 -29
  42. package/src/client/hybridRank.ts +1 -1
  43. package/src/client/index.ts +76 -16
  44. package/src/component/_generated/api.ts +2 -0
  45. package/src/component/_generated/component.ts +6 -1
  46. package/src/component/_generated/server.ts +0 -5
  47. package/src/component/chunks.ts +103 -93
  48. package/src/component/entries.ts +32 -84
  49. package/src/component/helpers.ts +124 -0
  50. package/src/component/namespaces.test.ts +97 -0
  51. package/src/component/namespaces.ts +25 -82
  52. package/src/component/schema.ts +0 -1
  53. package/src/component/search.test.ts +303 -1
  54. package/src/component/search.ts +266 -19
  55. package/src/shared.ts +7 -0
@@ -1,3 +1,18 @@
1
+ import { assert } from "convex-helpers";
2
+ import { paginator } from "convex-helpers/server/pagination";
3
+ import { mergedStream, stream } from "convex-helpers/server/stream";
4
+ import { paginationOptsValidator, PaginationResult } from "convex/server";
5
+ import type { Infer } from "convex/values";
6
+ import {
7
+ statuses,
8
+ vActiveStatus,
9
+ vEntry,
10
+ vNamespace,
11
+ vPaginationResult,
12
+ vStatus,
13
+ type OnCompleteNamespace,
14
+ } from "../shared.js";
15
+ import { api } from "./_generated/api.js";
1
16
  import type { Doc, Id } from "./_generated/dataModel.js";
2
17
  import {
3
18
  action,
@@ -5,59 +20,15 @@ import {
5
20
  mutation,
6
21
  query,
7
22
  type MutationCtx,
8
- type QueryCtx,
9
23
  } from "./_generated/server.js";
10
- import { schema, v } from "./schema.js";
24
+ import { deleteEntrySync } from "./entries.js";
11
25
  import {
12
- vNamespace,
13
- vPaginationResult,
14
- vActiveStatus,
15
- type Namespace,
16
- type NamespaceId,
17
- type OnCompleteNamespace,
18
- vStatus,
19
- statuses,
20
- filterNamesContain,
21
- vEntry,
22
- } from "../shared.js";
23
- import { paginationOptsValidator, PaginationResult } from "convex/server";
24
- import { paginator } from "convex-helpers/server/pagination";
25
- import type { Infer, ObjectType } from "convex/values";
26
- import { mergedStream, stream } from "convex-helpers/server/stream";
27
- import { assert } from "convex-helpers";
28
- import { api } from "./_generated/api.js";
29
-
30
- function namespaceIsCompatible(
31
- existing: Doc<"namespaces">,
32
- args: {
33
- modelId: string;
34
- dimension: number;
35
- filterNames: string[];
36
- },
37
- ) {
38
- // Check basic compatibility
39
- if (
40
- existing.modelId !== args.modelId ||
41
- existing.dimension !== args.dimension
42
- ) {
43
- return false;
44
- }
45
-
46
- // For filter names, the namespace must support all requested filters
47
- // but can support additional filters (superset is OK)
48
- if (!filterNamesContain(existing.filterNames, args.filterNames)) {
49
- return false;
50
- }
51
-
52
- return true;
53
- }
54
-
55
- export const vNamespaceLookupArgs = {
56
- namespace: v.string(),
57
- modelId: v.string(),
58
- dimension: v.number(),
59
- filterNames: v.array(v.string()),
60
- };
26
+ getCompatibleNamespaceHandler,
27
+ namespaceIsCompatible,
28
+ publicNamespace,
29
+ vNamespaceLookupArgs,
30
+ } from "./helpers.js";
31
+ import { schema, v } from "./schema.js";
61
32
 
62
33
  export const get = query({
63
34
  args: vNamespaceLookupArgs,
@@ -77,24 +48,6 @@ export const getCompatibleNamespace = internalQuery({
77
48
  handler: getCompatibleNamespaceHandler,
78
49
  });
79
50
 
80
- export async function getCompatibleNamespaceHandler(
81
- ctx: QueryCtx,
82
- args: ObjectType<typeof vNamespaceLookupArgs>,
83
- ) {
84
- const iter = ctx.db
85
- .query("namespaces")
86
- .withIndex("status_namespace_version", (q) =>
87
- q.eq("status.kind", "ready").eq("namespace", args.namespace),
88
- )
89
- .order("desc");
90
- for await (const existing of iter) {
91
- if (namespaceIsCompatible(existing, args)) {
92
- return existing;
93
- }
94
- }
95
- return null;
96
- }
97
-
98
51
  export const lookup = query({
99
52
  args: {
100
53
  namespace: v.string(),
@@ -312,16 +265,6 @@ export const listNamespaceVersions = query({
312
265
  },
313
266
  });
314
267
 
315
- export function publicNamespace(namespace: Doc<"namespaces">): Namespace {
316
- const { _id, _creationTime, status, ...rest } = namespace;
317
- return {
318
- namespaceId: _id as unknown as NamespaceId,
319
- createdAt: _creationTime,
320
- ...rest,
321
- status: status.kind,
322
- };
323
- }
324
-
325
268
  export const deleteNamespace = mutation({
326
269
  args: { namespaceId: v.id("namespaces") },
327
270
  returns: v.object({
@@ -368,13 +311,13 @@ export const deleteNamespaceSync = action({
368
311
  cursor,
369
312
  },
370
313
  })) as PaginationResult<Infer<typeof vEntry>>;
314
+ for (const entry of entries.page) {
315
+ await deleteEntrySync(ctx, entry.entryId as unknown as Id<"entries">);
316
+ }
371
317
  if (entries.isDone) {
372
318
  break;
373
319
  }
374
320
  cursor = entries.continueCursor;
375
- await ctx.runAction(api.entries.deleteSync, {
376
- entryId: entries.page[0].entryId as unknown as Id<"entries">,
377
- });
378
321
  }
379
322
  }
380
323
  await ctx.runMutation(api.namespaces.deleteNamespace, {
@@ -71,7 +71,6 @@ export const schema = defineSchema({
71
71
  v.object({
72
72
  kind: v.literal("ready"),
73
73
  embeddingId: vVectorId,
74
- // TODO: text search
75
74
  searchableText: v.optional(v.string()),
76
75
  }),
77
76
  v.object({
@@ -3,7 +3,7 @@
3
3
  import { describe, expect, test } from "vitest";
4
4
  import { convexTest, type TestConvex } from "convex-test";
5
5
  import schema from "./schema.js";
6
- import { api } from "./_generated/api.js";
6
+ import { api, internal } from "./_generated/api.js";
7
7
  import { modules } from "./setup.test.js";
8
8
  import { insertChunks } from "./chunks.js";
9
9
  import type { Id } from "./_generated/dataModel.js";
@@ -442,4 +442,306 @@ describe("search", () => {
442
442
  );
443
443
  }
444
444
  });
445
+
446
+ describe("hybrid search", () => {
447
+ function createSearchableChunks(texts: string[], baseEmbedding = 0.1) {
448
+ return texts.map((text, i) => ({
449
+ content: { text, metadata: { index: i } },
450
+ embedding: [...Array(127).fill(0.01), baseEmbedding + i * 0.01],
451
+ searchableText: text,
452
+ }));
453
+ }
454
+
455
+ test("textSearch internal query finds chunks by text content", async () => {
456
+ const t = convexTest(schema, modules);
457
+ const namespaceId = await setupTestNamespace(t);
458
+ const entryId = await setupTestEntry(t, namespaceId);
459
+
460
+ const chunks = createSearchableChunks([
461
+ "The quick brown fox jumps over the lazy dog",
462
+ "A fast red car drives on the highway",
463
+ "The brown bear sleeps in the forest",
464
+ ]);
465
+
466
+ await t.run(async (ctx) => {
467
+ await insertChunks(ctx, { entryId, startOrder: 0, chunks });
468
+ });
469
+
470
+ const results = await t.query(internal.search.textSearch, {
471
+ query: "brown",
472
+ namespaceId,
473
+ filters: [],
474
+ limit: 10,
475
+ });
476
+
477
+ expect(results.length).toBeGreaterThan(0);
478
+ for (const r of results) {
479
+ expect(r.entryId).toBe(entryId);
480
+ }
481
+ });
482
+
483
+ test("textSearch scopes results to the given namespace", async () => {
484
+ const t = convexTest(schema, modules);
485
+ const ns1Id = await setupTestNamespace(t, "namespace-1");
486
+ const ns2Id = await setupTestNamespace(t, "namespace-2");
487
+ const entry1Id = await setupTestEntry(t, ns1Id, "entry-1");
488
+ const entry2Id = await setupTestEntry(t, ns2Id, "entry-2");
489
+
490
+ await t.run(async (ctx) => {
491
+ await insertChunks(ctx, {
492
+ entryId: entry1Id,
493
+ startOrder: 0,
494
+ chunks: createSearchableChunks(["alpha bravo charlie"]),
495
+ });
496
+ await insertChunks(ctx, {
497
+ entryId: entry2Id,
498
+ startOrder: 0,
499
+ chunks: createSearchableChunks(["alpha delta echo"]),
500
+ });
501
+ });
502
+
503
+ const ns1Results = await t.query(internal.search.textSearch, {
504
+ query: "alpha",
505
+ namespaceId: ns1Id,
506
+ filters: [],
507
+ limit: 10,
508
+ });
509
+
510
+ // All results should belong to namespace-1's entry.
511
+ for (const r of ns1Results) {
512
+ expect(r.entryId).toBe(entry1Id);
513
+ }
514
+ });
515
+
516
+ test("textSearch applies numbered filters", async () => {
517
+ const t = convexTest(schema, modules);
518
+ const namespaceId = await setupTestNamespace(t, "filtered-ns", 128, [
519
+ "category",
520
+ ]);
521
+
522
+ const cat1Entry = await setupTestEntry(t, namespaceId, "cat1", 0, [
523
+ { name: "category", value: "docs" },
524
+ ]);
525
+ const cat2Entry = await setupTestEntry(t, namespaceId, "cat2", 0, [
526
+ { name: "category", value: "blogs" },
527
+ ]);
528
+
529
+ await t.run(async (ctx) => {
530
+ await insertChunks(ctx, {
531
+ entryId: cat1Entry,
532
+ startOrder: 0,
533
+ chunks: createSearchableChunks(["shared keyword content"]),
534
+ });
535
+ await insertChunks(ctx, {
536
+ entryId: cat2Entry,
537
+ startOrder: 0,
538
+ chunks: createSearchableChunks(["shared keyword content"]),
539
+ });
540
+ });
541
+
542
+ // Filter to "docs" category only (filter index 0 = "category").
543
+ const results = await t.query(internal.search.textSearch, {
544
+ query: "shared keyword",
545
+ namespaceId,
546
+ filters: [{ 0: "docs" }],
547
+ limit: 10,
548
+ });
549
+
550
+ expect(results.length).toBeGreaterThan(0);
551
+ for (const r of results) {
552
+ expect(r.entryId).toBe(cat1Entry);
553
+ }
554
+ });
555
+
556
+ test("text-only search returns results via dimension arg", async () => {
557
+ const t = convexTest(schema, modules);
558
+ const namespaceId = await setupTestNamespace(t);
559
+ const entryId = await setupTestEntry(t, namespaceId);
560
+
561
+ const chunks = createSearchableChunks([
562
+ "Machine learning is a subset of artificial intelligence",
563
+ "Deep learning uses neural networks with many layers",
564
+ "Natural language processing handles text data",
565
+ ]);
566
+
567
+ await t.run(async (ctx) => {
568
+ await insertChunks(ctx, { entryId, startOrder: 0, chunks });
569
+ });
570
+
571
+ // Text-only: no embedding, provide dimension instead.
572
+ const result = await t.action(api.search.search, {
573
+ namespace: "test-namespace",
574
+ dimension: 128,
575
+ modelId: "test-model",
576
+ filters: [],
577
+ limit: 10,
578
+ textQuery: "neural networks",
579
+ });
580
+
581
+ expect(result.results.length).toBeGreaterThan(0);
582
+ expect(result.entries).toHaveLength(1);
583
+
584
+ // Text-only scores are position-based.
585
+ expect(result.results[0].score).toBe(1.0);
586
+ for (let i = 1; i < result.results.length; i++) {
587
+ expect(result.results[i].score).toBeLessThan(
588
+ result.results[i - 1].score,
589
+ );
590
+ }
591
+ });
592
+
593
+ test("hybrid search returns results when textQuery is provided", async () => {
594
+ const t = convexTest(schema, modules);
595
+ const namespaceId = await setupTestNamespace(t);
596
+ const entryId = await setupTestEntry(t, namespaceId);
597
+
598
+ const chunks = createSearchableChunks([
599
+ "Machine learning is a subset of artificial intelligence",
600
+ "Deep learning uses neural networks with many layers",
601
+ "Natural language processing handles text data",
602
+ ]);
603
+
604
+ await t.run(async (ctx) => {
605
+ await insertChunks(ctx, { entryId, startOrder: 0, chunks });
606
+ });
607
+
608
+ const result = await t.action(api.search.search, {
609
+ namespace: "test-namespace",
610
+ embedding: [...Array(127).fill(0.01), 0.1],
611
+ modelId: "test-model",
612
+ filters: [],
613
+ limit: 10,
614
+ textQuery: "neural networks",
615
+ });
616
+
617
+ expect(result.results.length).toBeGreaterThan(0);
618
+ expect(result.entries).toHaveLength(1);
619
+
620
+ // Hybrid scores are position-based (1.0 for top, decreasing linearly).
621
+ expect(result.results[0].score).toBe(1.0);
622
+ for (let i = 1; i < result.results.length; i++) {
623
+ expect(result.results[i].score).toBeLessThan(
624
+ result.results[i - 1].score,
625
+ );
626
+ }
627
+ });
628
+
629
+ test("hybrid search deduplicates results from vector and text paths", async () => {
630
+ const t = convexTest(schema, modules);
631
+ const namespaceId = await setupTestNamespace(t);
632
+ const entryId = await setupTestEntry(t, namespaceId);
633
+
634
+ const chunks = createSearchableChunks([
635
+ "Unique content about quantum computing",
636
+ "Another chunk about classical physics",
637
+ ]);
638
+
639
+ await t.run(async (ctx) => {
640
+ await insertChunks(ctx, { entryId, startOrder: 0, chunks });
641
+ });
642
+
643
+ const result = await t.action(api.search.search, {
644
+ namespace: "test-namespace",
645
+ embedding: [...Array(127).fill(0.01), 0.1],
646
+ modelId: "test-model",
647
+ filters: [],
648
+ limit: 10,
649
+ textQuery: "quantum computing",
650
+ });
651
+
652
+ // Each chunk should appear at most once in the results.
653
+ const entryOrderPairs = result.results.map(
654
+ (r) => `${r.entryId}:${r.order}`,
655
+ );
656
+ const uniquePairs = new Set(entryOrderPairs);
657
+ expect(uniquePairs.size).toBe(entryOrderPairs.length);
658
+ });
659
+
660
+ test("vector-only search is unchanged when textQuery is not provided", async () => {
661
+ const t = convexTest(schema, modules);
662
+ const namespaceId = await setupTestNamespace(t);
663
+ const entryId = await setupTestEntry(t, namespaceId);
664
+
665
+ const targetEmbedding = [...Array(127).fill(0.5), 1];
666
+ const chunks = [
667
+ {
668
+ content: { text: "Target chunk", metadata: {} },
669
+ embedding: targetEmbedding,
670
+ searchableText: "Target chunk",
671
+ },
672
+ {
673
+ content: { text: "Other chunk", metadata: {} },
674
+ embedding: [...Array(127).fill(0.1), 0],
675
+ searchableText: "Other chunk",
676
+ },
677
+ ];
678
+
679
+ await t.run(async (ctx) => {
680
+ await insertChunks(ctx, { entryId, startOrder: 0, chunks });
681
+ });
682
+
683
+ const result = await t.action(api.search.search, {
684
+ namespace: "test-namespace",
685
+ embedding: targetEmbedding,
686
+ modelId: "test-model",
687
+ filters: [],
688
+ limit: 10,
689
+ });
690
+
691
+ // Without textQuery, scores should be cosine similarity (not position-based).
692
+ expect(result.results).toHaveLength(2);
693
+ expect(result.results[0].score).toBeGreaterThan(result.results[1].score);
694
+ // Cosine similarity scores are typically between -1 and 1, not exactly 1.0.
695
+ // Position-based would give exactly 1.0 for the first result.
696
+ // With cosine similarity the first result can be 1.0 if exact match,
697
+ // but the second should not follow the linear decrease pattern.
698
+ expect(result.results[0].content[0].text).toBe("Target chunk");
699
+ });
700
+
701
+ test("textWeight and vectorWeight influence hybrid ranking", async () => {
702
+ const t = convexTest(schema, modules);
703
+ const namespaceId = await setupTestNamespace(t);
704
+ const entryId = await setupTestEntry(t, namespaceId);
705
+
706
+ const chunks = createSearchableChunks([
707
+ "Alpha topic with specific terminology",
708
+ "Beta topic with different keywords",
709
+ "Gamma topic about something else entirely",
710
+ ]);
711
+
712
+ await t.run(async (ctx) => {
713
+ await insertChunks(ctx, { entryId, startOrder: 0, chunks });
714
+ });
715
+
716
+ const embedding = [...Array(127).fill(0.01), 0.1];
717
+
718
+ // Search with heavy text weight.
719
+ const textHeavy = await t.action(api.search.search, {
720
+ namespace: "test-namespace",
721
+ embedding,
722
+ modelId: "test-model",
723
+ filters: [],
724
+ limit: 10,
725
+ textQuery: "specific terminology",
726
+ textWeight: 10,
727
+ vectorWeight: 1,
728
+ });
729
+
730
+ // Search with heavy vector weight.
731
+ const vectorHeavy = await t.action(api.search.search, {
732
+ namespace: "test-namespace",
733
+ embedding,
734
+ modelId: "test-model",
735
+ filters: [],
736
+ limit: 10,
737
+ textQuery: "specific terminology",
738
+ textWeight: 1,
739
+ vectorWeight: 10,
740
+ });
741
+
742
+ // Both should return results.
743
+ expect(textHeavy.results.length).toBeGreaterThan(0);
744
+ expect(vectorHeavy.results.length).toBeGreaterThan(0);
745
+ });
746
+ });
445
747
  });