-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
llm_chain.ts
287 lines (261 loc) Β· 7.91 KB
/
llm_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
import {
BaseLanguageModel,
BaseLanguageModelInterface,
BaseLanguageModelInput,
} from "@langchain/core/language_models/base";
import type { ChainValues } from "@langchain/core/utils/types";
import type { Generation } from "@langchain/core/outputs";
import type { BaseMessage } from "@langchain/core/messages";
import type { BasePromptValueInterface } from "@langchain/core/prompt_values";
import { BasePromptTemplate } from "@langchain/core/prompts";
import {
BaseLLMOutputParser,
BaseOutputParser,
} from "@langchain/core/output_parsers";
import {
CallbackManager,
BaseCallbackConfig,
CallbackManagerForChainRun,
Callbacks,
} from "@langchain/core/callbacks/manager";
import { Runnable, type RunnableInterface } from "@langchain/core/runnables";
import { BaseChain, ChainInputs } from "./base.js";
import { SerializedLLMChain } from "./serde.js";
import { NoOpOutputParser } from "../output_parsers/noop.js";
type LLMType =
| BaseLanguageModelInterface
| Runnable<BaseLanguageModelInput, string>
| Runnable<BaseLanguageModelInput, BaseMessage>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type CallOptionsIfAvailable<T> = T extends { CallOptions: infer CO } ? CO : any;
/**
* Interface for the input parameters of the LLMChain class.
*/
export interface LLMChainInput<
T extends string | object = string,
Model extends LLMType = LLMType
> extends ChainInputs {
/** Prompt object to use */
prompt: BasePromptTemplate;
/** LLM Wrapper to use */
llm: Model;
/** Kwargs to pass to LLM */
llmKwargs?: CallOptionsIfAvailable<Model>;
/** OutputParser to use */
outputParser?: BaseLLMOutputParser<T>;
/** Key to use for output, defaults to `text` */
outputKey?: string;
}
function isBaseLanguageModel(llmLike: unknown): llmLike is BaseLanguageModel {
return typeof (llmLike as BaseLanguageModelInterface)._llmType === "function";
}
function _getLanguageModel(llmLike: RunnableInterface): BaseLanguageModel {
if (isBaseLanguageModel(llmLike)) {
return llmLike;
} else if ("bound" in llmLike && Runnable.isRunnable(llmLike.bound)) {
return _getLanguageModel(llmLike.bound);
} else if (
"runnable" in llmLike &&
"fallbacks" in llmLike &&
Runnable.isRunnable(llmLike.runnable)
) {
return _getLanguageModel(llmLike.runnable);
} else if ("default" in llmLike && Runnable.isRunnable(llmLike.default)) {
return _getLanguageModel(llmLike.default);
} else {
throw new Error("Unable to extract BaseLanguageModel from llmLike object.");
}
}
/**
* @deprecated This class will be removed in 0.3.0. Use the LangChain Expression Language (LCEL) instead.
* See the example below for how to use LCEL with the LLMChain class:
*
* Chain to run queries against LLMs.
*
* @example
* ```ts
* import { ChatPromptTemplate } from "@langchain/core/prompts";
* import { ChatOpenAI } from "@langchain/openai";
*
* const prompt = ChatPromptTemplate.fromTemplate("Tell me a {adjective} joke");
* const llm = new ChatOpenAI();
* const chain = prompt.pipe(llm);
*
* const response = await chain.invoke({ adjective: "funny" });
* ```
*/
export class LLMChain<
T extends string | object = string,
Model extends LLMType = LLMType
>
extends BaseChain
implements LLMChainInput<T>
{
static lc_name() {
return "LLMChain";
}
lc_serializable = true;
prompt: BasePromptTemplate;
llm: Model;
llmKwargs?: CallOptionsIfAvailable<Model>;
outputKey = "text";
outputParser?: BaseLLMOutputParser<T>;
get inputKeys() {
return this.prompt.inputVariables;
}
get outputKeys() {
return [this.outputKey];
}
constructor(fields: LLMChainInput<T, Model>) {
super(fields);
this.prompt = fields.prompt;
this.llm = fields.llm;
this.llmKwargs = fields.llmKwargs;
this.outputKey = fields.outputKey ?? this.outputKey;
this.outputParser =
fields.outputParser ?? (new NoOpOutputParser() as BaseOutputParser<T>);
if (this.prompt.outputParser) {
if (fields.outputParser) {
throw new Error("Cannot set both outputParser and prompt.outputParser");
}
this.outputParser = this.prompt.outputParser as BaseOutputParser<T>;
}
}
private getCallKeys(): string[] {
const callKeys = "callKeys" in this.llm ? this.llm.callKeys : [];
return callKeys;
}
/** @ignore */
_selectMemoryInputs(values: ChainValues): ChainValues {
const valuesForMemory = super._selectMemoryInputs(values);
const callKeys = this.getCallKeys();
for (const key of callKeys) {
if (key in values) {
delete valuesForMemory[key];
}
}
return valuesForMemory;
}
/** @ignore */
async _getFinalOutput(
generations: Generation[],
promptValue: BasePromptValueInterface,
runManager?: CallbackManagerForChainRun
): Promise<unknown> {
let finalCompletion: unknown;
if (this.outputParser) {
finalCompletion = await this.outputParser.parseResultWithPrompt(
generations,
promptValue,
runManager?.getChild()
);
} else {
finalCompletion = generations[0].text;
}
return finalCompletion;
}
/**
* Run the core logic of this chain and add to output if desired.
*
* Wraps _call and handles memory.
*/
call(
values: ChainValues & CallOptionsIfAvailable<Model>,
config?: Callbacks | BaseCallbackConfig
): Promise<ChainValues> {
return super.call(values, config);
}
/** @ignore */
async _call(
values: ChainValues & CallOptionsIfAvailable<Model>,
runManager?: CallbackManagerForChainRun
): Promise<ChainValues> {
const valuesForPrompt = { ...values };
const valuesForLLM = {
...this.llmKwargs,
} as CallOptionsIfAvailable<Model>;
const callKeys = this.getCallKeys();
for (const key of callKeys) {
if (key in values) {
if (valuesForLLM) {
valuesForLLM[key as keyof CallOptionsIfAvailable<Model>] =
values[key];
delete valuesForPrompt[key];
}
}
}
const promptValue = await this.prompt.formatPromptValue(valuesForPrompt);
if ("generatePrompt" in this.llm) {
const { generations } = await this.llm.generatePrompt(
[promptValue],
valuesForLLM,
runManager?.getChild()
);
return {
[this.outputKey]: await this._getFinalOutput(
generations[0],
promptValue,
runManager
),
};
}
const modelWithParser = this.outputParser
? this.llm.pipe(this.outputParser)
: this.llm;
const response = await modelWithParser.invoke(
promptValue,
runManager?.getChild()
);
return {
[this.outputKey]: response,
};
}
/**
* Format prompt with values and pass to LLM
*
* @param values - keys to pass to prompt template
* @param callbackManager - CallbackManager to use
* @returns Completion from LLM.
*
* @example
* ```ts
* llm.predict({ adjective: "funny" })
* ```
*/
async predict(
values: ChainValues & CallOptionsIfAvailable<Model>,
callbackManager?: CallbackManager
): Promise<T> {
const output = await this.call(values, callbackManager);
return output[this.outputKey];
}
_chainType() {
return "llm" as const;
}
static async deserialize(data: SerializedLLMChain) {
const { llm, prompt } = data;
if (!llm) {
throw new Error("LLMChain must have llm");
}
if (!prompt) {
throw new Error("LLMChain must have prompt");
}
return new LLMChain({
llm: await BaseLanguageModel.deserialize(llm),
prompt: await BasePromptTemplate.deserialize(prompt),
});
}
/** @deprecated */
serialize(): SerializedLLMChain {
const serialize =
"serialize" in this.llm ? this.llm.serialize() : undefined;
return {
_type: `${this._chainType()}_chain`,
llm: serialize,
prompt: this.prompt.serialize(),
};
}
_getNumTokens(text: string): Promise<number> {
return _getLanguageModel(this.llm).getNumTokens(text);
}
}