@librechat/agents 2.4.30 → 2.4.33

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 (124) hide show
  1. package/dist/cjs/common/enum.cjs +1 -0
  2. package/dist/cjs/common/enum.cjs.map +1 -1
  3. package/dist/cjs/events.cjs +3 -3
  4. package/dist/cjs/events.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +2 -1
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/main.cjs +7 -2
  8. package/dist/cjs/main.cjs.map +1 -1
  9. package/dist/cjs/messages/ids.cjs +23 -0
  10. package/dist/cjs/messages/ids.cjs.map +1 -0
  11. package/dist/cjs/splitStream.cjs +2 -1
  12. package/dist/cjs/splitStream.cjs.map +1 -1
  13. package/dist/cjs/stream.cjs +87 -154
  14. package/dist/cjs/stream.cjs.map +1 -1
  15. package/dist/cjs/tools/ToolNode.cjs +14 -3
  16. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  17. package/dist/cjs/tools/handlers.cjs +144 -0
  18. package/dist/cjs/tools/handlers.cjs.map +1 -0
  19. package/dist/cjs/tools/search/content.cjs +140 -0
  20. package/dist/cjs/tools/search/content.cjs.map +1 -0
  21. package/dist/cjs/tools/search/firecrawl.cjs +131 -0
  22. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -0
  23. package/dist/cjs/tools/search/format.cjs +203 -0
  24. package/dist/cjs/tools/search/format.cjs.map +1 -0
  25. package/dist/cjs/tools/search/highlights.cjs +245 -0
  26. package/dist/cjs/tools/search/highlights.cjs.map +1 -0
  27. package/dist/cjs/tools/search/rerankers.cjs +194 -0
  28. package/dist/cjs/tools/search/rerankers.cjs.map +1 -0
  29. package/dist/cjs/tools/search/schema.cjs +70 -0
  30. package/dist/cjs/tools/search/schema.cjs.map +1 -0
  31. package/dist/cjs/tools/search/search.cjs +491 -0
  32. package/dist/cjs/tools/search/search.cjs.map +1 -0
  33. package/dist/cjs/tools/search/tool.cjs +292 -0
  34. package/dist/cjs/tools/search/tool.cjs.map +1 -0
  35. package/dist/cjs/tools/search/utils.cjs +66 -0
  36. package/dist/cjs/tools/search/utils.cjs.map +1 -0
  37. package/dist/esm/common/enum.mjs +1 -0
  38. package/dist/esm/common/enum.mjs.map +1 -1
  39. package/dist/esm/events.mjs +1 -1
  40. package/dist/esm/events.mjs.map +1 -1
  41. package/dist/esm/graphs/Graph.mjs +2 -1
  42. package/dist/esm/graphs/Graph.mjs.map +1 -1
  43. package/dist/esm/main.mjs +4 -1
  44. package/dist/esm/main.mjs.map +1 -1
  45. package/dist/esm/messages/ids.mjs +21 -0
  46. package/dist/esm/messages/ids.mjs.map +1 -0
  47. package/dist/esm/splitStream.mjs +2 -1
  48. package/dist/esm/splitStream.mjs.map +1 -1
  49. package/dist/esm/stream.mjs +87 -152
  50. package/dist/esm/stream.mjs.map +1 -1
  51. package/dist/esm/tools/ToolNode.mjs +14 -3
  52. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  53. package/dist/esm/tools/handlers.mjs +141 -0
  54. package/dist/esm/tools/handlers.mjs.map +1 -0
  55. package/dist/esm/tools/search/content.mjs +119 -0
  56. package/dist/esm/tools/search/content.mjs.map +1 -0
  57. package/dist/esm/tools/search/firecrawl.mjs +128 -0
  58. package/dist/esm/tools/search/firecrawl.mjs.map +1 -0
  59. package/dist/esm/tools/search/format.mjs +201 -0
  60. package/dist/esm/tools/search/format.mjs.map +1 -0
  61. package/dist/esm/tools/search/highlights.mjs +243 -0
  62. package/dist/esm/tools/search/highlights.mjs.map +1 -0
  63. package/dist/esm/tools/search/rerankers.mjs +188 -0
  64. package/dist/esm/tools/search/rerankers.mjs.map +1 -0
  65. package/dist/esm/tools/search/schema.mjs +61 -0
  66. package/dist/esm/tools/search/schema.mjs.map +1 -0
  67. package/dist/esm/tools/search/search.mjs +488 -0
  68. package/dist/esm/tools/search/search.mjs.map +1 -0
  69. package/dist/esm/tools/search/tool.mjs +290 -0
  70. package/dist/esm/tools/search/tool.mjs.map +1 -0
  71. package/dist/esm/tools/search/utils.mjs +61 -0
  72. package/dist/esm/tools/search/utils.mjs.map +1 -0
  73. package/dist/types/common/enum.d.ts +1 -0
  74. package/dist/types/graphs/Graph.d.ts +1 -1
  75. package/dist/types/index.d.ts +2 -0
  76. package/dist/types/messages/ids.d.ts +3 -0
  77. package/dist/types/messages/index.d.ts +1 -0
  78. package/dist/types/scripts/search.d.ts +1 -0
  79. package/dist/types/stream.d.ts +0 -8
  80. package/dist/types/tools/ToolNode.d.ts +6 -0
  81. package/dist/types/tools/example.d.ts +23 -3
  82. package/dist/types/tools/handlers.d.ts +8 -0
  83. package/dist/types/tools/search/content.d.ts +4 -0
  84. package/dist/types/tools/search/firecrawl.d.ts +38 -0
  85. package/dist/types/tools/search/format.d.ts +5 -0
  86. package/dist/types/tools/search/highlights.d.ts +13 -0
  87. package/dist/types/tools/search/index.d.ts +2 -0
  88. package/dist/types/tools/search/rerankers.d.ts +36 -0
  89. package/dist/types/tools/search/schema.d.ts +16 -0
  90. package/dist/types/tools/search/search.d.ts +9 -0
  91. package/dist/types/tools/search/test.d.ts +1 -0
  92. package/dist/types/tools/search/tool.d.ts +33 -0
  93. package/dist/types/tools/search/types.d.ts +540 -0
  94. package/dist/types/tools/search/utils.d.ts +10 -0
  95. package/package.json +10 -7
  96. package/src/common/enum.ts +1 -0
  97. package/src/events.ts +49 -15
  98. package/src/graphs/Graph.ts +6 -2
  99. package/src/index.ts +2 -0
  100. package/src/messages/ids.ts +26 -0
  101. package/src/messages/index.ts +1 -0
  102. package/src/scripts/search.ts +146 -0
  103. package/src/splitStream.test.ts +132 -71
  104. package/src/splitStream.ts +2 -1
  105. package/src/stream.ts +94 -183
  106. package/src/tools/ToolNode.ts +37 -14
  107. package/src/tools/handlers.ts +167 -0
  108. package/src/tools/search/content.test.ts +173 -0
  109. package/src/tools/search/content.ts +147 -0
  110. package/src/tools/search/firecrawl.ts +158 -0
  111. package/src/tools/search/format.ts +252 -0
  112. package/src/tools/search/highlights.ts +320 -0
  113. package/src/tools/search/index.ts +2 -0
  114. package/src/tools/search/output.md +2775 -0
  115. package/src/tools/search/rerankers.ts +269 -0
  116. package/src/tools/search/schema.ts +63 -0
  117. package/src/tools/search/search.ts +680 -0
  118. package/src/tools/search/test.html +884 -0
  119. package/src/tools/search/test.md +643 -0
  120. package/src/tools/search/test.ts +159 -0
  121. package/src/tools/search/tool.ts +427 -0
  122. package/src/tools/search/types.ts +621 -0
  123. package/src/tools/search/utils.ts +79 -0
  124. package/src/utils/llmConfig.ts +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.cjs","sources":["../../../../src/tools/search/format.ts"],"sourcesContent":["import type * as t from './types';\nimport { getDomainName, fileExtRegex } from './utils';\n\nfunction addHighlightSection(): string[] {\n return ['\\n## Highlights', ''];\n}\n\n// Helper function to format a source (organic or top story)\nfunction formatSource(\n source: t.ValidSource,\n index: number,\n turn: number,\n sourceType: 'search' | 'news',\n references: t.ResultReference[]\n): string {\n /** Array of all lines to include in the output */\n const outputLines: string[] = [];\n\n // Add the title\n outputLines.push(\n `# ${sourceType.charAt(0).toUpperCase() + sourceType.slice(1)} ${index}: ${source.title != null && source.title ? `\"${source.title}\"` : '(no title)'}`\n );\n outputLines.push(`\\nAnchor: \\\\ue202turn${turn}${sourceType}${index}`);\n outputLines.push(`URL: ${source.link}`);\n\n // Add optional fields\n if ('snippet' in source && source.snippet != null) {\n outputLines.push(`Summary: ${source.snippet}`);\n }\n\n if (source.date != null) {\n outputLines.push(`Date: ${source.date}`);\n }\n\n if (source.attribution != null) {\n outputLines.push(`Source: ${source.attribution}`);\n }\n\n // Add highlight section or empty line\n if ((source.highlights?.length ?? 0) > 0) {\n outputLines.push(...addHighlightSection());\n } else {\n outputLines.push('');\n }\n\n // Process highlights if they exist\n (source.highlights ?? [])\n .filter((h) => h.text.trim().length > 0)\n .forEach((h, hIndex) => {\n outputLines.push(\n `### Highlight ${hIndex + 1} [Relevance: ${h.score.toFixed(2)}]`\n );\n outputLines.push('');\n outputLines.push('```text');\n outputLines.push(h.text.trim());\n outputLines.push('```');\n outputLines.push('');\n\n if (h.references != null && h.references.length) {\n let hasHeader = false;\n const refLines: string[] = [];\n\n for (let j = 0; j < h.references.length; j++) {\n const ref = h.references[j];\n if (ref.reference.originalUrl.includes('mailto:')) {\n continue;\n }\n references.push({\n type: ref.type,\n link: ref.reference.originalUrl,\n attribution: getDomainName(ref.reference.originalUrl),\n title: (\n ((ref.reference.title ?? '') || ref.reference.text) ??\n ''\n ).split('\\n')[0],\n });\n\n if (ref.type !== 'link') {\n continue;\n }\n\n if (fileExtRegex.test(ref.reference.originalUrl)) {\n continue;\n }\n\n if (!hasHeader) {\n refLines.push('Core References:');\n hasHeader = true;\n }\n\n refLines.push(\n `- ${ref.type}#${ref.originalIndex + 1}: ${ref.reference.originalUrl}`\n );\n refLines.push(\n `\\t- Anchor: \\\\ue202turn${turn}ref${references.length - 1}`\n );\n }\n\n if (hasHeader) {\n outputLines.push(...refLines);\n outputLines.push('');\n }\n }\n\n if (hIndex < (source.highlights?.length ?? 0) - 1) {\n outputLines.push('---');\n outputLines.push('');\n }\n });\n\n outputLines.push('');\n return outputLines.join('\\n');\n}\n\nexport function formatResultsForLLM(\n turn: number,\n results: t.SearchResultData\n): { output: string; references: t.ResultReference[] } {\n /** Array to collect all output lines */\n const outputLines: string[] = [];\n\n const addSection = (title: string): void => {\n outputLines.push('');\n outputLines.push(`=== ${title} ===`);\n outputLines.push('');\n };\n\n const references: t.ResultReference[] = [];\n\n // Organic (web) results\n if (results.organic?.length != null && results.organic.length > 0) {\n addSection(`Web Results, Turn ${turn}`);\n for (let i = 0; i < results.organic.length; i++) {\n const r = results.organic[i];\n outputLines.push(formatSource(r, i, turn, 'search', references));\n delete results.organic[i].highlights;\n }\n }\n\n // Top stories (news)\n const topStories = results.topStories ?? [];\n if (topStories.length) {\n addSection('News Results');\n for (let i = 0; i < topStories.length; i++) {\n const r = topStories[i];\n outputLines.push(formatSource(r, i, turn, 'news', references));\n if (results.topStories?.[i]?.highlights) {\n delete results.topStories[i].highlights;\n }\n }\n }\n\n // // Images\n // const images = results.images ?? [];\n // if (images.length) {\n // addSection('Image Results');\n // const imageLines = images.map((img, i) => [\n // `Anchor: \\ue202turn0image${i}`,\n // `Title: ${img.title ?? '(no title)'}`,\n // `Image URL: ${img.imageUrl}`,\n // ''\n // ].join('\\n'));\n // outputLines.push(imageLines.join('\\n'));\n // }\n\n // Knowledge Graph\n if (results.knowledgeGraph != null) {\n addSection('Knowledge Graph');\n const kgLines = [\n `**Title:** ${results.knowledgeGraph.title ?? '(no title)'}`,\n results.knowledgeGraph.type != null\n ? `**Type:** ${results.knowledgeGraph.type}`\n : '',\n results.knowledgeGraph.description != null\n ? `**Description:** ${results.knowledgeGraph.description}`\n : '',\n results.knowledgeGraph.descriptionSource != null\n ? `**Description Source:** ${results.knowledgeGraph.descriptionSource}`\n : '',\n results.knowledgeGraph.descriptionLink != null\n ? `**Description Link:** ${results.knowledgeGraph.descriptionLink}`\n : '',\n results.knowledgeGraph.imageUrl != null\n ? `**Image URL:** ${results.knowledgeGraph.imageUrl}`\n : '',\n results.knowledgeGraph.website != null\n ? `**Website:** ${results.knowledgeGraph.website}`\n : '',\n results.knowledgeGraph.attributes != null\n ? `**Attributes:**\\n\\`\\`\\`json\\n${JSON.stringify(\n results.knowledgeGraph.attributes,\n null,\n 2\n )}\\n\\`\\`\\``\n : '',\n '',\n ].filter(Boolean);\n\n outputLines.push(kgLines.join('\\n\\n'));\n }\n\n // Answer Box\n if (results.answerBox != null) {\n addSection('Answer Box');\n const abLines = [\n results.answerBox.title != null\n ? `**Title:** ${results.answerBox.title}`\n : '',\n results.answerBox.snippet != null\n ? `**Snippet:** ${results.answerBox.snippet}`\n : '',\n results.answerBox.snippetHighlighted != null\n ? `**Snippet Highlighted:** ${results.answerBox.snippetHighlighted\n .map((s) => `\\`${s}\\``)\n .join(' ')}`\n : '',\n results.answerBox.link != null\n ? `**Link:** ${results.answerBox.link}`\n : '',\n '',\n ].filter(Boolean);\n\n outputLines.push(abLines.join('\\n\\n'));\n }\n\n // People also ask\n const peopleAlsoAsk = results.peopleAlsoAsk ?? [];\n if (peopleAlsoAsk.length) {\n addSection('People Also Ask');\n\n const paaLines: string[] = [];\n peopleAlsoAsk.forEach((p, i) => {\n const questionLines = [\n `### Question ${i + 1}:`,\n `\"${p.question}\"`,\n `${p.snippet != null && p.snippet ? `Snippet: ${p.snippet}` : ''}`,\n `${p.title != null && p.title ? `Title: ${p.title}` : ''}`,\n `${p.link != null && p.link ? `Link: ${p.link}` : ''}`,\n '',\n ].filter(Boolean);\n\n paaLines.push(questionLines.join('\\n\\n'));\n });\n\n outputLines.push(paaLines.join(''));\n }\n\n return {\n output: outputLines.join('\\n').trim(),\n references,\n };\n}\n"],"names":["getDomainName","fileExtRegex"],"mappings":";;;;AAGA,SAAS,mBAAmB,GAAA;AAC1B,IAAA,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC;AAChC;AAEA;AACA,SAAS,YAAY,CACnB,MAAqB,EACrB,KAAa,EACb,IAAY,EACZ,UAA6B,EAC7B,UAA+B,EAAA;;IAG/B,MAAM,WAAW,GAAa,EAAE;;IAGhC,WAAW,CAAC,IAAI,CACd,CAAA,EAAA,EAAK,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA,CAAA,EAAI,KAAK,CAAA,EAAA,EAAK,MAAM,CAAC,KAAK,IAAI,IAAI,IAAI,MAAM,CAAC,KAAK,GAAG,IAAI,MAAM,CAAC,KAAK,CAAG,CAAA,CAAA,GAAG,YAAY,CAAE,CAAA,CACvJ;IACD,WAAW,CAAC,IAAI,CAAC,CAAwB,qBAAA,EAAA,IAAI,CAAG,EAAA,UAAU,CAAG,EAAA,KAAK,CAAE,CAAA,CAAC;IACrE,WAAW,CAAC,IAAI,CAAC,CAA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C,KAAK,IAAI,IAAI,IAAI,CAAC,CAAC,KAAK,GAAG,CAAA,OAAA,EAAU,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,CAAE,CAAA;gBAC1D,CAAG,EAAA,CAAC,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC,IAAI,GAAG,CAAA,MAAA,EAAS,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,CAAE,CAAA;gBACtD,EAAE;AACH,aAAA,CAAC,MAAM,CAAC,OAAO,CAAC;YAEjB,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC3C,SAAC,CAAC;QAEF,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;;IAGrC,OAAO;QACL,MAAM,EAAE,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE;QACrC,UAAU;KACX;AACH;;;;"}
@@ -0,0 +1,245 @@
1
+ 'use strict';
2
+
3
+ // 2. Pre-compile all regular expressions (only do this once)
4
+ // Group patterns by priority for early returns
5
+ const priorityPatterns = [
6
+ // High priority patterns (structural)
7
+ [
8
+ { regex: /\n\n/g }, // Double newline (paragraph break)
9
+ { regex: /\n/g }, // Single newline
10
+ { regex: /={3,}\s*\n|-{3,}\s*\n/g }, // Section separators
11
+ ],
12
+ // Medium priority (semantic)
13
+ [
14
+ { regex: /[.!?][")\]]?\s/g }, // End of sentence
15
+ { regex: /;\s/g }, // Semicolon
16
+ { regex: /:\s/g }, // Colon
17
+ ],
18
+ // Low priority (any breaks)
19
+ [
20
+ { regex: /,\s/g }, // Comma
21
+ { regex: /\s-\s/g }, // Dash surrounded by spaces
22
+ { regex: /\s/g }, // Any space
23
+ ],
24
+ ];
25
+ function findFirstMatch(text, regex) {
26
+ // Reset regex
27
+ regex.lastIndex = 0;
28
+ // For very long texts, try chunking
29
+ if (text.length > 10000) {
30
+ const chunkSize = 2000;
31
+ let position = 0;
32
+ while (position < text.length) {
33
+ const chunk = text.substring(position, position + chunkSize);
34
+ regex.lastIndex = 0;
35
+ const match = regex.exec(chunk);
36
+ if (match) {
37
+ return position + match.index;
38
+ }
39
+ // Move to next chunk with some overlap
40
+ position += chunkSize - 100;
41
+ if (position >= text.length)
42
+ break;
43
+ }
44
+ return -1;
45
+ }
46
+ // For shorter texts, normal regex search
47
+ const match = regex.exec(text);
48
+ return match ? match.index : -1;
49
+ }
50
+ // 3. Optimized boundary finding functions
51
+ function findLastMatch(text, regex) {
52
+ // Reset regex state
53
+ regex.lastIndex = 0;
54
+ let lastIndex = -1;
55
+ let lastLength = 0;
56
+ let match;
57
+ // For very long texts, use a different approach to avoid regex engine slowdowns
58
+ if (text.length > 10000) {
59
+ // Try dividing the text into chunks for faster processing
60
+ const chunkSize = 2000;
61
+ let startPosition = Math.max(0, text.length - chunkSize);
62
+ while (startPosition >= 0) {
63
+ const chunk = text.substring(startPosition, startPosition + chunkSize);
64
+ regex.lastIndex = 0;
65
+ let chunkLastIndex = -1;
66
+ let chunkLastLength = 0;
67
+ while ((match = regex.exec(chunk)) !== null) {
68
+ chunkLastIndex = match.index;
69
+ chunkLastLength = match[0].length;
70
+ }
71
+ if (chunkLastIndex !== -1) {
72
+ return startPosition + chunkLastIndex + chunkLastLength;
73
+ }
74
+ // Move to previous chunk with some overlap
75
+ startPosition = Math.max(0, startPosition - chunkSize + 100) - 1;
76
+ if (startPosition <= 0)
77
+ break;
78
+ }
79
+ return -1;
80
+ }
81
+ // For shorter texts, normal regex search
82
+ while ((match = regex.exec(text)) !== null) {
83
+ lastIndex = match.index;
84
+ lastLength = match[0].length;
85
+ }
86
+ return lastIndex === -1 ? -1 : lastIndex + lastLength;
87
+ }
88
+ // 4. Find the best boundary with priority groups
89
+ function findBestBoundary(text, direction = 'backward') {
90
+ if (!text || text.length === 0)
91
+ return 0;
92
+ // Try each priority group
93
+ for (const patternGroup of priorityPatterns) {
94
+ for (const pattern of patternGroup) {
95
+ const position = direction === 'backward'
96
+ ? findLastMatch(text, pattern.regex)
97
+ : findFirstMatch(text, pattern.regex);
98
+ if (position !== -1) {
99
+ return position;
100
+ }
101
+ }
102
+ }
103
+ // No match found, use character boundary
104
+ return direction === 'backward' ? text.length : 0;
105
+ }
106
+ /**
107
+ * Tracks references used in a highlight without changing their numbers
108
+ */
109
+ function trackReferencesInHighlight(text, sourceResult // Source containing the original references
110
+ ) {
111
+ // Track used references
112
+ const references = [];
113
+ if (!text || text.length === 0 || !text.includes('#')) {
114
+ return { references }; // Early return
115
+ }
116
+ // Quick check for reference markers
117
+ if (!text.includes('link#') &&
118
+ !text.includes('image#') &&
119
+ !text.includes('video#')) {
120
+ return { references };
121
+ }
122
+ // Get references from the source if available
123
+ const sourceRefs = sourceResult.references || {
124
+ links: [],
125
+ images: [],
126
+ videos: [],
127
+ };
128
+ // Find references but don't modify text
129
+ const refRegex = /\((link|image|video)#(\d+)(?:\s+"([^"]*)")?\)/g;
130
+ let match;
131
+ while ((match = refRegex.exec(text)) !== null) {
132
+ const [, type, indexStr] = match;
133
+ const originalIndex = parseInt(indexStr, 10) - 1; // Convert to 0-based
134
+ // Get the source array for this type
135
+ const refType = type;
136
+ const sourceArray = sourceRefs[`${refType}s`];
137
+ // Skip if invalid reference
138
+ if (!sourceArray ||
139
+ originalIndex < 0 ||
140
+ originalIndex >= sourceArray.length) {
141
+ continue; // Skip invalid references
142
+ }
143
+ // Get original reference
144
+ const reference = sourceArray[originalIndex];
145
+ // Track if not already tracked
146
+ const alreadyTracked = references.some((ref) => ref.type === refType && ref.originalIndex === originalIndex);
147
+ if (!alreadyTracked) {
148
+ references.push({
149
+ type: refType,
150
+ originalIndex,
151
+ reference,
152
+ });
153
+ }
154
+ }
155
+ return { references };
156
+ }
157
+ /**
158
+ * Expand highlights in search results using smart boundary detection.
159
+ *
160
+ * This implementation finds natural text boundaries like paragraphs, sentences,
161
+ * and phrases to provide context while maintaining readability.
162
+ *
163
+ * @param searchResults - Search results object
164
+ * @param mainExpandBy - Primary expansion size on each side (default: 300)
165
+ * @param separatorExpandBy - Additional range to look for separators (default: 150)
166
+ * @returns Copy of search results with expanded highlights and tracked references
167
+ */
168
+ function expandHighlights(searchResults, mainExpandBy = 300, separatorExpandBy = 150) {
169
+ // Avoid deep copy - only copy what we modify
170
+ const resultCopy = { ...searchResults };
171
+ if (resultCopy.organic)
172
+ resultCopy.organic = [...resultCopy.organic];
173
+ if (resultCopy.topStories)
174
+ resultCopy.topStories = [...resultCopy.topStories];
175
+ // Process the results efficiently
176
+ const processResultTypes = ['organic', 'topStories'];
177
+ for (const resultType of processResultTypes) {
178
+ if (!resultCopy[resultType])
179
+ continue;
180
+ // Map results to new array with modified highlights
181
+ resultCopy[resultType] = resultCopy[resultType]?.map((result) => {
182
+ if (result.content == null ||
183
+ result.content === '' ||
184
+ !result.highlights ||
185
+ result.highlights.length === 0) {
186
+ return result; // No modification needed
187
+ }
188
+ // Create a shallow copy with expanded highlights
189
+ const resultCopy = { ...result };
190
+ const content = result.content;
191
+ const highlights = [];
192
+ // Process each highlight
193
+ for (const highlight of result.highlights) {
194
+ const { references } = trackReferencesInHighlight(highlight.text, result);
195
+ let startPos = content.indexOf(highlight.text);
196
+ let highlightLen = highlight.text.length;
197
+ if (startPos === -1) {
198
+ // Try with stripped whitespace
199
+ const strippedHighlight = highlight.text.trim();
200
+ startPos = content.indexOf(strippedHighlight);
201
+ if (startPos === -1) {
202
+ highlights.push({
203
+ text: highlight.text,
204
+ score: highlight.score,
205
+ references,
206
+ });
207
+ continue;
208
+ }
209
+ highlightLen = strippedHighlight.length;
210
+ }
211
+ // Calculate boundaries
212
+ const mainStart = Math.max(0, startPos - mainExpandBy);
213
+ const mainEnd = Math.min(content.length, startPos + highlightLen + mainExpandBy);
214
+ const separatorStart = Math.max(0, mainStart - separatorExpandBy);
215
+ const separatorEnd = Math.min(content.length, mainEnd + separatorExpandBy);
216
+ // Extract text segments
217
+ const headText = content.substring(separatorStart, mainStart);
218
+ const tailText = content.substring(mainEnd, separatorEnd);
219
+ // Find natural boundaries
220
+ const bestHeadBoundary = findBestBoundary(headText, 'backward');
221
+ const bestTailBoundary = findBestBoundary(tailText, 'forward');
222
+ // Calculate final positions
223
+ const finalStart = separatorStart + bestHeadBoundary;
224
+ const finalEnd = mainEnd + bestTailBoundary;
225
+ // Extract the expanded highlight
226
+ const expandedHighlightText = content
227
+ .substring(finalStart, finalEnd)
228
+ .trim();
229
+ highlights.push({
230
+ text: expandedHighlightText,
231
+ score: highlight.score,
232
+ references,
233
+ });
234
+ }
235
+ resultCopy.highlights = highlights;
236
+ delete resultCopy.content;
237
+ delete resultCopy.references;
238
+ return resultCopy;
239
+ });
240
+ }
241
+ return resultCopy;
242
+ }
243
+
244
+ exports.expandHighlights = expandHighlights;
245
+ //# sourceMappingURL=highlights.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"highlights.cjs","sources":["../../../../src/tools/search/highlights.ts"],"sourcesContent":["import type * as t from './types';\n\n// 2. Pre-compile all regular expressions (only do this once)\n// Group patterns by priority for early returns\nconst priorityPatterns = [\n // High priority patterns (structural)\n [\n { regex: /\\n\\n/g }, // Double newline (paragraph break)\n { regex: /\\n/g }, // Single newline\n { regex: /={3,}\\s*\\n|-{3,}\\s*\\n/g }, // Section separators\n ],\n // Medium priority (semantic)\n [\n { regex: /[.!?][\")\\]]?\\s/g }, // End of sentence\n { regex: /;\\s/g }, // Semicolon\n { regex: /:\\s/g }, // Colon\n ],\n // Low priority (any breaks)\n [\n { regex: /,\\s/g }, // Comma\n { regex: /\\s-\\s/g }, // Dash surrounded by spaces\n { regex: /\\s/g }, // Any space\n ],\n];\n\nfunction findFirstMatch(text: string, regex: RegExp): number {\n // Reset regex\n regex.lastIndex = 0;\n\n // For very long texts, try chunking\n if (text.length > 10000) {\n const chunkSize = 2000;\n let position = 0;\n\n while (position < text.length) {\n const chunk = text.substring(position, position + chunkSize);\n regex.lastIndex = 0;\n\n const match = regex.exec(chunk);\n if (match) {\n return position + match.index;\n }\n\n // Move to next chunk with some overlap\n position += chunkSize - 100;\n if (position >= text.length) break;\n }\n return -1;\n }\n\n // For shorter texts, normal regex search\n const match = regex.exec(text);\n return match ? match.index : -1;\n}\n\n// 3. Optimized boundary finding functions\nfunction findLastMatch(text: string, regex: RegExp): number {\n // Reset regex state\n regex.lastIndex = 0;\n\n let lastIndex = -1;\n let lastLength = 0;\n let match;\n\n // For very long texts, use a different approach to avoid regex engine slowdowns\n if (text.length > 10000) {\n // Try dividing the text into chunks for faster processing\n const chunkSize = 2000;\n let startPosition = Math.max(0, text.length - chunkSize);\n\n while (startPosition >= 0) {\n const chunk = text.substring(startPosition, startPosition + chunkSize);\n regex.lastIndex = 0;\n\n let chunkLastIndex = -1;\n let chunkLastLength = 0;\n\n while ((match = regex.exec(chunk)) !== null) {\n chunkLastIndex = match.index;\n chunkLastLength = match[0].length;\n }\n\n if (chunkLastIndex !== -1) {\n return startPosition + chunkLastIndex + chunkLastLength;\n }\n\n // Move to previous chunk with some overlap\n startPosition = Math.max(0, startPosition - chunkSize + 100) - 1;\n if (startPosition <= 0) break;\n }\n return -1;\n }\n\n // For shorter texts, normal regex search\n while ((match = regex.exec(text)) !== null) {\n lastIndex = match.index;\n lastLength = match[0].length;\n }\n\n return lastIndex === -1 ? -1 : lastIndex + lastLength;\n}\n\n// 4. Find the best boundary with priority groups\nfunction findBestBoundary(text: string, direction = 'backward'): number {\n if (!text || text.length === 0) return 0;\n\n // Try each priority group\n for (const patternGroup of priorityPatterns) {\n for (const pattern of patternGroup) {\n const position =\n direction === 'backward'\n ? findLastMatch(text, pattern.regex)\n : findFirstMatch(text, pattern.regex);\n\n if (position !== -1) {\n return position;\n }\n }\n }\n\n // No match found, use character boundary\n return direction === 'backward' ? text.length : 0;\n}\n\n/**\n * Tracks references used in a highlight without changing their numbers\n */\nfunction trackReferencesInHighlight(\n text: string,\n sourceResult: t.ValidSource // Source containing the original references\n): {\n references: {\n type: 'link' | 'image' | 'video';\n originalIndex: number;\n reference: t.MediaReference; // Original reference object\n }[];\n} {\n // Track used references\n const references: {\n type: 'link' | 'image' | 'video';\n originalIndex: number;\n reference: t.MediaReference;\n }[] = [];\n\n if (!text || text.length === 0 || !text.includes('#')) {\n return { references }; // Early return\n }\n\n // Quick check for reference markers\n if (\n !text.includes('link#') &&\n !text.includes('image#') &&\n !text.includes('video#')\n ) {\n return { references };\n }\n\n // Get references from the source if available\n const sourceRefs = sourceResult.references || {\n links: [],\n images: [],\n videos: [],\n };\n\n // Find references but don't modify text\n const refRegex = /\\((link|image|video)#(\\d+)(?:\\s+\"([^\"]*)\")?\\)/g;\n let match;\n\n while ((match = refRegex.exec(text)) !== null) {\n const [, type, indexStr] = match;\n const originalIndex = parseInt(indexStr, 10) - 1; // Convert to 0-based\n\n // Get the source array for this type\n const refType = type as 'link' | 'image' | 'video';\n const sourceArray = sourceRefs[`${refType}s`] as\n | t.MediaReference[]\n | undefined;\n\n // Skip if invalid reference\n if (\n !sourceArray ||\n originalIndex < 0 ||\n originalIndex >= sourceArray.length\n ) {\n continue; // Skip invalid references\n }\n\n // Get original reference\n const reference = sourceArray[originalIndex];\n\n // Track if not already tracked\n const alreadyTracked = references.some(\n (ref) => ref.type === refType && ref.originalIndex === originalIndex\n );\n\n if (!alreadyTracked) {\n references.push({\n type: refType,\n originalIndex,\n reference,\n });\n }\n }\n\n return { references };\n}\n\n/**\n * Expand highlights in search results using smart boundary detection.\n *\n * This implementation finds natural text boundaries like paragraphs, sentences,\n * and phrases to provide context while maintaining readability.\n *\n * @param searchResults - Search results object\n * @param mainExpandBy - Primary expansion size on each side (default: 300)\n * @param separatorExpandBy - Additional range to look for separators (default: 150)\n * @returns Copy of search results with expanded highlights and tracked references\n */\nexport function expandHighlights(\n searchResults: t.SearchResultData,\n mainExpandBy = 300,\n separatorExpandBy = 150\n): t.SearchResultData {\n // Avoid deep copy - only copy what we modify\n const resultCopy = { ...searchResults };\n if (resultCopy.organic) resultCopy.organic = [...resultCopy.organic];\n if (resultCopy.topStories) resultCopy.topStories = [...resultCopy.topStories];\n\n // Process the results efficiently\n const processResultTypes = ['organic', 'topStories'] as const;\n\n for (const resultType of processResultTypes) {\n if (!resultCopy[resultType as 'organic' | 'topStories']) continue;\n\n // Map results to new array with modified highlights\n resultCopy[resultType] = resultCopy[resultType]?.map((result) => {\n if (\n result.content == null ||\n result.content === '' ||\n !result.highlights ||\n result.highlights.length === 0\n ) {\n return result; // No modification needed\n }\n\n // Create a shallow copy with expanded highlights\n const resultCopy = { ...result };\n const content = result.content;\n const highlights = [];\n // Process each highlight\n for (const highlight of result.highlights) {\n const { references } = trackReferencesInHighlight(\n highlight.text,\n result\n );\n\n let startPos = content.indexOf(highlight.text);\n let highlightLen = highlight.text.length;\n\n if (startPos === -1) {\n // Try with stripped whitespace\n const strippedHighlight = highlight.text.trim();\n startPos = content.indexOf(strippedHighlight);\n\n if (startPos === -1) {\n highlights.push({\n text: highlight.text,\n score: highlight.score,\n references,\n });\n continue;\n }\n highlightLen = strippedHighlight.length;\n }\n\n // Calculate boundaries\n const mainStart = Math.max(0, startPos - mainExpandBy);\n const mainEnd = Math.min(\n content.length,\n startPos + highlightLen + mainExpandBy\n );\n\n const separatorStart = Math.max(0, mainStart - separatorExpandBy);\n const separatorEnd = Math.min(\n content.length,\n mainEnd + separatorExpandBy\n );\n\n // Extract text segments\n const headText = content.substring(separatorStart, mainStart);\n const tailText = content.substring(mainEnd, separatorEnd);\n\n // Find natural boundaries\n const bestHeadBoundary = findBestBoundary(headText, 'backward');\n const bestTailBoundary = findBestBoundary(tailText, 'forward');\n\n // Calculate final positions\n const finalStart = separatorStart + bestHeadBoundary;\n const finalEnd = mainEnd + bestTailBoundary;\n\n // Extract the expanded highlight\n const expandedHighlightText = content\n .substring(finalStart, finalEnd)\n .trim();\n highlights.push({\n text: expandedHighlightText,\n score: highlight.score,\n references,\n });\n }\n\n resultCopy.highlights = highlights;\n delete resultCopy.content;\n delete resultCopy.references;\n return resultCopy;\n });\n }\n\n return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,EAAE,qBAAqB;oBAC3B,KAAK,EAAE,SAAS,CAAC,KAAK;oBACtB,UAAU;AACX,iBAAA,CAAC;;AAGJ,YAAA,UAAU,CAAC,UAAU,GAAG,UAAU;YAClC,OAAO,UAAU,CAAC,OAAO;YACzB,OAAO,UAAU,CAAC,UAAU;AAC5B,YAAA,OAAO,UAAU;AACnB,SAAC,CAAC;;AAGJ,IAAA,OAAO,UAAU;AACnB;;;;"}
@@ -0,0 +1,194 @@
1
+ 'use strict';
2
+
3
+ var axios = require('axios');
4
+ var utils = require('./utils.cjs');
5
+
6
+ class BaseReranker {
7
+ apiKey;
8
+ logger;
9
+ constructor(logger) {
10
+ // Each specific reranker will set its API key
11
+ this.logger = logger || utils.createDefaultLogger();
12
+ }
13
+ getDefaultRanking(documents, topK) {
14
+ return documents
15
+ .slice(0, Math.min(topK, documents.length))
16
+ .map((doc) => ({ text: doc, score: 0 }));
17
+ }
18
+ logDocumentSamples(documents) {
19
+ this.logger.debug('Sample documents being sent to API:');
20
+ for (let i = 0; i < Math.min(3, documents.length); i++) {
21
+ this.logger.debug(`Document ${i}: ${documents[i].substring(0, 100)}...`);
22
+ }
23
+ }
24
+ }
25
+ class JinaReranker extends BaseReranker {
26
+ constructor({ apiKey = process.env.JINA_API_KEY, logger, }) {
27
+ super(logger);
28
+ this.apiKey = apiKey;
29
+ }
30
+ async rerank(query, documents, topK = 5) {
31
+ this.logger.debug(`Reranking ${documents.length} documents with Jina`);
32
+ try {
33
+ if (this.apiKey == null || this.apiKey === '') {
34
+ this.logger.warn('JINA_API_KEY is not set. Using default ranking.');
35
+ return this.getDefaultRanking(documents, topK);
36
+ }
37
+ this.logDocumentSamples(documents);
38
+ const requestData = {
39
+ model: 'jina-reranker-v2-base-multilingual',
40
+ query: query,
41
+ top_n: topK,
42
+ documents: documents,
43
+ return_documents: true,
44
+ };
45
+ const response = await axios.post('https://api.jina.ai/v1/rerank', requestData, {
46
+ headers: {
47
+ 'Content-Type': 'application/json',
48
+ Authorization: `Bearer ${this.apiKey}`,
49
+ },
50
+ });
51
+ // Log the response data structure
52
+ this.logger.debug('Jina API response structure:');
53
+ this.logger.debug('Model:', response.data?.model);
54
+ this.logger.debug('Usage:', response.data?.usage);
55
+ this.logger.debug('Results count:', response.data?.results.length);
56
+ // Log a sample of the results
57
+ if ((response.data?.results.length ?? 0) > 0) {
58
+ this.logger.debug('Sample result:', JSON.stringify(response.data?.results[0], null, 2));
59
+ }
60
+ if (response.data && response.data.results.length) {
61
+ return response.data.results.map((result) => {
62
+ const docIndex = result.index;
63
+ const score = result.relevance_score;
64
+ let text = '';
65
+ // If return_documents is true, the document field will be present
66
+ if (result.document != null) {
67
+ const doc = result.document;
68
+ if (typeof doc === 'object' && 'text' in doc) {
69
+ text = doc.text;
70
+ }
71
+ else if (typeof doc === 'string') {
72
+ text = doc;
73
+ }
74
+ }
75
+ else {
76
+ // Otherwise, use the index to get the document
77
+ text = documents[docIndex];
78
+ }
79
+ return { text, score };
80
+ });
81
+ }
82
+ else {
83
+ this.logger.warn('Unexpected response format from Jina API. Using default ranking.');
84
+ return this.getDefaultRanking(documents, topK);
85
+ }
86
+ }
87
+ catch (error) {
88
+ this.logger.error('Error using Jina reranker:', error);
89
+ // Fallback to default ranking on error
90
+ return this.getDefaultRanking(documents, topK);
91
+ }
92
+ }
93
+ }
94
+ class CohereReranker extends BaseReranker {
95
+ constructor({ apiKey = process.env.COHERE_API_KEY, logger, }) {
96
+ super(logger);
97
+ this.apiKey = apiKey;
98
+ }
99
+ async rerank(query, documents, topK = 5) {
100
+ this.logger.debug(`Reranking ${documents.length} documents with Cohere`);
101
+ try {
102
+ if (this.apiKey == null || this.apiKey === '') {
103
+ this.logger.warn('COHERE_API_KEY is not set. Using default ranking.');
104
+ return this.getDefaultRanking(documents, topK);
105
+ }
106
+ this.logDocumentSamples(documents);
107
+ const requestData = {
108
+ model: 'rerank-v3.5',
109
+ query: query,
110
+ top_n: topK,
111
+ documents: documents,
112
+ };
113
+ const response = await axios.post('https://api.cohere.com/v2/rerank', requestData, {
114
+ headers: {
115
+ 'Content-Type': 'application/json',
116
+ Authorization: `Bearer ${this.apiKey}`,
117
+ },
118
+ });
119
+ // Log the response data structure
120
+ this.logger.debug('Cohere API response structure:');
121
+ this.logger.debug('ID:', response.data?.id);
122
+ this.logger.debug('Meta:', response.data?.meta);
123
+ this.logger.debug('Results count:', response.data?.results.length);
124
+ // Log a sample of the results
125
+ if ((response.data?.results.length ?? 0) > 0) {
126
+ this.logger.debug('Sample result:', JSON.stringify(response.data?.results[0], null, 2));
127
+ }
128
+ if (response.data && response.data.results.length) {
129
+ return response.data.results.map((result) => {
130
+ const docIndex = result.index;
131
+ const score = result.relevance_score;
132
+ const text = documents[docIndex];
133
+ return { text, score };
134
+ });
135
+ }
136
+ else {
137
+ this.logger.warn('Unexpected response format from Cohere API. Using default ranking.');
138
+ return this.getDefaultRanking(documents, topK);
139
+ }
140
+ }
141
+ catch (error) {
142
+ this.logger.error('Error using Cohere reranker:', error);
143
+ // Fallback to default ranking on error
144
+ return this.getDefaultRanking(documents, topK);
145
+ }
146
+ }
147
+ }
148
+ class InfinityReranker extends BaseReranker {
149
+ constructor(logger) {
150
+ super(logger);
151
+ // No API key needed for the placeholder implementation
152
+ }
153
+ async rerank(query, documents, topK = 5) {
154
+ this.logger.debug(`Reranking ${documents.length} documents with Infinity (placeholder)`);
155
+ // This would be replaced with actual Infinity reranker implementation
156
+ return this.getDefaultRanking(documents, topK);
157
+ }
158
+ }
159
+ /**
160
+ * Creates the appropriate reranker based on type and configuration
161
+ */
162
+ const createReranker = (config) => {
163
+ const { rerankerType, jinaApiKey, cohereApiKey, logger } = config;
164
+ // Create a default logger if none is provided
165
+ const defaultLogger = logger || utils.createDefaultLogger();
166
+ switch (rerankerType.toLowerCase()) {
167
+ case 'jina':
168
+ return new JinaReranker({ apiKey: jinaApiKey, logger: defaultLogger });
169
+ case 'cohere':
170
+ return new CohereReranker({
171
+ apiKey: cohereApiKey,
172
+ logger: defaultLogger,
173
+ });
174
+ case 'infinity':
175
+ return new InfinityReranker(defaultLogger);
176
+ case 'none':
177
+ defaultLogger.debug('Skipping reranking as reranker is set to "none"');
178
+ return undefined;
179
+ default:
180
+ defaultLogger.warn(`Unknown reranker type: ${rerankerType}. Defaulting to InfinityReranker.`);
181
+ return new JinaReranker({ apiKey: jinaApiKey, logger: defaultLogger });
182
+ }
183
+ };
184
+ // Example usage:
185
+ // const jinaReranker = new JinaReranker();
186
+ // const cohereReranker = new CohereReranker();
187
+ // const infinityReranker = new InfinityReranker();
188
+
189
+ exports.BaseReranker = BaseReranker;
190
+ exports.CohereReranker = CohereReranker;
191
+ exports.InfinityReranker = InfinityReranker;
192
+ exports.JinaReranker = JinaReranker;
193
+ exports.createReranker = createReranker;
194
+ //# sourceMappingURL=rerankers.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rerankers.cjs","sources":["../../../../src/tools/search/rerankers.ts"],"sourcesContent":["import axios from 'axios';\nimport type * as t from './types';\nimport { createDefaultLogger } from './utils';\n\nexport abstract class BaseReranker {\n protected apiKey: string | undefined;\n protected logger: t.Logger;\n\n constructor(logger?: t.Logger) {\n // Each specific reranker will set its API key\n this.logger = logger || createDefaultLogger();\n }\n\n abstract rerank(\n query: string,\n documents: string[],\n topK?: number\n ): Promise<t.Highlight[]>;\n\n protected getDefaultRanking(\n documents: string[],\n topK: number\n ): t.Highlight[] {\n return documents\n .slice(0, Math.min(topK, documents.length))\n .map((doc) => ({ text: doc, score: 0 }));\n }\n\n protected logDocumentSamples(documents: string[]): void {\n this.logger.debug('Sample documents being sent to API:');\n for (let i = 0; i < Math.min(3, documents.length); i++) {\n this.logger.debug(`Document ${i}: ${documents[i].substring(0, 100)}...`);\n }\n }\n}\n\nexport class JinaReranker extends BaseReranker {\n constructor({\n apiKey = process.env.JINA_API_KEY,\n logger,\n }: {\n apiKey?: string;\n logger?: t.Logger;\n }) {\n super(logger);\n this.apiKey = apiKey;\n }\n\n async rerank(\n query: string,\n documents: string[],\n topK: number = 5\n ): Promise<t.Highlight[]> {\n this.logger.debug(`Reranking ${documents.length} documents with Jina`);\n\n try {\n if (this.apiKey == null || this.apiKey === '') {\n this.logger.warn('JINA_API_KEY is not set. Using default ranking.');\n return this.getDefaultRanking(documents, topK);\n }\n\n this.logDocumentSamples(documents);\n\n const requestData = {\n model: 'jina-reranker-v2-base-multilingual',\n query: query,\n top_n: topK,\n documents: documents,\n return_documents: true,\n };\n\n const response = await axios.post<t.JinaRerankerResponse | undefined>(\n 'https://api.jina.ai/v1/rerank',\n requestData,\n {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n },\n }\n );\n\n // Log the response data structure\n this.logger.debug('Jina API response structure:');\n this.logger.debug('Model:', response.data?.model);\n this.logger.debug('Usage:', response.data?.usage);\n this.logger.debug('Results count:', response.data?.results.length);\n\n // Log a sample of the results\n if ((response.data?.results.length ?? 0) > 0) {\n this.logger.debug(\n 'Sample result:',\n JSON.stringify(response.data?.results[0], null, 2)\n );\n }\n\n if (response.data && response.data.results.length) {\n return response.data.results.map((result) => {\n const docIndex = result.index;\n const score = result.relevance_score;\n let text = '';\n\n // If return_documents is true, the document field will be present\n if (result.document != null) {\n const doc = result.document;\n if (typeof doc === 'object' && 'text' in doc) {\n text = doc.text;\n } else if (typeof doc === 'string') {\n text = doc;\n }\n } else {\n // Otherwise, use the index to get the document\n text = documents[docIndex];\n }\n\n return { text, score };\n });\n } else {\n this.logger.warn(\n 'Unexpected response format from Jina API. Using default ranking.'\n );\n return this.getDefaultRanking(documents, topK);\n }\n } catch (error) {\n this.logger.error('Error using Jina reranker:', error);\n // Fallback to default ranking on error\n return this.getDefaultRanking(documents, topK);\n }\n }\n}\n\nexport class CohereReranker extends BaseReranker {\n constructor({\n apiKey = process.env.COHERE_API_KEY,\n logger,\n }: {\n apiKey?: string;\n logger?: t.Logger;\n }) {\n super(logger);\n this.apiKey = apiKey;\n }\n\n async rerank(\n query: string,\n documents: string[],\n topK: number = 5\n ): Promise<t.Highlight[]> {\n this.logger.debug(`Reranking ${documents.length} documents with Cohere`);\n\n try {\n if (this.apiKey == null || this.apiKey === '') {\n this.logger.warn('COHERE_API_KEY is not set. Using default ranking.');\n return this.getDefaultRanking(documents, topK);\n }\n\n this.logDocumentSamples(documents);\n\n const requestData = {\n model: 'rerank-v3.5',\n query: query,\n top_n: topK,\n documents: documents,\n };\n\n const response = await axios.post<t.CohereRerankerResponse | undefined>(\n 'https://api.cohere.com/v2/rerank',\n requestData,\n {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n },\n }\n );\n\n // Log the response data structure\n this.logger.debug('Cohere API response structure:');\n this.logger.debug('ID:', response.data?.id);\n this.logger.debug('Meta:', response.data?.meta);\n this.logger.debug('Results count:', response.data?.results.length);\n\n // Log a sample of the results\n if ((response.data?.results.length ?? 0) > 0) {\n this.logger.debug(\n 'Sample result:',\n JSON.stringify(response.data?.results[0], null, 2)\n );\n }\n\n if (response.data && response.data.results.length) {\n return response.data.results.map((result) => {\n const docIndex = result.index;\n const score = result.relevance_score;\n const text = documents[docIndex];\n return { text, score };\n });\n } else {\n this.logger.warn(\n 'Unexpected response format from Cohere API. Using default ranking.'\n );\n return this.getDefaultRanking(documents, topK);\n }\n } catch (error) {\n this.logger.error('Error using Cohere reranker:', error);\n // Fallback to default ranking on error\n return this.getDefaultRanking(documents, topK);\n }\n }\n}\n\nexport class InfinityReranker extends BaseReranker {\n constructor(logger?: t.Logger) {\n super(logger);\n // No API key needed for the placeholder implementation\n }\n\n async rerank(\n query: string,\n documents: string[],\n topK: number = 5\n ): Promise<t.Highlight[]> {\n this.logger.debug(\n `Reranking ${documents.length} documents with Infinity (placeholder)`\n );\n // This would be replaced with actual Infinity reranker implementation\n return this.getDefaultRanking(documents, topK);\n }\n}\n\n/**\n * Creates the appropriate reranker based on type and configuration\n */\nexport const createReranker = (config: {\n rerankerType: t.RerankerType;\n jinaApiKey?: string;\n cohereApiKey?: string;\n logger?: t.Logger;\n}): BaseReranker | undefined => {\n const { rerankerType, jinaApiKey, cohereApiKey, logger } = config;\n\n // Create a default logger if none is provided\n const defaultLogger = logger || createDefaultLogger();\n\n switch (rerankerType.toLowerCase()) {\n case 'jina':\n return new JinaReranker({ apiKey: jinaApiKey, logger: defaultLogger });\n case 'cohere':\n return new CohereReranker({\n apiKey: cohereApiKey,\n logger: defaultLogger,\n });\n case 'infinity':\n return new InfinityReranker(defaultLogger);\n case 'none':\n defaultLogger.debug('Skipping reranking as reranker is set to \"none\"');\n return undefined;\n default:\n defaultLogger.warn(\n `Unknown reranker type: ${rerankerType}. Defaulting to InfinityReranker.`\n );\n return new JinaReranker({ apiKey: jinaApiKey, logger: defaultLogger });\n }\n};\n\n// Example usage:\n// const jinaReranker = new JinaReranker();\n// const cohereReranker = new CohereReranker();\n// const infinityReranker = new InfinityReranker();\n"],"names":["createDefaultLogger"],"mappings":";;;;;MAIsB,YAAY,CAAA;AACtB,IAAA,MAAM;AACN,IAAA,MAAM;AAEhB,IAAA,WAAA,CAAY,MAAiB,EAAA;;AAE3B,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM,IAAIA,yBAAmB,EAAE;;IASrC,iBAAiB,CACzB,SAAmB,EACnB,IAAY,EAAA;AAEZ,QAAA,OAAO;AACJ,aAAA,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC;AACzC,aAAA,GAAG,CAAC,CAAC,GAAG,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;;AAGlC,IAAA,kBAAkB,CAAC,SAAmB,EAAA;AAC9C,QAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,qCAAqC,CAAC;QACxD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,SAAS,CAAC,MAAM,CAAC,EAA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YAAY;AACpB,gBAAA,MAAM,EAAE,aAAa;AACtB,aAAA,CAAC;AACJ,QAAA,KAAK,UAAU;AACb,YAAA,OAAO,IAAI,gBAAgB,CAAC,aAAa,CAAC;AAC5C,QAAA,KAAK,MAAM;AACT,YAAA,aAAa,CAAC,KAAK,CAAC,iDAAiD,CAAC;AACtE,YAAA,OAAO,SAAS;AAClB,QAAA;AACE,YAAA,aAAa,CAAC,IAAI,CAChB,0BAA0B,YAAY,CAAA,iCAAA,CAAmC,CAC1E;AACD,YAAA,OAAO,IAAI,YAAY,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC;;AAE1E;AAEA;AACA;AACA;AACA;;;;;;;;"}
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+
3
+ var zod = require('zod');
4
+
5
+ exports.DATE_RANGE = void 0;
6
+ (function (DATE_RANGE) {
7
+ DATE_RANGE["PAST_HOUR"] = "h";
8
+ DATE_RANGE["PAST_24_HOURS"] = "d";
9
+ DATE_RANGE["PAST_WEEK"] = "w";
10
+ DATE_RANGE["PAST_MONTH"] = "m";
11
+ DATE_RANGE["PAST_YEAR"] = "y";
12
+ })(exports.DATE_RANGE || (exports.DATE_RANGE = {}));
13
+ const DEFAULT_QUERY_DESCRIPTION = `
14
+ GUIDELINES:
15
+ - Start broad, then narrow: Begin with key concepts, then refine with specifics
16
+ - Think like sources: Use terminology experts would use in the field
17
+ - Consider perspective: Frame queries from different viewpoints for better results
18
+ - Quality over quantity: A precise 3-4 word query often beats lengthy sentences
19
+
20
+ TECHNIQUES (combine for power searches):
21
+ - EXACT PHRASES: Use quotes ("climate change report")
22
+ - EXCLUDE TERMS: Use minus to remove unwanted results (-wikipedia)
23
+ - SITE-SPECIFIC: Restrict to websites (site:edu research)
24
+ - FILETYPE: Find specific documents (filetype:pdf study)
25
+ - OR OPERATOR: Find alternatives (electric OR hybrid cars)
26
+ - DATE RANGE: Recent information (data after:2020)
27
+ - WILDCARDS: Use * for unknown terms (how to * bread)
28
+ - SPECIFIC QUESTIONS: Use who/what/when/where/why/how
29
+ - DOMAIN TERMS: Include technical terminology for specialized topics
30
+ - CONCISE TERMS: Prioritize keywords over sentences
31
+ `.trim();
32
+ const DEFAULT_COUNTRY_DESCRIPTION = `Country code to localize search results.
33
+ Use standard 2-letter country codes: "us", "uk", "ca", "de", "fr", "jp", "br", etc.
34
+ Provide this when the search should return results specific to a particular country.
35
+ Examples:
36
+ - "us" for United States (default)
37
+ - "de" for Germany
38
+ - "in" for India
39
+ `.trim();
40
+ const querySchema = zod.z.string().describe(DEFAULT_QUERY_DESCRIPTION);
41
+ const dateSchema = zod.z
42
+ .nativeEnum(exports.DATE_RANGE)
43
+ .optional()
44
+ .describe('Date range for search results.');
45
+ const countrySchema = zod.z
46
+ .string()
47
+ .optional()
48
+ .describe(DEFAULT_COUNTRY_DESCRIPTION);
49
+ const imagesSchema = zod.z
50
+ .boolean()
51
+ .optional()
52
+ .describe('Whether to also run an image search.');
53
+ const videosSchema = zod.z
54
+ .boolean()
55
+ .optional()
56
+ .describe('Whether to also run a video search.');
57
+ const newsSchema = zod.z
58
+ .boolean()
59
+ .optional()
60
+ .describe('Whether to also run a news search.');
61
+
62
+ exports.DEFAULT_COUNTRY_DESCRIPTION = DEFAULT_COUNTRY_DESCRIPTION;
63
+ exports.DEFAULT_QUERY_DESCRIPTION = DEFAULT_QUERY_DESCRIPTION;
64
+ exports.countrySchema = countrySchema;
65
+ exports.dateSchema = dateSchema;
66
+ exports.imagesSchema = imagesSchema;
67
+ exports.newsSchema = newsSchema;
68
+ exports.querySchema = querySchema;
69
+ exports.videosSchema = videosSchema;
70
+ //# sourceMappingURL=schema.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.cjs","sources":["../../../../src/tools/search/schema.ts"],"sourcesContent":["import { z } from 'zod';\n\nexport enum DATE_RANGE {\n PAST_HOUR = 'h',\n PAST_24_HOURS = 'd',\n PAST_WEEK = 'w',\n PAST_MONTH = 'm',\n PAST_YEAR = 'y',\n}\n\nexport const DEFAULT_QUERY_DESCRIPTION = `\nGUIDELINES:\n- Start broad, then narrow: Begin with key concepts, then refine with specifics\n- Think like sources: Use terminology experts would use in the field\n- Consider perspective: Frame queries from different viewpoints for better results\n- Quality over quantity: A precise 3-4 word query often beats lengthy sentences\n\nTECHNIQUES (combine for power searches):\n- EXACT PHRASES: Use quotes (\"climate change report\")\n- EXCLUDE TERMS: Use minus to remove unwanted results (-wikipedia)\n- SITE-SPECIFIC: Restrict to websites (site:edu research)\n- FILETYPE: Find specific documents (filetype:pdf study)\n- OR OPERATOR: Find alternatives (electric OR hybrid cars)\n- DATE RANGE: Recent information (data after:2020)\n- WILDCARDS: Use * for unknown terms (how to * bread)\n- SPECIFIC QUESTIONS: Use who/what/when/where/why/how\n- DOMAIN TERMS: Include technical terminology for specialized topics\n- CONCISE TERMS: Prioritize keywords over sentences\n`.trim();\n\nexport const DEFAULT_COUNTRY_DESCRIPTION =\n `Country code to localize search results.\nUse standard 2-letter country codes: \"us\", \"uk\", \"ca\", \"de\", \"fr\", \"jp\", \"br\", etc.\nProvide this when the search should return results specific to a particular country.\nExamples:\n- \"us\" for United States (default)\n- \"de\" for Germany\n- \"in\" for India\n`.trim();\n\nexport const querySchema = z.string().describe(DEFAULT_QUERY_DESCRIPTION);\nexport const dateSchema = z\n .nativeEnum(DATE_RANGE)\n .optional()\n .describe('Date range for search results.');\nexport const countrySchema = z\n .string()\n .optional()\n .describe(DEFAULT_COUNTRY_DESCRIPTION);\nexport const imagesSchema = z\n .boolean()\n .optional()\n .describe('Whether to also run an image search.');\n\nexport const videosSchema = z\n .boolean()\n .optional()\n .describe('Whether to also run a video search.');\n\nexport const newsSchema = z\n .boolean()\n .optional()\n .describe('Whether to also run a news search.');\n"],"names":["DATE_RANGE","z"],"mappings":";;;;AAEYA;AAAZ,CAAA,UAAY,UAAU,EAAA;AACpB,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,GAAe;AACf,IAAA,UAAA,CAAA,eAAA,CAAA,GAAA,GAAmB;AACnB,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,GAAe;AACf,IAAA,UAAA,CAAA,YAAA,CAAA,GAAA,GAAgB;AAChB,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,GAAe;AACjB,CAAC,EANWA,kBAAU,KAAVA,kBAAU,GAMrB,EAAA,CAAA,CAAA;AAEY,MAAA,yBAAyB,GAAG;;;;;;;;;;;;;;;;;;CAkBxC,CAAC,IAAI;AAEO,MAAA,2BAA2B,GACtC,CAAA;;;;;;;CAOD,CAAC,IAAI;AAEC,MAAM,WAAW,GAAGC,KAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,yBAAyB;AACjE,MAAM,UAAU,GAAGA;KACvB,UAAU,CAACD,kBAAU;AACrB,KAAA,QAAQ;KACR,QAAQ,CAAC,gCAAgC;AACrC,MAAM,aAAa,GAAGC;AAC1B,KAAA,MAAM;AACN,KAAA,QAAQ;KACR,QAAQ,CAAC,2BAA2B;AAChC,MAAM,YAAY,GAAGA;AACzB,KAAA,OAAO;AACP,KAAA,QAAQ;KACR,QAAQ,CAAC,sCAAsC;AAE3C,MAAM,YAAY,GAAGA;AACzB,KAAA,OAAO;AACP,KAAA,QAAQ;KACR,QAAQ,CAAC,qCAAqC;AAE1C,MAAM,UAAU,GAAGA;AACvB,KAAA,OAAO;AACP,KAAA,QAAQ;KACR,QAAQ,CAAC,oCAAoC;;;;;;;;;;;"}