@illuma-ai/agents 1.1.21 → 1.1.22

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 (241) hide show
  1. package/dist/cjs/graphs/Graph.cjs +12 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +85 -1
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/cjs/run.cjs +20 -9
  6. package/dist/cjs/run.cjs.map +1 -1
  7. package/dist/esm/graphs/Graph.mjs +12 -1
  8. package/dist/esm/graphs/Graph.mjs.map +1 -1
  9. package/dist/esm/graphs/MultiAgentGraph.mjs +85 -1
  10. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  11. package/dist/esm/run.mjs +20 -9
  12. package/dist/esm/run.mjs.map +1 -1
  13. package/dist/types/graphs/MultiAgentGraph.d.ts +17 -0
  14. package/package.json +1 -1
  15. package/src/graphs/Graph.ts +12 -1
  16. package/src/graphs/MultiAgentGraph.ts +105 -1
  17. package/src/graphs/__tests__/multi-agent-delegate.test.ts +191 -0
  18. package/src/run.ts +20 -11
  19. package/src/scripts/test-bedrock-handoff-autonomous.ts +231 -0
  20. package/src/agents/AgentContext.js +0 -782
  21. package/src/agents/AgentContext.test.js +0 -421
  22. package/src/agents/__tests__/AgentContext.test.js +0 -678
  23. package/src/agents/__tests__/resolveStructuredOutputMode.test.js +0 -117
  24. package/src/common/enum.js +0 -192
  25. package/src/common/index.js +0 -3
  26. package/src/events.js +0 -166
  27. package/src/graphs/Graph.js +0 -1857
  28. package/src/graphs/MultiAgentGraph.js +0 -1092
  29. package/src/graphs/__tests__/structured-output.integration.test.js +0 -624
  30. package/src/graphs/__tests__/structured-output.test.js +0 -144
  31. package/src/graphs/contextManagement.e2e.test.js +0 -718
  32. package/src/graphs/contextManagement.test.js +0 -485
  33. package/src/graphs/handoffValidation.test.js +0 -276
  34. package/src/graphs/index.js +0 -3
  35. package/src/index.js +0 -28
  36. package/src/instrumentation.js +0 -21
  37. package/src/llm/anthropic/index.js +0 -319
  38. package/src/llm/anthropic/types.js +0 -46
  39. package/src/llm/anthropic/utils/message_inputs.js +0 -627
  40. package/src/llm/anthropic/utils/message_outputs.js +0 -290
  41. package/src/llm/anthropic/utils/output_parsers.js +0 -89
  42. package/src/llm/anthropic/utils/tools.js +0 -25
  43. package/src/llm/bedrock/__tests__/bedrock-caching.test.js +0 -392
  44. package/src/llm/bedrock/index.js +0 -303
  45. package/src/llm/bedrock/types.js +0 -2
  46. package/src/llm/bedrock/utils/index.js +0 -6
  47. package/src/llm/bedrock/utils/message_inputs.js +0 -463
  48. package/src/llm/bedrock/utils/message_outputs.js +0 -269
  49. package/src/llm/fake.js +0 -92
  50. package/src/llm/google/index.js +0 -215
  51. package/src/llm/google/types.js +0 -12
  52. package/src/llm/google/utils/common.js +0 -670
  53. package/src/llm/google/utils/tools.js +0 -111
  54. package/src/llm/google/utils/zod_to_genai_parameters.js +0 -47
  55. package/src/llm/openai/index.js +0 -1033
  56. package/src/llm/openai/types.js +0 -2
  57. package/src/llm/openai/utils/index.js +0 -756
  58. package/src/llm/openai/utils/isReasoningModel.test.js +0 -79
  59. package/src/llm/openrouter/index.js +0 -261
  60. package/src/llm/openrouter/reasoning.test.js +0 -181
  61. package/src/llm/providers.js +0 -36
  62. package/src/llm/text.js +0 -65
  63. package/src/llm/vertexai/index.js +0 -402
  64. package/src/messages/__tests__/tools.test.js +0 -392
  65. package/src/messages/cache.js +0 -404
  66. package/src/messages/cache.test.js +0 -1167
  67. package/src/messages/content.js +0 -48
  68. package/src/messages/content.test.js +0 -314
  69. package/src/messages/core.js +0 -359
  70. package/src/messages/ensureThinkingBlock.test.js +0 -997
  71. package/src/messages/format.js +0 -973
  72. package/src/messages/formatAgentMessages.test.js +0 -2278
  73. package/src/messages/formatAgentMessages.tools.test.js +0 -362
  74. package/src/messages/formatMessage.test.js +0 -608
  75. package/src/messages/ids.js +0 -18
  76. package/src/messages/index.js +0 -9
  77. package/src/messages/labelContentByAgent.test.js +0 -725
  78. package/src/messages/prune.js +0 -438
  79. package/src/messages/reducer.js +0 -60
  80. package/src/messages/shiftIndexTokenCountMap.test.js +0 -63
  81. package/src/messages/summarize.js +0 -146
  82. package/src/messages/summarize.test.js +0 -332
  83. package/src/messages/tools.js +0 -90
  84. package/src/mockStream.js +0 -81
  85. package/src/prompts/collab.js +0 -7
  86. package/src/prompts/index.js +0 -3
  87. package/src/prompts/taskmanager.js +0 -58
  88. package/src/run.js +0 -427
  89. package/src/schemas/index.js +0 -3
  90. package/src/schemas/schema-preparation.test.js +0 -370
  91. package/src/schemas/validate.js +0 -314
  92. package/src/schemas/validate.test.js +0 -264
  93. package/src/scripts/abort.js +0 -127
  94. package/src/scripts/ant_web_search.js +0 -130
  95. package/src/scripts/ant_web_search_edge_case.js +0 -133
  96. package/src/scripts/ant_web_search_error_edge_case.js +0 -119
  97. package/src/scripts/args.js +0 -41
  98. package/src/scripts/bedrock-cache-debug.js +0 -186
  99. package/src/scripts/bedrock-content-aggregation-test.js +0 -195
  100. package/src/scripts/bedrock-merge-test.js +0 -80
  101. package/src/scripts/bedrock-parallel-tools-test.js +0 -150
  102. package/src/scripts/caching.js +0 -106
  103. package/src/scripts/cli.js +0 -152
  104. package/src/scripts/cli2.js +0 -119
  105. package/src/scripts/cli3.js +0 -163
  106. package/src/scripts/cli4.js +0 -165
  107. package/src/scripts/cli5.js +0 -165
  108. package/src/scripts/code_exec.js +0 -171
  109. package/src/scripts/code_exec_files.js +0 -180
  110. package/src/scripts/code_exec_multi_session.js +0 -185
  111. package/src/scripts/code_exec_ptc.js +0 -265
  112. package/src/scripts/code_exec_session.js +0 -217
  113. package/src/scripts/code_exec_simple.js +0 -120
  114. package/src/scripts/content.js +0 -111
  115. package/src/scripts/empty_input.js +0 -125
  116. package/src/scripts/handoff-test.js +0 -96
  117. package/src/scripts/image.js +0 -138
  118. package/src/scripts/memory.js +0 -83
  119. package/src/scripts/multi-agent-chain.js +0 -271
  120. package/src/scripts/multi-agent-conditional.js +0 -185
  121. package/src/scripts/multi-agent-document-review-chain.js +0 -171
  122. package/src/scripts/multi-agent-hybrid-flow.js +0 -264
  123. package/src/scripts/multi-agent-parallel-start.js +0 -214
  124. package/src/scripts/multi-agent-parallel.js +0 -346
  125. package/src/scripts/multi-agent-sequence.js +0 -184
  126. package/src/scripts/multi-agent-supervisor.js +0 -324
  127. package/src/scripts/multi-agent-test.js +0 -147
  128. package/src/scripts/parallel-asymmetric-tools-test.js +0 -202
  129. package/src/scripts/parallel-full-metadata-test.js +0 -176
  130. package/src/scripts/parallel-tools-test.js +0 -256
  131. package/src/scripts/programmatic_exec.js +0 -277
  132. package/src/scripts/programmatic_exec_agent.js +0 -168
  133. package/src/scripts/search.js +0 -118
  134. package/src/scripts/sequential-full-metadata-test.js +0 -143
  135. package/src/scripts/simple.js +0 -174
  136. package/src/scripts/single-agent-metadata-test.js +0 -152
  137. package/src/scripts/stream.js +0 -113
  138. package/src/scripts/test-custom-prompt-key.js +0 -132
  139. package/src/scripts/test-handoff-input.js +0 -143
  140. package/src/scripts/test-handoff-preamble.js +0 -227
  141. package/src/scripts/test-handoff-steering.js +0 -353
  142. package/src/scripts/test-multi-agent-list-handoff.js +0 -318
  143. package/src/scripts/test-parallel-agent-labeling.js +0 -253
  144. package/src/scripts/test-parallel-handoffs.js +0 -229
  145. package/src/scripts/test-thinking-handoff-bedrock.js +0 -132
  146. package/src/scripts/test-thinking-handoff.js +0 -132
  147. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +0 -140
  148. package/src/scripts/test-tool-before-handoff-role-order.js +0 -223
  149. package/src/scripts/test-tools-before-handoff.js +0 -187
  150. package/src/scripts/test_code_api.js +0 -263
  151. package/src/scripts/thinking-bedrock.js +0 -128
  152. package/src/scripts/thinking-vertexai.js +0 -130
  153. package/src/scripts/thinking.js +0 -134
  154. package/src/scripts/tool_search.js +0 -114
  155. package/src/scripts/tools.js +0 -125
  156. package/src/specs/agent-handoffs-bedrock.integration.test.js +0 -280
  157. package/src/specs/agent-handoffs.test.js +0 -924
  158. package/src/specs/anthropic.simple.test.js +0 -287
  159. package/src/specs/azure.simple.test.js +0 -381
  160. package/src/specs/cache.simple.test.js +0 -282
  161. package/src/specs/custom-event-await.test.js +0 -148
  162. package/src/specs/deepseek.simple.test.js +0 -189
  163. package/src/specs/emergency-prune.test.js +0 -308
  164. package/src/specs/moonshot.simple.test.js +0 -237
  165. package/src/specs/observability.integration.test.js +0 -1337
  166. package/src/specs/openai.simple.test.js +0 -233
  167. package/src/specs/openrouter.simple.test.js +0 -202
  168. package/src/specs/prune.test.js +0 -733
  169. package/src/specs/reasoning.test.js +0 -144
  170. package/src/specs/spec.utils.js +0 -4
  171. package/src/specs/thinking-handoff.test.js +0 -486
  172. package/src/specs/thinking-prune.test.js +0 -600
  173. package/src/specs/token-distribution-edge-case.test.js +0 -246
  174. package/src/specs/token-memoization.test.js +0 -32
  175. package/src/specs/tokens.test.js +0 -49
  176. package/src/specs/tool-error.test.js +0 -139
  177. package/src/splitStream.js +0 -204
  178. package/src/splitStream.test.js +0 -504
  179. package/src/stream.js +0 -650
  180. package/src/stream.test.js +0 -225
  181. package/src/test/mockTools.js +0 -340
  182. package/src/tools/BrowserTools.js +0 -245
  183. package/src/tools/Calculator.js +0 -38
  184. package/src/tools/Calculator.test.js +0 -225
  185. package/src/tools/CodeExecutor.js +0 -233
  186. package/src/tools/ProgrammaticToolCalling.js +0 -602
  187. package/src/tools/StreamingToolCallBuffer.js +0 -179
  188. package/src/tools/ToolNode.js +0 -930
  189. package/src/tools/ToolSearch.js +0 -904
  190. package/src/tools/__tests__/BrowserTools.test.js +0 -306
  191. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +0 -276
  192. package/src/tools/__tests__/ProgrammaticToolCalling.test.js +0 -807
  193. package/src/tools/__tests__/StreamingToolCallBuffer.test.js +0 -175
  194. package/src/tools/__tests__/ToolApproval.test.js +0 -675
  195. package/src/tools/__tests__/ToolNode.recovery.test.js +0 -200
  196. package/src/tools/__tests__/ToolNode.session.test.js +0 -319
  197. package/src/tools/__tests__/ToolSearch.integration.test.js +0 -125
  198. package/src/tools/__tests__/ToolSearch.test.js +0 -812
  199. package/src/tools/__tests__/handlers.test.js +0 -799
  200. package/src/tools/__tests__/truncation-recovery.integration.test.js +0 -362
  201. package/src/tools/handlers.js +0 -306
  202. package/src/tools/schema.js +0 -25
  203. package/src/tools/search/anthropic.js +0 -34
  204. package/src/tools/search/content.js +0 -116
  205. package/src/tools/search/content.test.js +0 -133
  206. package/src/tools/search/firecrawl.js +0 -173
  207. package/src/tools/search/format.js +0 -198
  208. package/src/tools/search/highlights.js +0 -241
  209. package/src/tools/search/index.js +0 -3
  210. package/src/tools/search/jina-reranker.test.js +0 -106
  211. package/src/tools/search/rerankers.js +0 -165
  212. package/src/tools/search/schema.js +0 -102
  213. package/src/tools/search/search.js +0 -561
  214. package/src/tools/search/serper-scraper.js +0 -126
  215. package/src/tools/search/test.js +0 -129
  216. package/src/tools/search/tool.js +0 -453
  217. package/src/tools/search/types.js +0 -2
  218. package/src/tools/search/utils.js +0 -59
  219. package/src/types/graph.js +0 -24
  220. package/src/types/graph.test.js +0 -192
  221. package/src/types/index.js +0 -7
  222. package/src/types/llm.js +0 -2
  223. package/src/types/messages.js +0 -2
  224. package/src/types/run.js +0 -2
  225. package/src/types/stream.js +0 -2
  226. package/src/types/tools.js +0 -2
  227. package/src/utils/contextAnalytics.js +0 -79
  228. package/src/utils/contextAnalytics.test.js +0 -166
  229. package/src/utils/events.js +0 -26
  230. package/src/utils/graph.js +0 -11
  231. package/src/utils/handlers.js +0 -65
  232. package/src/utils/index.js +0 -10
  233. package/src/utils/llm.js +0 -21
  234. package/src/utils/llmConfig.js +0 -205
  235. package/src/utils/logging.js +0 -37
  236. package/src/utils/misc.js +0 -51
  237. package/src/utils/run.js +0 -69
  238. package/src/utils/schema.js +0 -21
  239. package/src/utils/title.js +0 -119
  240. package/src/utils/tokens.js +0 -92
  241. package/src/utils/toonFormat.js +0 -379
@@ -1,561 +0,0 @@
1
- import axios from 'axios';
2
- import { RecursiveCharacterTextSplitter } from '@langchain/textsplitters';
3
- import { getAttribution, createDefaultLogger } from './utils';
4
- const chunker = {
5
- cleanText: (text) => {
6
- if (!text)
7
- return '';
8
- /** Normalized all line endings to '\n' */
9
- const normalizedText = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
10
- /** Handle multiple backslashes followed by newlines
11
- * This replaces patterns like '\\\\\\n' with a single newline */
12
- const fixedBackslashes = normalizedText.replace(/\\+\n/g, '\n');
13
- /** Cleaned up consecutive newlines, tabs, and spaces around newlines */
14
- const cleanedNewlines = fixedBackslashes.replace(/[\t ]*\n[\t \n]*/g, '\n');
15
- /** Cleaned up excessive spaces and tabs */
16
- const cleanedSpaces = cleanedNewlines.replace(/[ \t]+/g, ' ');
17
- return cleanedSpaces.trim();
18
- },
19
- splitText: async (text, options) => {
20
- const chunkSize = options?.chunkSize ?? 150;
21
- const chunkOverlap = options?.chunkOverlap ?? 50;
22
- const separators = options?.separators || ['\n\n', '\n'];
23
- const splitter = new RecursiveCharacterTextSplitter({
24
- separators,
25
- chunkSize,
26
- chunkOverlap,
27
- });
28
- return await splitter.splitText(text);
29
- },
30
- splitTexts: async (texts, options, logger) => {
31
- // Split multiple texts
32
- const logger_ = logger || createDefaultLogger();
33
- const promises = texts.map((text) => chunker.splitText(text, options).catch((error) => {
34
- logger_.error('Error splitting text:', error);
35
- return [text];
36
- }));
37
- return Promise.all(promises);
38
- },
39
- };
40
- function createSourceUpdateCallback(sourceMap) {
41
- return (link, update) => {
42
- const source = sourceMap.get(link);
43
- if (source) {
44
- sourceMap.set(link, {
45
- ...source,
46
- ...update,
47
- });
48
- }
49
- };
50
- }
51
- const getHighlights = async ({ query, content, reranker, topResults = 5, logger, }) => {
52
- const logger_ = logger || createDefaultLogger();
53
- if (!content) {
54
- logger_.warn('No content provided for highlights');
55
- return;
56
- }
57
- if (!reranker) {
58
- logger_.warn('No reranker provided for highlights');
59
- return;
60
- }
61
- try {
62
- const documents = await chunker.splitText(content);
63
- if (Array.isArray(documents)) {
64
- return await reranker.rerank(query, documents, topResults);
65
- }
66
- else {
67
- logger_.error('Expected documents to be an array, got:', typeof documents);
68
- return;
69
- }
70
- }
71
- catch (error) {
72
- logger_.error('Error in content processing:', error);
73
- return;
74
- }
75
- };
76
- const createSerperAPI = (apiKey) => {
77
- const config = {
78
- apiKey: apiKey ?? process.env.SERPER_API_KEY,
79
- apiUrl: 'https://google.serper.dev/search',
80
- timeout: 10000,
81
- };
82
- if (config.apiKey == null || config.apiKey === '') {
83
- throw new Error('SERPER_API_KEY is required for SerperAPI');
84
- }
85
- const getSources = async ({ query, date, country, safeSearch, numResults = 8, type, }) => {
86
- if (!query.trim()) {
87
- return { success: false, error: 'Query cannot be empty' };
88
- }
89
- try {
90
- const safe = ['off', 'moderate', 'active'];
91
- const payload = {
92
- q: query,
93
- safe: safe[safeSearch ?? 1],
94
- num: Math.min(Math.max(1, numResults), 10),
95
- };
96
- // Set the search type if provided
97
- if (type) {
98
- payload.type = type;
99
- }
100
- if (date != null) {
101
- payload.tbs = `qdr:${date}`;
102
- }
103
- if (country != null && country !== '') {
104
- payload['gl'] = country.toLowerCase();
105
- }
106
- // Determine the API endpoint based on the search type
107
- let apiEndpoint = config.apiUrl;
108
- if (type === 'images') {
109
- apiEndpoint = 'https://google.serper.dev/images';
110
- }
111
- else if (type === 'videos') {
112
- apiEndpoint = 'https://google.serper.dev/videos';
113
- }
114
- else if (type === 'news') {
115
- apiEndpoint = 'https://google.serper.dev/news';
116
- }
117
- const response = await axios.post(apiEndpoint, payload, {
118
- headers: {
119
- 'X-API-KEY': config.apiKey,
120
- 'Content-Type': 'application/json',
121
- },
122
- timeout: config.timeout,
123
- });
124
- const data = response.data;
125
- const results = {
126
- organic: data.organic,
127
- images: data.images ?? [],
128
- answerBox: data.answerBox,
129
- topStories: data.topStories ?? [],
130
- peopleAlsoAsk: data.peopleAlsoAsk,
131
- knowledgeGraph: data.knowledgeGraph,
132
- relatedSearches: data.relatedSearches,
133
- videos: data.videos ?? [],
134
- news: data.news ?? [],
135
- };
136
- return { success: true, data: results };
137
- }
138
- catch (error) {
139
- const errorMessage = error instanceof Error ? error.message : String(error);
140
- return { success: false, error: `API request failed: ${errorMessage}` };
141
- }
142
- };
143
- return { getSources };
144
- };
145
- const createSearXNGAPI = (instanceUrl, apiKey) => {
146
- const config = {
147
- instanceUrl: instanceUrl ?? process.env.SEARXNG_INSTANCE_URL,
148
- apiKey: apiKey ?? process.env.SEARXNG_API_KEY,
149
- defaultLocation: 'all',
150
- timeout: 10000,
151
- };
152
- if (config.instanceUrl == null || config.instanceUrl === '') {
153
- throw new Error('SEARXNG_INSTANCE_URL is required for SearXNG API');
154
- }
155
- const getSources = async ({ query, numResults = 8, safeSearch, type, }) => {
156
- if (!query.trim()) {
157
- return { success: false, error: 'Query cannot be empty' };
158
- }
159
- try {
160
- // Ensure the instance URL ends with /search
161
- if (config.instanceUrl == null || config.instanceUrl === '') {
162
- return { success: false, error: 'Instance URL is not defined' };
163
- }
164
- let searchUrl = config.instanceUrl;
165
- if (!searchUrl.endsWith('/search')) {
166
- searchUrl = searchUrl.replace(/\/$/, '') + '/search';
167
- }
168
- // Determine the search category based on the type
169
- let category = 'general';
170
- if (type === 'images') {
171
- category = 'images';
172
- }
173
- else if (type === 'videos') {
174
- category = 'videos';
175
- }
176
- else if (type === 'news') {
177
- category = 'news';
178
- }
179
- // Prepare parameters for SearXNG
180
- const params = {
181
- q: query,
182
- format: 'json',
183
- pageno: 1,
184
- categories: category,
185
- language: 'all',
186
- safesearch: safeSearch,
187
- engines: 'google,bing,duckduckgo',
188
- };
189
- const headers = {
190
- 'Content-Type': 'application/json',
191
- };
192
- if (config.apiKey != null && config.apiKey !== '') {
193
- headers['X-API-Key'] = config.apiKey;
194
- }
195
- const response = await axios.get(searchUrl, {
196
- headers,
197
- params,
198
- timeout: config.timeout,
199
- });
200
- const data = response.data;
201
- // Helper function to identify news results since SearXNG doesn't provide that classification by default
202
- const isNewsResult = (result) => {
203
- const url = result.url?.toLowerCase() ?? '';
204
- const title = result.title?.toLowerCase() ?? '';
205
- // News-related keywords in title/content
206
- const newsKeywords = [
207
- 'breaking news',
208
- 'latest news',
209
- 'top stories',
210
- 'news today',
211
- 'developing story',
212
- 'trending news',
213
- 'news',
214
- ];
215
- // Check if title/content contains news keywords
216
- const hasNewsKeywords = newsKeywords.some((keyword) => title.toLowerCase().includes(keyword) // just title probably fine, content parsing is overkill for what we need: || content.includes(keyword)
217
- );
218
- // Check if URL contains news-related paths
219
- const hasNewsPath = url.includes('/news/') ||
220
- url.includes('/world/') ||
221
- url.includes('/politics/') ||
222
- url.includes('/breaking/');
223
- return hasNewsKeywords || hasNewsPath;
224
- };
225
- // Transform SearXNG results to match SerperAPI format
226
- const organicResults = (data.results ?? [])
227
- .slice(0, numResults)
228
- .map((result, index) => {
229
- let attribution = '';
230
- try {
231
- attribution = new URL(result.url ?? '').hostname;
232
- }
233
- catch {
234
- attribution = '';
235
- }
236
- return {
237
- position: index + 1,
238
- title: result.title ?? '',
239
- link: result.url ?? '',
240
- snippet: result.content ?? '',
241
- date: result.publishedDate ?? '',
242
- attribution,
243
- };
244
- });
245
- const imageResults = (data.results ?? [])
246
- .filter((result) => result.img_src)
247
- .slice(0, 6)
248
- .map((result, index) => ({
249
- title: result.title ?? '',
250
- imageUrl: result.img_src ?? '',
251
- position: index + 1,
252
- source: new URL(result.url ?? '').hostname,
253
- domain: new URL(result.url ?? '').hostname,
254
- link: result.url ?? '',
255
- }));
256
- // Extract news results from organic results
257
- const newsResults = (data.results ?? [])
258
- .filter(isNewsResult)
259
- .map((result, index) => {
260
- let attribution = '';
261
- try {
262
- attribution = new URL(result.url ?? '').hostname;
263
- }
264
- catch {
265
- attribution = '';
266
- }
267
- return {
268
- title: result.title ?? '',
269
- link: result.url ?? '',
270
- snippet: result.content ?? '',
271
- date: result.publishedDate ?? '',
272
- source: attribution,
273
- imageUrl: result.img_src ?? '',
274
- position: index + 1,
275
- };
276
- });
277
- const topStories = newsResults.slice(0, 5);
278
- const relatedSearches = Array.isArray(data.suggestions)
279
- ? data.suggestions.map((suggestion) => ({ query: suggestion }))
280
- : [];
281
- const results = {
282
- organic: organicResults,
283
- images: imageResults,
284
- topStories: topStories, // Use first 5 extracted news as top stories
285
- relatedSearches,
286
- videos: [],
287
- news: newsResults,
288
- // Add empty arrays for other Serper fields to maintain parity
289
- places: [],
290
- shopping: [],
291
- peopleAlsoAsk: [],
292
- knowledgeGraph: undefined,
293
- answerBox: undefined,
294
- };
295
- return { success: true, data: results };
296
- }
297
- catch (error) {
298
- const errorMessage = error instanceof Error ? error.message : String(error);
299
- return {
300
- success: false,
301
- error: `SearXNG API request failed: ${errorMessage}`,
302
- };
303
- }
304
- };
305
- return { getSources };
306
- };
307
- export const createSearchAPI = (config) => {
308
- const { searchProvider = 'serper', serperApiKey, searxngInstanceUrl, searxngApiKey, } = config;
309
- if (searchProvider.toLowerCase() === 'serper') {
310
- return createSerperAPI(serperApiKey);
311
- }
312
- else if (searchProvider.toLowerCase() === 'searxng') {
313
- return createSearXNGAPI(searxngInstanceUrl, searxngApiKey);
314
- }
315
- else {
316
- throw new Error(`Invalid search provider: ${searchProvider}. Must be 'serper' or 'searxng'`);
317
- }
318
- };
319
- export const createSourceProcessor = (config = {}, scraperInstance) => {
320
- if (!scraperInstance) {
321
- throw new Error('Scraper instance is required');
322
- }
323
- const { topResults = 5,
324
- // strategies = ['no_extraction'],
325
- // filterContent = true,
326
- reranker, logger, } = config;
327
- const logger_ = logger || createDefaultLogger();
328
- const scraper = scraperInstance;
329
- const webScraper = {
330
- scrapeMany: async ({ query, links, onGetHighlights, }) => {
331
- logger_.debug(`Scraping ${links.length} links`);
332
- const promises = [];
333
- try {
334
- for (let i = 0; i < links.length; i++) {
335
- const currentLink = links[i];
336
- const promise = scraper
337
- .scrapeUrl(currentLink, {})
338
- .then(([url, response]) => {
339
- const attribution = getAttribution(url, response.data?.metadata, logger_);
340
- if (response.success && response.data) {
341
- const [content, references] = scraper.extractContent(response);
342
- return {
343
- url,
344
- references,
345
- attribution,
346
- content: chunker.cleanText(content),
347
- };
348
- }
349
- else {
350
- logger_.error(`Error scraping ${url}: ${response.error ?? 'Unknown error'}`);
351
- }
352
- return {
353
- url,
354
- attribution,
355
- error: true,
356
- content: '',
357
- };
358
- })
359
- .then(async (result) => {
360
- try {
361
- if (result.error != null) {
362
- logger_.error(`Error scraping ${result.url}: ${result.content}`);
363
- return {
364
- ...result,
365
- };
366
- }
367
- const highlights = await getHighlights({
368
- query,
369
- reranker,
370
- content: result.content,
371
- logger: logger_,
372
- });
373
- if (onGetHighlights) {
374
- onGetHighlights(result.url);
375
- }
376
- return {
377
- ...result,
378
- highlights,
379
- };
380
- }
381
- catch (error) {
382
- logger_.error('Error processing scraped content:', error);
383
- return {
384
- ...result,
385
- };
386
- }
387
- })
388
- .catch((error) => {
389
- logger_.error(`Error scraping ${currentLink}:`, error);
390
- return {
391
- url: currentLink,
392
- error: true,
393
- content: '',
394
- };
395
- });
396
- promises.push(promise);
397
- }
398
- return await Promise.all(promises);
399
- }
400
- catch (error) {
401
- logger_.error('Error in scrapeMany:', error);
402
- return [];
403
- }
404
- },
405
- };
406
- const fetchContents = async ({ links, query, target, onGetHighlights, onContentScraped, }) => {
407
- const initialLinks = links.slice(0, target);
408
- // const remainingLinks = links.slice(target).reverse();
409
- const results = await webScraper.scrapeMany({
410
- query,
411
- links: initialLinks,
412
- onGetHighlights,
413
- });
414
- for (const result of results) {
415
- if (result.error === true) {
416
- continue;
417
- }
418
- const { url, content, attribution, references, highlights } = result;
419
- onContentScraped?.(url, {
420
- content,
421
- attribution,
422
- references,
423
- highlights,
424
- });
425
- }
426
- };
427
- const processSources = async ({ result, numElements, query, news, proMode = true, onGetHighlights, skipScraping = false, }) => {
428
- try {
429
- if (!result.data) {
430
- return {
431
- organic: [],
432
- topStories: [],
433
- images: [],
434
- relatedSearches: [],
435
- };
436
- }
437
- else if (!result.data.organic) {
438
- return result.data;
439
- }
440
- // If content was already extracted directly (e.g., direct URL extraction), skip scraping
441
- if (skipScraping) {
442
- logger_.debug('Skipping additional scraping - content already extracted');
443
- return result.data;
444
- }
445
- if (!proMode) {
446
- const wikiSources = result.data.organic.filter((source) => source.link.includes('wikipedia.org'));
447
- if (!wikiSources.length) {
448
- return result.data;
449
- }
450
- const wikiSourceMap = new Map();
451
- wikiSourceMap.set(wikiSources[0].link, wikiSources[0]);
452
- const onContentScraped = createSourceUpdateCallback(wikiSourceMap);
453
- await fetchContents({
454
- query,
455
- target: 1,
456
- onGetHighlights,
457
- onContentScraped,
458
- links: [wikiSources[0].link],
459
- });
460
- for (let i = 0; i < result.data.organic.length; i++) {
461
- const source = result.data.organic[i];
462
- const updatedSource = wikiSourceMap.get(source.link);
463
- if (updatedSource) {
464
- result.data.organic[i] = {
465
- ...source,
466
- ...updatedSource,
467
- };
468
- }
469
- }
470
- return result.data;
471
- }
472
- const sourceMap = new Map();
473
- const organicLinksSet = new Set();
474
- // Collect organic links
475
- const organicLinks = collectLinks(result.data.organic, sourceMap, organicLinksSet);
476
- // Collect top story links, excluding any that are already in organic links
477
- const topStories = result.data.topStories ?? [];
478
- const topStoryLinks = collectLinks(topStories, sourceMap, organicLinksSet);
479
- if (organicLinks.length === 0 && (topStoryLinks.length === 0 || !news)) {
480
- return result.data;
481
- }
482
- const onContentScraped = createSourceUpdateCallback(sourceMap);
483
- const promises = [];
484
- // Process organic links
485
- if (organicLinks.length > 0) {
486
- promises.push(fetchContents({
487
- query,
488
- onGetHighlights,
489
- onContentScraped,
490
- links: organicLinks,
491
- target: numElements,
492
- }));
493
- }
494
- // Process top story links
495
- if (news && topStoryLinks.length > 0) {
496
- promises.push(fetchContents({
497
- query,
498
- onGetHighlights,
499
- onContentScraped,
500
- links: topStoryLinks,
501
- target: numElements,
502
- }));
503
- }
504
- await Promise.all(promises);
505
- if (result.data.organic.length > 0) {
506
- updateSourcesWithContent(result.data.organic, sourceMap);
507
- }
508
- if (news && topStories.length > 0) {
509
- updateSourcesWithContent(topStories, sourceMap);
510
- }
511
- return result.data;
512
- }
513
- catch (error) {
514
- logger_.error('Error in processSources:', error);
515
- return {
516
- organic: [],
517
- topStories: [],
518
- images: [],
519
- relatedSearches: [],
520
- ...result.data,
521
- error: error instanceof Error ? error.message : String(error),
522
- };
523
- }
524
- };
525
- return {
526
- processSources,
527
- topResults,
528
- };
529
- };
530
- /** Helper function to collect links and update sourceMap */
531
- function collectLinks(sources, sourceMap, existingLinksSet) {
532
- const links = [];
533
- for (const source of sources) {
534
- if (source.link) {
535
- // For topStories, only add if not already in organic links
536
- if (existingLinksSet && existingLinksSet.has(source.link)) {
537
- continue;
538
- }
539
- links.push(source.link);
540
- if (existingLinksSet) {
541
- existingLinksSet.add(source.link);
542
- }
543
- sourceMap.set(source.link, source);
544
- }
545
- }
546
- return links;
547
- }
548
- /** Helper function to update sources with scraped content */
549
- function updateSourcesWithContent(sources, sourceMap) {
550
- for (let i = 0; i < sources.length; i++) {
551
- const source = sources[i];
552
- const updatedSource = sourceMap.get(source.link);
553
- if (updatedSource) {
554
- sources[i] = {
555
- ...source,
556
- ...updatedSource,
557
- };
558
- }
559
- }
560
- }
561
- //# sourceMappingURL=search.js.map
@@ -1,126 +0,0 @@
1
- import axios from 'axios';
2
- import { createDefaultLogger } from './utils';
3
- /**
4
- * Serper scraper implementation
5
- * Uses the Serper Scrape API (https://scrape.serper.dev) to scrape web pages
6
- *
7
- * Features:
8
- * - Simple API with single endpoint
9
- * - Returns both text and markdown content
10
- * - Includes metadata from scraped pages
11
- * - Credits-based pricing model
12
- *
13
- * @example
14
- * ```typescript
15
- * const scraper = createSerperScraper({
16
- * apiKey: 'your-serper-api-key',
17
- * includeMarkdown: true,
18
- * timeout: 10000
19
- * });
20
- *
21
- * const [url, response] = await scraper.scrapeUrl('https://example.com');
22
- * if (response.success) {
23
- * const [content] = scraper.extractContent(response);
24
- * console.log(content);
25
- * }
26
- * ```
27
- */
28
- export class SerperScraper {
29
- apiKey;
30
- apiUrl;
31
- timeout;
32
- logger;
33
- includeMarkdown;
34
- constructor(config = {}) {
35
- this.apiKey = config.apiKey ?? process.env.SERPER_API_KEY ?? '';
36
- this.apiUrl =
37
- config.apiUrl ??
38
- process.env.SERPER_SCRAPE_URL ??
39
- 'https://scrape.serper.dev';
40
- this.timeout = config.timeout ?? 7500;
41
- this.includeMarkdown = config.includeMarkdown ?? true;
42
- this.logger = config.logger || createDefaultLogger();
43
- if (!this.apiKey) {
44
- this.logger.warn('SERPER_API_KEY is not set. Scraping will not work.');
45
- }
46
- this.logger.debug(`Serper scraper initialized with API URL: ${this.apiUrl}`);
47
- }
48
- /**
49
- * Scrape a single URL
50
- * @param url URL to scrape
51
- * @param options Scrape options
52
- * @returns Scrape response
53
- */
54
- async scrapeUrl(url, options = {}) {
55
- if (!this.apiKey) {
56
- return [
57
- url,
58
- {
59
- success: false,
60
- error: 'SERPER_API_KEY is not set',
61
- },
62
- ];
63
- }
64
- try {
65
- const payload = {
66
- url,
67
- includeMarkdown: options.includeMarkdown ?? this.includeMarkdown,
68
- };
69
- const response = await axios.post(this.apiUrl, payload, {
70
- headers: {
71
- 'X-API-KEY': this.apiKey,
72
- 'Content-Type': 'application/json',
73
- },
74
- timeout: options.timeout ?? this.timeout,
75
- });
76
- return [url, { success: true, data: response.data }];
77
- }
78
- catch (error) {
79
- const errorMessage = error instanceof Error ? error.message : String(error);
80
- return [
81
- url,
82
- {
83
- success: false,
84
- error: `Serper Scrape API request failed: ${errorMessage}`,
85
- },
86
- ];
87
- }
88
- }
89
- /**
90
- * Extract content from scrape response
91
- * @param response Scrape response
92
- * @returns Extracted content or empty string if not available
93
- */
94
- extractContent(response) {
95
- if (!response.success || !response.data) {
96
- return ['', undefined];
97
- }
98
- if (response.data.markdown != null) {
99
- return [response.data.markdown, undefined];
100
- }
101
- if (response.data.text != null) {
102
- return [response.data.text, undefined];
103
- }
104
- return ['', undefined];
105
- }
106
- /**
107
- * Extract metadata from scrape response
108
- * @param response Scrape response
109
- * @returns Metadata object
110
- */
111
- extractMetadata(response) {
112
- if (!response.success || !response.data || !response.data.metadata) {
113
- return {};
114
- }
115
- return response.data.metadata;
116
- }
117
- }
118
- /**
119
- * Create a Serper scraper instance
120
- * @param config Scraper configuration
121
- * @returns Serper scraper instance
122
- */
123
- export const createSerperScraper = (config = {}) => {
124
- return new SerperScraper(config);
125
- };
126
- //# sourceMappingURL=serper-scraper.js.map