langchain 0.0.153 → 0.0.155
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/base_language/index.cjs +36 -0
- package/dist/base_language/index.d.ts +9 -1
- package/dist/base_language/index.js +36 -0
- package/dist/cache/base.cjs +24 -1
- package/dist/cache/base.d.ts +9 -0
- package/dist/cache/base.js +21 -0
- package/dist/cache/cloudflare_kv.cjs +2 -5
- package/dist/cache/cloudflare_kv.js +3 -6
- package/dist/cache/ioredis.cjs +16 -6
- package/dist/cache/ioredis.d.ts +5 -2
- package/dist/cache/ioredis.js +17 -7
- package/dist/cache/momento.cjs +6 -2
- package/dist/cache/momento.js +7 -3
- package/dist/cache/redis.cjs +3 -5
- package/dist/cache/redis.js +4 -6
- package/dist/cache/upstash_redis.cjs +2 -5
- package/dist/cache/upstash_redis.js +3 -6
- package/dist/callbacks/base.d.ts +42 -28
- package/dist/callbacks/handlers/log_stream.cjs +283 -0
- package/dist/callbacks/handlers/log_stream.d.ts +99 -0
- package/dist/callbacks/handlers/log_stream.js +277 -0
- package/dist/callbacks/handlers/tracer.cjs +34 -18
- package/dist/callbacks/handlers/tracer.d.ts +18 -16
- package/dist/callbacks/handlers/tracer.js +34 -18
- package/dist/chat_models/base.cjs +64 -20
- package/dist/chat_models/base.d.ts +7 -0
- package/dist/chat_models/base.js +64 -20
- package/dist/document_loaders/web/notionapi.cjs +8 -4
- package/dist/document_loaders/web/notionapi.js +8 -4
- package/dist/document_loaders/web/searchapi.cjs +134 -0
- package/dist/document_loaders/web/searchapi.d.ts +65 -0
- package/dist/document_loaders/web/searchapi.js +130 -0
- package/dist/llms/base.cjs +10 -26
- package/dist/llms/base.d.ts +4 -4
- package/dist/llms/base.js +4 -20
- package/dist/load/import_constants.cjs +1 -0
- package/dist/load/import_constants.js +1 -0
- package/dist/load/import_map.cjs +3 -2
- package/dist/load/import_map.d.ts +1 -0
- package/dist/load/import_map.js +1 -0
- package/dist/schema/index.cjs +50 -1
- package/dist/schema/index.d.ts +5 -0
- package/dist/schema/index.js +48 -0
- package/dist/schema/runnable/base.cjs +64 -5
- package/dist/schema/runnable/base.d.ts +13 -0
- package/dist/schema/runnable/base.js +64 -5
- package/dist/stores/message/utils.cjs +2 -50
- package/dist/stores/message/utils.d.ts +0 -14
- package/dist/stores/message/utils.js +2 -49
- package/dist/tools/index.cjs +3 -1
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.js +1 -0
- package/dist/tools/searchapi.cjs +139 -0
- package/dist/tools/searchapi.d.ts +64 -0
- package/dist/tools/searchapi.js +135 -0
- package/dist/util/fast-json-patch/index.cjs +48 -0
- package/dist/util/fast-json-patch/index.d.ts +21 -0
- package/dist/util/fast-json-patch/index.js +15 -0
- package/dist/util/fast-json-patch/src/core.cjs +469 -0
- package/dist/util/fast-json-patch/src/core.d.ts +111 -0
- package/dist/util/fast-json-patch/src/core.js +459 -0
- package/dist/util/fast-json-patch/src/helpers.cjs +194 -0
- package/dist/util/fast-json-patch/src/helpers.d.ts +36 -0
- package/dist/util/fast-json-patch/src/helpers.js +181 -0
- package/dist/util/googlevertexai-webauth.cjs +6 -2
- package/dist/util/googlevertexai-webauth.d.ts +1 -0
- package/dist/util/googlevertexai-webauth.js +6 -2
- package/dist/util/stream.cjs +2 -40
- package/dist/util/stream.d.ts +1 -2
- package/dist/util/stream.js +1 -38
- package/dist/vectorstores/pgvector.cjs +1 -1
- package/dist/vectorstores/pgvector.js +1 -1
- package/dist/vectorstores/vercel_postgres.cjs +300 -0
- package/dist/vectorstores/vercel_postgres.d.ts +145 -0
- package/dist/vectorstores/vercel_postgres.js +296 -0
- package/document_loaders/web/searchapi.cjs +1 -0
- package/document_loaders/web/searchapi.d.ts +1 -0
- package/document_loaders/web/searchapi.js +1 -0
- package/package.json +22 -1
- package/vectorstores/vercel_postgres.cjs +1 -0
- package/vectorstores/vercel_postgres.d.ts +1 -0
- package/vectorstores/vercel_postgres.js +1 -0
|
@@ -21,7 +21,7 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
21
21
|
_addChildRun(parentRun, childRun) {
|
|
22
22
|
parentRun.child_runs.push(childRun);
|
|
23
23
|
}
|
|
24
|
-
_startTrace(run) {
|
|
24
|
+
async _startTrace(run) {
|
|
25
25
|
if (run.parent_run_id !== undefined) {
|
|
26
26
|
const parentRun = this.runMap.get(run.parent_run_id);
|
|
27
27
|
if (parentRun) {
|
|
@@ -30,6 +30,7 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
this.runMap.set(run.id, run);
|
|
33
|
+
await this.onRunCreate?.(run);
|
|
33
34
|
}
|
|
34
35
|
async _endTrace(run) {
|
|
35
36
|
const parentRun = run.parent_run_id !== undefined && this.runMap.get(run.parent_run_id);
|
|
@@ -40,6 +41,7 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
40
41
|
await this.persistRun(run);
|
|
41
42
|
}
|
|
42
43
|
this.runMap.delete(run.id);
|
|
44
|
+
await this.onRunUpdate?.(run);
|
|
43
45
|
}
|
|
44
46
|
_getExecutionOrder(parentRunId) {
|
|
45
47
|
const parentRun = parentRunId !== undefined && this.runMap.get(parentRunId);
|
|
@@ -49,7 +51,7 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
49
51
|
}
|
|
50
52
|
return parentRun.child_execution_order + 1;
|
|
51
53
|
}
|
|
52
|
-
async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata) {
|
|
54
|
+
async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) {
|
|
53
55
|
const execution_order = this._getExecutionOrder(parentRunId);
|
|
54
56
|
const start_time = Date.now();
|
|
55
57
|
const finalExtraParams = metadata
|
|
@@ -57,7 +59,7 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
57
59
|
: extraParams;
|
|
58
60
|
const run = {
|
|
59
61
|
id: runId,
|
|
60
|
-
name: llm.id[llm.id.length - 1],
|
|
62
|
+
name: name ?? llm.id[llm.id.length - 1],
|
|
61
63
|
parent_run_id: parentRunId,
|
|
62
64
|
start_time,
|
|
63
65
|
serialized: llm,
|
|
@@ -75,10 +77,11 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
75
77
|
extra: finalExtraParams ?? {},
|
|
76
78
|
tags: tags || [],
|
|
77
79
|
};
|
|
78
|
-
this._startTrace(run);
|
|
80
|
+
await this._startTrace(run);
|
|
79
81
|
await this.onLLMStart?.(run);
|
|
82
|
+
return run;
|
|
80
83
|
}
|
|
81
|
-
async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata) {
|
|
84
|
+
async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) {
|
|
82
85
|
const execution_order = this._getExecutionOrder(parentRunId);
|
|
83
86
|
const start_time = Date.now();
|
|
84
87
|
const finalExtraParams = metadata
|
|
@@ -86,7 +89,7 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
86
89
|
: extraParams;
|
|
87
90
|
const run = {
|
|
88
91
|
id: runId,
|
|
89
|
-
name: llm.id[llm.id.length - 1],
|
|
92
|
+
name: name ?? llm.id[llm.id.length - 1],
|
|
90
93
|
parent_run_id: parentRunId,
|
|
91
94
|
start_time,
|
|
92
95
|
serialized: llm,
|
|
@@ -104,8 +107,9 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
104
107
|
extra: finalExtraParams ?? {},
|
|
105
108
|
tags: tags || [],
|
|
106
109
|
};
|
|
107
|
-
this._startTrace(run);
|
|
110
|
+
await this._startTrace(run);
|
|
108
111
|
await this.onLLMStart?.(run);
|
|
112
|
+
return run;
|
|
109
113
|
}
|
|
110
114
|
async handleLLMEnd(output, runId) {
|
|
111
115
|
const run = this.runMap.get(runId);
|
|
@@ -120,6 +124,7 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
120
124
|
});
|
|
121
125
|
await this.onLLMEnd?.(run);
|
|
122
126
|
await this._endTrace(run);
|
|
127
|
+
return run;
|
|
123
128
|
}
|
|
124
129
|
async handleLLMError(error, runId) {
|
|
125
130
|
const run = this.runMap.get(runId);
|
|
@@ -134,13 +139,14 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
134
139
|
});
|
|
135
140
|
await this.onLLMError?.(run);
|
|
136
141
|
await this._endTrace(run);
|
|
142
|
+
return run;
|
|
137
143
|
}
|
|
138
|
-
async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType) {
|
|
144
|
+
async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) {
|
|
139
145
|
const execution_order = this._getExecutionOrder(parentRunId);
|
|
140
146
|
const start_time = Date.now();
|
|
141
147
|
const run = {
|
|
142
148
|
id: runId,
|
|
143
|
-
name: chain.id[chain.id.length - 1],
|
|
149
|
+
name: name ?? chain.id[chain.id.length - 1],
|
|
144
150
|
parent_run_id: parentRunId,
|
|
145
151
|
start_time,
|
|
146
152
|
serialized: chain,
|
|
@@ -158,8 +164,9 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
158
164
|
extra: metadata ? { metadata } : {},
|
|
159
165
|
tags: tags || [],
|
|
160
166
|
};
|
|
161
|
-
this._startTrace(run);
|
|
167
|
+
await this._startTrace(run);
|
|
162
168
|
await this.onChainStart?.(run);
|
|
169
|
+
return run;
|
|
163
170
|
}
|
|
164
171
|
async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) {
|
|
165
172
|
const run = this.runMap.get(runId);
|
|
@@ -177,6 +184,7 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
177
184
|
}
|
|
178
185
|
await this.onChainEnd?.(run);
|
|
179
186
|
await this._endTrace(run);
|
|
187
|
+
return run;
|
|
180
188
|
}
|
|
181
189
|
async handleChainError(error, runId, _parentRunId, _tags, kwargs) {
|
|
182
190
|
const run = this.runMap.get(runId);
|
|
@@ -194,13 +202,14 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
194
202
|
}
|
|
195
203
|
await this.onChainError?.(run);
|
|
196
204
|
await this._endTrace(run);
|
|
205
|
+
return run;
|
|
197
206
|
}
|
|
198
|
-
async handleToolStart(tool, input, runId, parentRunId, tags, metadata) {
|
|
207
|
+
async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) {
|
|
199
208
|
const execution_order = this._getExecutionOrder(parentRunId);
|
|
200
209
|
const start_time = Date.now();
|
|
201
210
|
const run = {
|
|
202
211
|
id: runId,
|
|
203
|
-
name: tool.id[tool.id.length - 1],
|
|
212
|
+
name: name ?? tool.id[tool.id.length - 1],
|
|
204
213
|
parent_run_id: parentRunId,
|
|
205
214
|
start_time,
|
|
206
215
|
serialized: tool,
|
|
@@ -218,8 +227,9 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
218
227
|
extra: metadata ? { metadata } : {},
|
|
219
228
|
tags: tags || [],
|
|
220
229
|
};
|
|
221
|
-
this._startTrace(run);
|
|
230
|
+
await this._startTrace(run);
|
|
222
231
|
await this.onToolStart?.(run);
|
|
232
|
+
return run;
|
|
223
233
|
}
|
|
224
234
|
async handleToolEnd(output, runId) {
|
|
225
235
|
const run = this.runMap.get(runId);
|
|
@@ -234,6 +244,7 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
234
244
|
});
|
|
235
245
|
await this.onToolEnd?.(run);
|
|
236
246
|
await this._endTrace(run);
|
|
247
|
+
return run;
|
|
237
248
|
}
|
|
238
249
|
async handleToolError(error, runId) {
|
|
239
250
|
const run = this.runMap.get(runId);
|
|
@@ -248,6 +259,7 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
248
259
|
});
|
|
249
260
|
await this.onToolError?.(run);
|
|
250
261
|
await this._endTrace(run);
|
|
262
|
+
return run;
|
|
251
263
|
}
|
|
252
264
|
async handleAgentAction(action, runId) {
|
|
253
265
|
const run = this.runMap.get(runId);
|
|
@@ -276,12 +288,12 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
276
288
|
});
|
|
277
289
|
await this.onAgentEnd?.(run);
|
|
278
290
|
}
|
|
279
|
-
async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata) {
|
|
291
|
+
async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) {
|
|
280
292
|
const execution_order = this._getExecutionOrder(parentRunId);
|
|
281
293
|
const start_time = Date.now();
|
|
282
294
|
const run = {
|
|
283
295
|
id: runId,
|
|
284
|
-
name: retriever.id[retriever.id.length - 1],
|
|
296
|
+
name: name ?? retriever.id[retriever.id.length - 1],
|
|
285
297
|
parent_run_id: parentRunId,
|
|
286
298
|
start_time,
|
|
287
299
|
serialized: retriever,
|
|
@@ -299,8 +311,9 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
299
311
|
extra: metadata ? { metadata } : {},
|
|
300
312
|
tags: tags || [],
|
|
301
313
|
};
|
|
302
|
-
this._startTrace(run);
|
|
314
|
+
await this._startTrace(run);
|
|
303
315
|
await this.onRetrieverStart?.(run);
|
|
316
|
+
return run;
|
|
304
317
|
}
|
|
305
318
|
async handleRetrieverEnd(documents, runId) {
|
|
306
319
|
const run = this.runMap.get(runId);
|
|
@@ -315,6 +328,7 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
315
328
|
});
|
|
316
329
|
await this.onRetrieverEnd?.(run);
|
|
317
330
|
await this._endTrace(run);
|
|
331
|
+
return run;
|
|
318
332
|
}
|
|
319
333
|
async handleRetrieverError(error, runId) {
|
|
320
334
|
const run = this.runMap.get(runId);
|
|
@@ -329,6 +343,7 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
329
343
|
});
|
|
330
344
|
await this.onRetrieverError?.(run);
|
|
331
345
|
await this._endTrace(run);
|
|
346
|
+
return run;
|
|
332
347
|
}
|
|
333
348
|
async handleText(text, runId) {
|
|
334
349
|
const run = this.runMap.get(runId);
|
|
@@ -345,13 +360,14 @@ export class BaseTracer extends BaseCallbackHandler {
|
|
|
345
360
|
async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) {
|
|
346
361
|
const run = this.runMap.get(runId);
|
|
347
362
|
if (!run || run?.run_type !== "llm") {
|
|
348
|
-
|
|
363
|
+
throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`);
|
|
349
364
|
}
|
|
350
365
|
run.events.push({
|
|
351
366
|
name: "new_token",
|
|
352
367
|
time: new Date().toISOString(),
|
|
353
368
|
kwargs: { token, idx, chunk: fields?.chunk },
|
|
354
369
|
});
|
|
355
|
-
await this.onLLMNewToken?.(run);
|
|
370
|
+
await this.onLLMNewToken?.(run, token);
|
|
371
|
+
return run;
|
|
356
372
|
}
|
|
357
373
|
}
|
|
@@ -94,33 +94,18 @@ class BaseChatModel extends index_js_2.BaseLanguageModel {
|
|
|
94
94
|
})));
|
|
95
95
|
}
|
|
96
96
|
}
|
|
97
|
-
/**
|
|
98
|
-
|
|
99
|
-
* @param messages An array of arrays of BaseMessage instances.
|
|
100
|
-
* @param options The call options or an array of stop sequences.
|
|
101
|
-
* @param callbacks The callbacks for the language model.
|
|
102
|
-
* @returns A Promise that resolves to an LLMResult.
|
|
103
|
-
*/
|
|
104
|
-
async generate(messages, options, callbacks) {
|
|
105
|
-
// parse call options
|
|
106
|
-
let parsedOptions;
|
|
107
|
-
if (Array.isArray(options)) {
|
|
108
|
-
parsedOptions = { stop: options };
|
|
109
|
-
}
|
|
110
|
-
else {
|
|
111
|
-
parsedOptions = options;
|
|
112
|
-
}
|
|
97
|
+
/** @ignore */
|
|
98
|
+
async _generateUncached(messages, parsedOptions, handledOptions) {
|
|
113
99
|
const baseMessages = messages.map((messageList) => messageList.map(index_js_1.coerceMessageLikeToMessage));
|
|
114
|
-
const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions);
|
|
115
100
|
// create callback manager and start run
|
|
116
|
-
const callbackManager_ = await manager_js_1.CallbackManager.configure(
|
|
101
|
+
const callbackManager_ = await manager_js_1.CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose });
|
|
117
102
|
const extra = {
|
|
118
|
-
options:
|
|
103
|
+
options: parsedOptions,
|
|
119
104
|
invocation_params: this?.invocationParams(parsedOptions),
|
|
120
105
|
};
|
|
121
106
|
const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages, undefined, undefined, extra);
|
|
122
107
|
// generate results
|
|
123
|
-
const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...
|
|
108
|
+
const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...parsedOptions, promptIndex: i }, runManagers?.[i])));
|
|
124
109
|
// handle results
|
|
125
110
|
const generations = [];
|
|
126
111
|
const llmOutputs = [];
|
|
@@ -155,6 +140,54 @@ class BaseChatModel extends index_js_2.BaseLanguageModel {
|
|
|
155
140
|
});
|
|
156
141
|
return output;
|
|
157
142
|
}
|
|
143
|
+
/**
|
|
144
|
+
* Generates chat based on the input messages.
|
|
145
|
+
* @param messages An array of arrays of BaseMessage instances.
|
|
146
|
+
* @param options The call options or an array of stop sequences.
|
|
147
|
+
* @param callbacks The callbacks for the language model.
|
|
148
|
+
* @returns A Promise that resolves to an LLMResult.
|
|
149
|
+
*/
|
|
150
|
+
async generate(messages, options, callbacks) {
|
|
151
|
+
// parse call options
|
|
152
|
+
let parsedOptions;
|
|
153
|
+
if (Array.isArray(options)) {
|
|
154
|
+
parsedOptions = { stop: options };
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
parsedOptions = options;
|
|
158
|
+
}
|
|
159
|
+
const baseMessages = messages.map((messageList) => messageList.map(index_js_1.coerceMessageLikeToMessage));
|
|
160
|
+
const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions);
|
|
161
|
+
runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks;
|
|
162
|
+
if (!this.cache) {
|
|
163
|
+
return this._generateUncached(baseMessages, callOptions, runnableConfig);
|
|
164
|
+
}
|
|
165
|
+
const { cache } = this;
|
|
166
|
+
const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions);
|
|
167
|
+
const missingPromptIndices = [];
|
|
168
|
+
const generations = await Promise.all(baseMessages.map(async (baseMessage, index) => {
|
|
169
|
+
// Join all content into one string for the prompt index
|
|
170
|
+
const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString();
|
|
171
|
+
const result = await cache.lookup(prompt, llmStringKey);
|
|
172
|
+
if (!result) {
|
|
173
|
+
missingPromptIndices.push(index);
|
|
174
|
+
}
|
|
175
|
+
return result;
|
|
176
|
+
}));
|
|
177
|
+
let llmOutput = {};
|
|
178
|
+
if (missingPromptIndices.length > 0) {
|
|
179
|
+
const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig);
|
|
180
|
+
await Promise.all(results.generations.map(async (generation, index) => {
|
|
181
|
+
const promptIndex = missingPromptIndices[index];
|
|
182
|
+
generations[promptIndex] = generation;
|
|
183
|
+
// Join all content into one string for the prompt index
|
|
184
|
+
const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString();
|
|
185
|
+
return cache.update(prompt, llmStringKey, generation);
|
|
186
|
+
}));
|
|
187
|
+
llmOutput = results.llmOutput ?? {};
|
|
188
|
+
}
|
|
189
|
+
return { generations, llmOutput };
|
|
190
|
+
}
|
|
158
191
|
/**
|
|
159
192
|
* Get the parameters used to invoke the model
|
|
160
193
|
*/
|
|
@@ -165,6 +198,17 @@ class BaseChatModel extends index_js_2.BaseLanguageModel {
|
|
|
165
198
|
_modelType() {
|
|
166
199
|
return "base_chat_model";
|
|
167
200
|
}
|
|
201
|
+
/**
|
|
202
|
+
* @deprecated
|
|
203
|
+
* Return a json-like object representing this LLM.
|
|
204
|
+
*/
|
|
205
|
+
serialize() {
|
|
206
|
+
return {
|
|
207
|
+
...this.invocationParams(),
|
|
208
|
+
_type: this._llmType(),
|
|
209
|
+
_model: this._modelType(),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
168
212
|
/**
|
|
169
213
|
* Generates a prompt based on the input prompt values.
|
|
170
214
|
* @param promptValues An array of BasePromptValue instances.
|
|
@@ -49,6 +49,8 @@ export declare abstract class BaseChatModel<CallOptions extends BaseChatModelCal
|
|
|
49
49
|
invoke(input: BaseLanguageModelInput, options?: CallOptions): Promise<BaseMessageChunk>;
|
|
50
50
|
_streamResponseChunks(_messages: BaseMessage[], _options: this["ParsedCallOptions"], _runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
|
|
51
51
|
_streamIterator(input: BaseLanguageModelInput, options?: CallOptions): AsyncGenerator<BaseMessageChunk>;
|
|
52
|
+
/** @ignore */
|
|
53
|
+
_generateUncached(messages: BaseMessageLike[][], parsedOptions: this["ParsedCallOptions"], handledOptions: RunnableConfig): Promise<LLMResult>;
|
|
52
54
|
/**
|
|
53
55
|
* Generates chat based on the input messages.
|
|
54
56
|
* @param messages An array of arrays of BaseMessage instances.
|
|
@@ -63,6 +65,11 @@ export declare abstract class BaseChatModel<CallOptions extends BaseChatModelCal
|
|
|
63
65
|
invocationParams(_options?: this["ParsedCallOptions"]): any;
|
|
64
66
|
_modelType(): string;
|
|
65
67
|
abstract _llmType(): string;
|
|
68
|
+
/**
|
|
69
|
+
* @deprecated
|
|
70
|
+
* Return a json-like object representing this LLM.
|
|
71
|
+
*/
|
|
72
|
+
serialize(): SerializedLLM;
|
|
66
73
|
/**
|
|
67
74
|
* Generates a prompt based on the input prompt values.
|
|
68
75
|
* @param promptValues An array of BasePromptValue instances.
|
package/dist/chat_models/base.js
CHANGED
|
@@ -90,33 +90,18 @@ export class BaseChatModel extends BaseLanguageModel {
|
|
|
90
90
|
})));
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
|
-
/**
|
|
94
|
-
|
|
95
|
-
* @param messages An array of arrays of BaseMessage instances.
|
|
96
|
-
* @param options The call options or an array of stop sequences.
|
|
97
|
-
* @param callbacks The callbacks for the language model.
|
|
98
|
-
* @returns A Promise that resolves to an LLMResult.
|
|
99
|
-
*/
|
|
100
|
-
async generate(messages, options, callbacks) {
|
|
101
|
-
// parse call options
|
|
102
|
-
let parsedOptions;
|
|
103
|
-
if (Array.isArray(options)) {
|
|
104
|
-
parsedOptions = { stop: options };
|
|
105
|
-
}
|
|
106
|
-
else {
|
|
107
|
-
parsedOptions = options;
|
|
108
|
-
}
|
|
93
|
+
/** @ignore */
|
|
94
|
+
async _generateUncached(messages, parsedOptions, handledOptions) {
|
|
109
95
|
const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage));
|
|
110
|
-
const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions);
|
|
111
96
|
// create callback manager and start run
|
|
112
|
-
const callbackManager_ = await CallbackManager.configure(
|
|
97
|
+
const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose });
|
|
113
98
|
const extra = {
|
|
114
|
-
options:
|
|
99
|
+
options: parsedOptions,
|
|
115
100
|
invocation_params: this?.invocationParams(parsedOptions),
|
|
116
101
|
};
|
|
117
102
|
const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages, undefined, undefined, extra);
|
|
118
103
|
// generate results
|
|
119
|
-
const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...
|
|
104
|
+
const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...parsedOptions, promptIndex: i }, runManagers?.[i])));
|
|
120
105
|
// handle results
|
|
121
106
|
const generations = [];
|
|
122
107
|
const llmOutputs = [];
|
|
@@ -151,6 +136,54 @@ export class BaseChatModel extends BaseLanguageModel {
|
|
|
151
136
|
});
|
|
152
137
|
return output;
|
|
153
138
|
}
|
|
139
|
+
/**
|
|
140
|
+
* Generates chat based on the input messages.
|
|
141
|
+
* @param messages An array of arrays of BaseMessage instances.
|
|
142
|
+
* @param options The call options or an array of stop sequences.
|
|
143
|
+
* @param callbacks The callbacks for the language model.
|
|
144
|
+
* @returns A Promise that resolves to an LLMResult.
|
|
145
|
+
*/
|
|
146
|
+
async generate(messages, options, callbacks) {
|
|
147
|
+
// parse call options
|
|
148
|
+
let parsedOptions;
|
|
149
|
+
if (Array.isArray(options)) {
|
|
150
|
+
parsedOptions = { stop: options };
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
parsedOptions = options;
|
|
154
|
+
}
|
|
155
|
+
const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage));
|
|
156
|
+
const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions);
|
|
157
|
+
runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks;
|
|
158
|
+
if (!this.cache) {
|
|
159
|
+
return this._generateUncached(baseMessages, callOptions, runnableConfig);
|
|
160
|
+
}
|
|
161
|
+
const { cache } = this;
|
|
162
|
+
const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions);
|
|
163
|
+
const missingPromptIndices = [];
|
|
164
|
+
const generations = await Promise.all(baseMessages.map(async (baseMessage, index) => {
|
|
165
|
+
// Join all content into one string for the prompt index
|
|
166
|
+
const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString();
|
|
167
|
+
const result = await cache.lookup(prompt, llmStringKey);
|
|
168
|
+
if (!result) {
|
|
169
|
+
missingPromptIndices.push(index);
|
|
170
|
+
}
|
|
171
|
+
return result;
|
|
172
|
+
}));
|
|
173
|
+
let llmOutput = {};
|
|
174
|
+
if (missingPromptIndices.length > 0) {
|
|
175
|
+
const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig);
|
|
176
|
+
await Promise.all(results.generations.map(async (generation, index) => {
|
|
177
|
+
const promptIndex = missingPromptIndices[index];
|
|
178
|
+
generations[promptIndex] = generation;
|
|
179
|
+
// Join all content into one string for the prompt index
|
|
180
|
+
const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString();
|
|
181
|
+
return cache.update(prompt, llmStringKey, generation);
|
|
182
|
+
}));
|
|
183
|
+
llmOutput = results.llmOutput ?? {};
|
|
184
|
+
}
|
|
185
|
+
return { generations, llmOutput };
|
|
186
|
+
}
|
|
154
187
|
/**
|
|
155
188
|
* Get the parameters used to invoke the model
|
|
156
189
|
*/
|
|
@@ -161,6 +194,17 @@ export class BaseChatModel extends BaseLanguageModel {
|
|
|
161
194
|
_modelType() {
|
|
162
195
|
return "base_chat_model";
|
|
163
196
|
}
|
|
197
|
+
/**
|
|
198
|
+
* @deprecated
|
|
199
|
+
* Return a json-like object representing this LLM.
|
|
200
|
+
*/
|
|
201
|
+
serialize() {
|
|
202
|
+
return {
|
|
203
|
+
...this.invocationParams(),
|
|
204
|
+
_type: this._llmType(),
|
|
205
|
+
_model: this._modelType(),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
164
208
|
/**
|
|
165
209
|
* Generates a prompt based on the input prompt values.
|
|
166
210
|
* @param promptValues An array of BasePromptValue instances.
|
|
@@ -119,11 +119,15 @@ class NotionAPILoader extends base_js_1.BaseDocumentLoader {
|
|
|
119
119
|
* @returns The string of the title.
|
|
120
120
|
*/
|
|
121
121
|
getTitle(obj) {
|
|
122
|
-
if ((0, exports.isPage)(obj)
|
|
123
|
-
|
|
122
|
+
if ((0, exports.isPage)(obj)) {
|
|
123
|
+
const titleProp = Object.values(obj.properties).find((prop) => prop.type === "title");
|
|
124
|
+
if (titleProp)
|
|
125
|
+
return this.getPropValue(titleProp);
|
|
124
126
|
}
|
|
125
127
|
if ((0, exports.isDatabase)(obj))
|
|
126
|
-
return obj.title
|
|
128
|
+
return obj.title
|
|
129
|
+
.map((v) => this.n2mClient.annotatePlainText(v.plain_text, v.annotations))
|
|
130
|
+
.join("");
|
|
127
131
|
return null;
|
|
128
132
|
}
|
|
129
133
|
/**
|
|
@@ -284,7 +288,7 @@ class NotionAPILoader extends base_js_1.BaseDocumentLoader {
|
|
|
284
288
|
});
|
|
285
289
|
this.documents.push(pageDocument);
|
|
286
290
|
this.pageCompleted.push(pageId);
|
|
287
|
-
this.onDocumentLoaded(this.documents.length, this.pageQueueTotal,
|
|
291
|
+
this.onDocumentLoaded(this.documents.length, this.pageQueueTotal, this.getTitle(pageDetails) || undefined, this.rootTitle);
|
|
288
292
|
}
|
|
289
293
|
/**
|
|
290
294
|
* Loads a Notion database and adds it's pages to the queue.
|
|
@@ -111,11 +111,15 @@ export class NotionAPILoader extends BaseDocumentLoader {
|
|
|
111
111
|
* @returns The string of the title.
|
|
112
112
|
*/
|
|
113
113
|
getTitle(obj) {
|
|
114
|
-
if (isPage(obj)
|
|
115
|
-
|
|
114
|
+
if (isPage(obj)) {
|
|
115
|
+
const titleProp = Object.values(obj.properties).find((prop) => prop.type === "title");
|
|
116
|
+
if (titleProp)
|
|
117
|
+
return this.getPropValue(titleProp);
|
|
116
118
|
}
|
|
117
119
|
if (isDatabase(obj))
|
|
118
|
-
return obj.title
|
|
120
|
+
return obj.title
|
|
121
|
+
.map((v) => this.n2mClient.annotatePlainText(v.plain_text, v.annotations))
|
|
122
|
+
.join("");
|
|
119
123
|
return null;
|
|
120
124
|
}
|
|
121
125
|
/**
|
|
@@ -276,7 +280,7 @@ export class NotionAPILoader extends BaseDocumentLoader {
|
|
|
276
280
|
});
|
|
277
281
|
this.documents.push(pageDocument);
|
|
278
282
|
this.pageCompleted.push(pageId);
|
|
279
|
-
this.onDocumentLoaded(this.documents.length, this.pageQueueTotal,
|
|
283
|
+
this.onDocumentLoaded(this.documents.length, this.pageQueueTotal, this.getTitle(pageDetails) || undefined, this.rootTitle);
|
|
280
284
|
}
|
|
281
285
|
/**
|
|
282
286
|
* Loads a Notion database and adds it's pages to the queue.
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SearchApiLoader = void 0;
|
|
4
|
+
const env_js_1 = require("../../util/env.cjs");
|
|
5
|
+
const document_js_1 = require("../../document.cjs");
|
|
6
|
+
const base_js_1 = require("../base.cjs");
|
|
7
|
+
/**
|
|
8
|
+
* Class representing a document loader for loading search results from
|
|
9
|
+
* the SearchApi. It extends the BaseDocumentLoader class.
|
|
10
|
+
*/
|
|
11
|
+
class SearchApiLoader extends base_js_1.BaseDocumentLoader {
|
|
12
|
+
constructor(params) {
|
|
13
|
+
super();
|
|
14
|
+
Object.defineProperty(this, "apiKey", {
|
|
15
|
+
enumerable: true,
|
|
16
|
+
configurable: true,
|
|
17
|
+
writable: true,
|
|
18
|
+
value: void 0
|
|
19
|
+
});
|
|
20
|
+
Object.defineProperty(this, "parameters", {
|
|
21
|
+
enumerable: true,
|
|
22
|
+
configurable: true,
|
|
23
|
+
writable: true,
|
|
24
|
+
value: void 0
|
|
25
|
+
});
|
|
26
|
+
const { apiKey = (0, env_js_1.getEnvironmentVariable)("SEARCHAPI_API_KEY") } = params;
|
|
27
|
+
if (typeof apiKey !== "string") {
|
|
28
|
+
throw new Error("Invalid type for apiKey. Expected string.");
|
|
29
|
+
}
|
|
30
|
+
if (!apiKey) {
|
|
31
|
+
throw new Error("SearchApi API key not set. You can set it as SEARCHAPI_API_KEY in your .env file, or pass it to SearchApi.");
|
|
32
|
+
}
|
|
33
|
+
this.apiKey = apiKey;
|
|
34
|
+
this.parameters = { ...params };
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Builds the URL for the SearchApi search request.
|
|
38
|
+
* @returns The URL for the search request.
|
|
39
|
+
*/
|
|
40
|
+
buildUrl() {
|
|
41
|
+
this.parameters = {
|
|
42
|
+
engine: "google",
|
|
43
|
+
api_key: this.apiKey,
|
|
44
|
+
...this.parameters,
|
|
45
|
+
};
|
|
46
|
+
const preparedParams = Object.entries(this.parameters)
|
|
47
|
+
.filter(([key, value]) => value !== undefined && value !== null && key !== "apiKey")
|
|
48
|
+
.map(([key, value]) => [key, `${value}`]);
|
|
49
|
+
const searchParams = new URLSearchParams(preparedParams);
|
|
50
|
+
return `https://www.searchapi.io/api/v1/search?${searchParams}`;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Extracts documents from the provided output.
|
|
54
|
+
* @param output - The output to extract documents from.
|
|
55
|
+
* @param responseType - The type of the response to extract documents from.
|
|
56
|
+
* @returns An array of Documents.
|
|
57
|
+
*/
|
|
58
|
+
extractDocuments(output, responseType) {
|
|
59
|
+
const documents = [];
|
|
60
|
+
const results = Array.isArray(output) ? output : [output];
|
|
61
|
+
if (responseType === "transcripts") {
|
|
62
|
+
const pageContent = results.map((result) => result.text).join("\n");
|
|
63
|
+
const metadata = {
|
|
64
|
+
source: "SearchApi",
|
|
65
|
+
responseType,
|
|
66
|
+
};
|
|
67
|
+
documents.push(new document_js_1.Document({ pageContent, metadata }));
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
for (const result of results) {
|
|
71
|
+
const pageContent = JSON.stringify(result);
|
|
72
|
+
const metadata = {
|
|
73
|
+
source: "SearchApi",
|
|
74
|
+
responseType,
|
|
75
|
+
};
|
|
76
|
+
documents.push(new document_js_1.Document({ pageContent, metadata }));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return documents;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Processes the response data from the SearchApi search request and converts it into an array of Documents.
|
|
83
|
+
* @param data - The response data from the SearchApi search request.
|
|
84
|
+
* @returns An array of Documents.
|
|
85
|
+
*/
|
|
86
|
+
processResponseData(data) {
|
|
87
|
+
const documents = [];
|
|
88
|
+
const responseTypes = [
|
|
89
|
+
"answer_box",
|
|
90
|
+
"shopping_results",
|
|
91
|
+
"knowledge_graph",
|
|
92
|
+
"organic_results",
|
|
93
|
+
"transcripts",
|
|
94
|
+
];
|
|
95
|
+
for (const responseType of responseTypes) {
|
|
96
|
+
if (responseType in data) {
|
|
97
|
+
documents.push(...this.extractDocuments(data[responseType], responseType));
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return documents;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Fetches the data from the provided URL and returns it as a JSON object.
|
|
104
|
+
* If an error occurs during the fetch operation, an exception is thrown with the error message.
|
|
105
|
+
* @param url - The URL to fetch data from.
|
|
106
|
+
* @returns A promise that resolves to the fetched data as a JSON object.
|
|
107
|
+
* @throws An error if the fetch operation fails.
|
|
108
|
+
*/
|
|
109
|
+
async fetchData(url) {
|
|
110
|
+
const response = await fetch(url);
|
|
111
|
+
const data = await response.json();
|
|
112
|
+
if (data.error) {
|
|
113
|
+
throw new Error(`Failed to load search results from SearchApi due to: ${data.error}`);
|
|
114
|
+
}
|
|
115
|
+
return data;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Loads the search results from the SearchApi.
|
|
119
|
+
* @returns An array of Documents representing the search results.
|
|
120
|
+
* @throws An error if the search results could not be loaded.
|
|
121
|
+
*/
|
|
122
|
+
async load() {
|
|
123
|
+
const url = this.buildUrl();
|
|
124
|
+
const data = await this.fetchData(url);
|
|
125
|
+
try {
|
|
126
|
+
return this.processResponseData(data);
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
console.error(error);
|
|
130
|
+
throw new Error(`Failed to process search results from SearchApi: ${error}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
exports.SearchApiLoader = SearchApiLoader;
|