-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
base.ts
319 lines (298 loc) Β· 9.23 KB
/
base.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import { BaseMemory } from "@langchain/core/memory";
import { ChainValues } from "@langchain/core/utils/types";
import { RUN_KEY } from "@langchain/core/outputs";
import {
CallbackManagerForChainRun,
CallbackManager,
Callbacks,
parseCallbackConfigArg,
} from "@langchain/core/callbacks/manager";
import { ensureConfig, type RunnableConfig } from "@langchain/core/runnables";
import {
BaseLangChain,
BaseLangChainParams,
} from "@langchain/core/language_models/base";
import { SerializedBaseChain } from "./serde.js";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type LoadValues = Record<string, any>;
export interface ChainInputs extends BaseLangChainParams {
memory?: BaseMemory;
/**
* @deprecated Use `callbacks` instead
*/
callbackManager?: CallbackManager;
}
/**
* Base interface that all chains must implement.
*/
export abstract class BaseChain<
RunInput extends ChainValues = ChainValues,
RunOutput extends ChainValues = ChainValues
>
extends BaseLangChain<RunInput, RunOutput>
implements ChainInputs
{
declare memory?: BaseMemory;
get lc_namespace(): string[] {
return ["langchain", "chains", this._chainType()];
}
constructor(
fields?: BaseMemory | ChainInputs,
/** @deprecated */
verbose?: boolean,
/** @deprecated */
callbacks?: Callbacks
) {
if (
arguments.length === 1 &&
typeof fields === "object" &&
!("saveContext" in fields)
) {
// fields is not a BaseMemory
const { memory, callbackManager, ...rest } = fields;
super({ ...rest, callbacks: callbackManager ?? rest.callbacks });
this.memory = memory;
} else {
// fields is a BaseMemory
super({ verbose, callbacks });
this.memory = fields as BaseMemory;
}
}
/** @ignore */
_selectMemoryInputs(values: ChainValues): ChainValues {
const valuesForMemory = { ...values };
if ("signal" in valuesForMemory) {
delete valuesForMemory.signal;
}
if ("timeout" in valuesForMemory) {
delete valuesForMemory.timeout;
}
return valuesForMemory;
}
/**
* Invoke the chain with the provided input and returns the output.
* @param input Input values for the chain run.
* @param config Optional configuration for the Runnable.
* @returns Promise that resolves with the output of the chain run.
*/
async invoke(input: RunInput, options?: RunnableConfig): Promise<RunOutput> {
const config = ensureConfig(options);
const fullValues = await this._formatValues(input);
const callbackManager_ = await CallbackManager.configure(
config?.callbacks,
this.callbacks,
config?.tags,
this.tags,
config?.metadata,
this.metadata,
{ verbose: this.verbose }
);
const runManager = await callbackManager_?.handleChainStart(
this.toJSON(),
fullValues,
undefined,
undefined,
undefined,
undefined,
config?.runName
);
let outputValues: RunOutput;
try {
outputValues = await (fullValues.signal
? (Promise.race([
this._call(fullValues as RunInput, runManager, config),
new Promise((_, reject) => {
fullValues.signal?.addEventListener("abort", () => {
reject(new Error("AbortError"));
});
}),
]) as Promise<RunOutput>)
: this._call(fullValues as RunInput, runManager, config));
} catch (e) {
await runManager?.handleChainError(e);
throw e;
}
if (!(this.memory == null)) {
await this.memory.saveContext(
this._selectMemoryInputs(input),
outputValues
);
}
await runManager?.handleChainEnd(outputValues);
// add the runManager's currentRunId to the outputValues
Object.defineProperty(outputValues, RUN_KEY, {
value: runManager ? { runId: runManager?.runId } : undefined,
configurable: true,
});
return outputValues;
}
private _validateOutputs(outputs: Record<string, unknown>): void {
const missingKeys = this.outputKeys.filter((k) => !(k in outputs));
if (missingKeys.length) {
throw new Error(
`Missing output keys: ${missingKeys.join(
", "
)} from chain ${this._chainType()}`
);
}
}
async prepOutputs(
inputs: Record<string, unknown>,
outputs: Record<string, unknown>,
returnOnlyOutputs = false
) {
this._validateOutputs(outputs);
if (this.memory) {
await this.memory.saveContext(inputs, outputs);
}
if (returnOnlyOutputs) {
return outputs;
}
return { ...inputs, ...outputs };
}
/**
* Run the core logic of this chain and return the output
*/
abstract _call(
values: RunInput,
runManager?: CallbackManagerForChainRun,
config?: RunnableConfig
): Promise<RunOutput>;
/**
* Return the string type key uniquely identifying this class of chain.
*/
abstract _chainType(): string;
/**
* Return a json-like object representing this chain.
*/
serialize(): SerializedBaseChain {
throw new Error("Method not implemented.");
}
abstract get inputKeys(): string[];
abstract get outputKeys(): string[];
/** @deprecated Use .invoke() instead. Will be removed in 0.2.0. */
async run(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
input: any,
config?: Callbacks | RunnableConfig
): Promise<string> {
const inputKeys = this.inputKeys.filter(
(k) => !this.memory?.memoryKeys.includes(k) ?? true
);
const isKeylessInput = inputKeys.length <= 1;
if (!isKeylessInput) {
throw new Error(
`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `
);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const values = inputKeys.length ? { [inputKeys[0]]: input } : ({} as any);
const returnValues = await this.call(values, config);
const keys = Object.keys(returnValues);
if (keys.length === 1) {
return returnValues[keys[0]];
}
throw new Error(
"return values have multiple keys, `run` only supported when one key currently"
);
}
protected async _formatValues(
values: ChainValues & { signal?: AbortSignal; timeout?: number }
) {
const fullValues = { ...values } as typeof values;
if (fullValues.timeout && !fullValues.signal) {
fullValues.signal = AbortSignal.timeout(fullValues.timeout);
delete fullValues.timeout;
}
if (!(this.memory == null)) {
const newValues = await this.memory.loadMemoryVariables(
this._selectMemoryInputs(values)
);
for (const [key, value] of Object.entries(newValues)) {
fullValues[key] = value;
}
}
return fullValues;
}
/**
* @deprecated Use .invoke() instead. Will be removed in 0.2.0.
*
* Run the core logic of this chain and add to output if desired.
*
* Wraps _call and handles memory.
*/
async call(
values: ChainValues & { signal?: AbortSignal; timeout?: number },
config?: Callbacks | RunnableConfig,
/** @deprecated */
tags?: string[]
): Promise<RunOutput> {
const parsedConfig = { tags, ...parseCallbackConfigArg(config) };
return this.invoke(values as RunInput, parsedConfig);
}
/**
* @deprecated Use .batch() instead. Will be removed in 0.2.0.
*
* Call the chain on all inputs in the list
*/
async apply(
inputs: RunInput[],
config?: (Callbacks | RunnableConfig)[]
): Promise<RunOutput[]> {
return Promise.all(
inputs.map(async (i, idx) => this.call(i, config?.[idx]))
);
}
/**
* Load a chain from a json-like object describing it.
*/
static async deserialize(
data: SerializedBaseChain,
values: LoadValues = {}
): Promise<BaseChain> {
switch (data._type) {
case "llm_chain": {
const { LLMChain } = await import("./llm_chain.js");
return LLMChain.deserialize(data);
}
case "sequential_chain": {
const { SequentialChain } = await import("./sequential_chain.js");
return SequentialChain.deserialize(data);
}
case "simple_sequential_chain": {
const { SimpleSequentialChain } = await import("./sequential_chain.js");
return SimpleSequentialChain.deserialize(data);
}
case "stuff_documents_chain": {
const { StuffDocumentsChain } = await import("./combine_docs_chain.js");
return StuffDocumentsChain.deserialize(data);
}
case "map_reduce_documents_chain": {
const { MapReduceDocumentsChain } = await import(
"./combine_docs_chain.js"
);
return MapReduceDocumentsChain.deserialize(data);
}
case "refine_documents_chain": {
const { RefineDocumentsChain } = await import(
"./combine_docs_chain.js"
);
return RefineDocumentsChain.deserialize(data);
}
case "vector_db_qa": {
const { VectorDBQAChain } = await import("./vector_db_qa.js");
return VectorDBQAChain.deserialize(data, values);
}
case "api_chain": {
const { APIChain } = await import("./api/api_chain.js");
return APIChain.deserialize(data);
}
default:
throw new Error(
`Invalid prompt type in config: ${
(data as SerializedBaseChain)._type
}`
);
}
}
}