-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
sequential_chain.ts
396 lines (357 loc) Β· 12.3 KB
/
sequential_chain.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import { ChainValues } from "@langchain/core/utils/types";
import { CallbackManagerForChainRun } from "@langchain/core/callbacks/manager";
import { BaseChain, ChainInputs } from "./base.js";
import {
SerializedBaseChain,
SerializedSequentialChain,
SerializedSimpleSequentialChain,
} from "./serde.js";
import { intersection, union, difference } from "../util/set.js";
function formatSet(input: Set<string>) {
return Array.from(input)
.map((i) => `"${i}"`)
.join(", ");
}
/**
* Interface for the input parameters of the SequentialChain class.
*
* @deprecated
* Switch to expression language: https://js.langchain.com/docs/expression_language/
* Will be removed in 0.2.0
*/
export interface SequentialChainInput extends ChainInputs {
/** Array of chains to run as a sequence. The chains are run in order they appear in the array. */
chains: BaseChain[];
/** Defines which variables should be passed as initial input to the first chain. */
inputVariables: string[];
/** Which variables should be returned as a result of executing the chain. If not specified, output of the last of the chains is used. */
outputVariables?: string[];
/** Whether or not to return all intermediate outputs and variables (excluding initial input variables). */
returnAll?: boolean;
}
/**
* Chain where the outputs of one chain feed directly into next.
* @example
* ```typescript
* const promptTemplate = new PromptTemplate({
* template: `You are a playwright. Given the title of play and the era it is set in, it is your job to write a synopsis for that title.
* Title: {title}
* Era: {era}
* Playwright: This is a synopsis for the above play:`,
* inputVariables: ["title", "era"],
* });
* const reviewPromptTemplate = new PromptTemplate({
* template: `You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play.
*
* Play Synopsis:
* {synopsis}
* Review from a New York Times play critic of the above play:`,
* inputVariables: ["synopsis"],
* });
* const overallChain = new SequentialChain({
* chains: [
* new LLMChain({
* llm: new ChatOpenAI({ temperature: 0 }),
* prompt: promptTemplate,
* outputKey: "synopsis",
* }),
* new LLMChain({
* llm: new OpenAI({ temperature: 0 }),
* prompt: reviewPromptTemplate,
* outputKey: "review",
* }),
* ],
* inputVariables: ["era", "title"],
* outputVariables: ["synopsis", "review"],
* verbose: true,
* });
* const chainExecutionResult = await overallChain.call({
* title: "Tragedy at sunset on the beach",
* era: "Victorian England",
* });
* console.log(chainExecutionResult);
* ```
*
* @deprecated
* Switch to {@link https://js.langchain.com/docs/expression_language/ | expression language}.
* Will be removed in 0.2.0
*/
export class SequentialChain extends BaseChain implements SequentialChainInput {
static lc_name() {
return "SequentialChain";
}
chains: BaseChain[];
inputVariables: string[];
outputVariables: string[];
returnAll?: boolean | undefined;
get inputKeys() {
return this.inputVariables;
}
get outputKeys(): string[] {
return this.outputVariables;
}
constructor(fields: SequentialChainInput) {
super(fields);
this.chains = fields.chains;
this.inputVariables = fields.inputVariables;
this.outputVariables = fields.outputVariables ?? [];
if (this.outputVariables.length > 0 && fields.returnAll) {
throw new Error(
"Either specify variables to return using `outputVariables` or use `returnAll` param. Cannot apply both conditions at the same time."
);
}
this.returnAll = fields.returnAll ?? false;
this._validateChains();
}
/** @ignore */
_validateChains() {
if (this.chains.length === 0) {
throw new Error("Sequential chain must have at least one chain.");
}
const memoryKeys = this.memory?.memoryKeys ?? [];
const inputKeysSet = new Set(this.inputKeys);
const memoryKeysSet = new Set(memoryKeys);
const keysIntersection = intersection(inputKeysSet, memoryKeysSet);
if (keysIntersection.size > 0) {
throw new Error(
`The following keys: ${formatSet(
keysIntersection
)} are overlapping between memory and input keys of the chain variables. This can lead to unexpected behaviour. Please use input and memory keys that don't overlap.`
);
}
const availableKeys = union(inputKeysSet, memoryKeysSet);
for (const chain of this.chains) {
let missingKeys = difference(new Set(chain.inputKeys), availableKeys);
if (chain.memory) {
missingKeys = difference(missingKeys, new Set(chain.memory.memoryKeys));
}
if (missingKeys.size > 0) {
throw new Error(
`Missing variables for chain "${chain._chainType()}": ${formatSet(
missingKeys
)}. Only got the following variables: ${formatSet(availableKeys)}.`
);
}
const outputKeysSet = new Set(chain.outputKeys);
const overlappingOutputKeys = intersection(availableKeys, outputKeysSet);
if (overlappingOutputKeys.size > 0) {
throw new Error(
`The following output variables for chain "${chain._chainType()}" are overlapping: ${formatSet(
overlappingOutputKeys
)}. This can lead to unexpected behaviour.`
);
}
for (const outputKey of outputKeysSet) {
availableKeys.add(outputKey);
}
}
if (this.outputVariables.length === 0) {
if (this.returnAll) {
const outputKeys = difference(availableKeys, inputKeysSet);
this.outputVariables = Array.from(outputKeys);
} else {
this.outputVariables = this.chains[this.chains.length - 1].outputKeys;
}
} else {
const missingKeys = difference(
new Set(this.outputVariables),
new Set(availableKeys)
);
if (missingKeys.size > 0) {
throw new Error(
`The following output variables were expected to be in the final chain output but were not found: ${formatSet(
missingKeys
)}.`
);
}
}
}
/** @ignore */
async _call(
values: ChainValues,
runManager?: CallbackManagerForChainRun
): Promise<ChainValues> {
let input: ChainValues = {};
const allChainValues: ChainValues = values;
let i = 0;
for (const chain of this.chains) {
i += 1;
input = await chain.call(
allChainValues,
runManager?.getChild(`step_${i}`)
);
for (const key of Object.keys(input)) {
allChainValues[key] = input[key];
}
}
const output: ChainValues = {};
for (const key of this.outputVariables) {
output[key] = allChainValues[key];
}
return output;
}
_chainType() {
return "sequential_chain" as const;
}
static async deserialize(data: SerializedSequentialChain) {
const chains: BaseChain[] = [];
const inputVariables: string[] = data.input_variables;
const outputVariables: string[] = data.output_variables;
const serializedChains = data.chains;
for (const serializedChain of serializedChains) {
const deserializedChain = await BaseChain.deserialize(serializedChain);
chains.push(deserializedChain);
}
return new SequentialChain({ chains, inputVariables, outputVariables });
}
serialize(): SerializedSequentialChain {
const chains: SerializedBaseChain[] = [];
for (const chain of this.chains) {
chains.push(chain.serialize());
}
return {
_type: this._chainType(),
input_variables: this.inputVariables,
output_variables: this.outputVariables,
chains,
};
}
}
/**
* @deprecated Switch to expression language: https://js.langchain.com/docs/expression_language/
* Interface for the input parameters of the SimpleSequentialChain class.
*/
export interface SimpleSequentialChainInput extends ChainInputs {
/** Array of chains to run as a sequence. The chains are run in order they appear in the array. */
chains: Array<BaseChain>;
/** Whether or not to trim the intermediate outputs. */
trimOutputs?: boolean;
}
/**
* @deprecated Switch to expression language: https://js.langchain.com/docs/expression_language/
* Simple chain where a single string output of one chain is fed directly into the next.
* @augments BaseChain
* @augments SimpleSequentialChainInput
*
* @example
* ```ts
* import { SimpleSequentialChain, LLMChain } from "langchain/chains";
* import { OpenAI } from "langchain/llms/openai";
* import { PromptTemplate } from "langchain/prompts";
*
* // This is an LLMChain to write a synopsis given a title of a play.
* const llm = new OpenAI({ temperature: 0 });
* const template = `You are a playwright. Given the title of play, it is your job to write a synopsis for that title.
*
* Title: {title}
* Playwright: This is a synopsis for the above play:`
* const promptTemplate = new PromptTemplate({ template, inputVariables: ["title"] });
* const synopsisChain = new LLMChain({ llm, prompt: promptTemplate });
*
*
* // This is an LLMChain to write a review of a play given a synopsis.
* const reviewLLM = new OpenAI({ temperature: 0 })
* const reviewTemplate = `You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play.
*
* Play Synopsis:
* {synopsis}
* Review from a New York Times play critic of the above play:`
* const reviewPromptTemplate = new PromptTemplate({ template: reviewTemplate, inputVariables: ["synopsis"] });
* const reviewChain = new LLMChain({ llm: reviewLLM, prompt: reviewPromptTemplate });
*
* const overallChain = new SimpleSequentialChain({chains: [synopsisChain, reviewChain], verbose:true})
* const review = await overallChain.run("Tragedy at sunset on the beach")
* // the variable review contains resulting play review.
* ```
*/
export class SimpleSequentialChain
extends BaseChain
implements SimpleSequentialChainInput
{
static lc_name() {
return "SimpleSequentialChain";
}
chains: Array<BaseChain>;
inputKey = "input";
outputKey = "output";
trimOutputs: boolean;
get inputKeys() {
return [this.inputKey];
}
get outputKeys(): string[] {
return [this.outputKey];
}
constructor(fields: SimpleSequentialChainInput) {
super(fields);
this.chains = fields.chains;
this.trimOutputs = fields.trimOutputs ?? false;
this._validateChains();
}
/** @ignore */
_validateChains() {
for (const chain of this.chains) {
if (
chain.inputKeys.filter(
(k) => !chain.memory?.memoryKeys.includes(k) ?? true
).length !== 1
) {
throw new Error(
`Chains used in SimpleSequentialChain should all have one input, got ${
chain.inputKeys.length
} for ${chain._chainType()}.`
);
}
if (chain.outputKeys.length !== 1) {
throw new Error(
`Chains used in SimpleSequentialChain should all have one output, got ${
chain.outputKeys.length
} for ${chain._chainType()}.`
);
}
}
}
/** @ignore */
async _call(
values: ChainValues,
runManager?: CallbackManagerForChainRun
): Promise<ChainValues> {
let input: string = values[this.inputKey];
let i = 0;
for (const chain of this.chains) {
i += 1;
input = (
await chain.call(
{ [chain.inputKeys[0]]: input, signal: values.signal },
runManager?.getChild(`step_${i}`)
)
)[chain.outputKeys[0]];
if (this.trimOutputs) {
input = input.trim();
}
await runManager?.handleText(input);
}
return { [this.outputKey]: input };
}
_chainType() {
return "simple_sequential_chain" as const;
}
static async deserialize(data: SerializedSimpleSequentialChain) {
const chains: Array<BaseChain> = [];
const serializedChains = data.chains;
for (const serializedChain of serializedChains) {
const deserializedChain = await BaseChain.deserialize(serializedChain);
chains.push(deserializedChain);
}
return new SimpleSequentialChain({ chains });
}
serialize(): SerializedSimpleSequentialChain {
const chains: Array<SerializedBaseChain> = [];
for (const chain of this.chains) {
chains.push(chain.serialize());
}
return {
_type: this._chainType(),
chains,
};
}
}