-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
chat_models.ts
648 lines (602 loc) Β· 19 KB
/
chat_models.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
import {
AIMessage,
type BaseMessage,
BaseMessageChunk,
type BaseMessageLike,
HumanMessage,
coerceMessageLikeToMessage,
} from "../messages/index.js";
import type { BasePromptValueInterface } from "../prompt_values.js";
import {
LLMResult,
RUN_KEY,
type ChatGeneration,
ChatGenerationChunk,
type ChatResult,
type Generation,
} from "../outputs.js";
import {
BaseLanguageModel,
type BaseLanguageModelCallOptions,
type BaseLanguageModelInput,
type BaseLanguageModelParams,
} from "./base.js";
import {
CallbackManager,
type CallbackManagerForLLMRun,
type Callbacks,
} from "../callbacks/manager.js";
import type { RunnableConfig } from "../runnables/config.js";
import type { BaseCache } from "../caches.js";
/**
* Represents a serialized chat model.
*/
export type SerializedChatModel = {
_model: string;
_type: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} & Record<string, any>;
// todo?
/**
* Represents a serialized large language model.
*/
export type SerializedLLM = {
_model: string;
_type: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} & Record<string, any>;
/**
* Represents the parameters for a base chat model.
*/
export type BaseChatModelParams = BaseLanguageModelParams;
/**
* Represents the call options for a base chat model.
*/
export type BaseChatModelCallOptions = BaseLanguageModelCallOptions;
/**
* Creates a transform stream for encoding chat message chunks.
* @deprecated Use {@link BytesOutputParser} instead
* @returns A TransformStream instance that encodes chat message chunks.
*/
export function createChatMessageChunkEncoderStream() {
const textEncoder = new TextEncoder();
return new TransformStream<BaseMessageChunk>({
transform(chunk: BaseMessageChunk, controller) {
controller.enqueue(
textEncoder.encode(
typeof chunk.content === "string"
? chunk.content
: JSON.stringify(chunk.content)
)
);
},
});
}
interface ChatModelGenerateCachedParameters<
T extends BaseChatModel<CallOptions>,
CallOptions extends BaseChatModelCallOptions = BaseChatModelCallOptions
> {
messages: BaseMessageLike[][];
cache: BaseCache<Generation[]>;
llmStringKey: string;
parsedOptions: T["ParsedCallOptions"];
handledOptions: RunnableConfig;
}
/**
* Base class for chat models. It extends the BaseLanguageModel class and
* provides methods for generating chat based on input messages.
*/
export abstract class BaseChatModel<
CallOptions extends BaseChatModelCallOptions = BaseChatModelCallOptions
> extends BaseLanguageModel<BaseMessageChunk, CallOptions> {
declare ParsedCallOptions: Omit<
CallOptions,
keyof RunnableConfig & "timeout"
>;
// Only ever instantiated in main LangChain
lc_namespace = ["langchain", "chat_models", this._llmType()];
constructor(fields: BaseChatModelParams) {
super(fields);
}
_combineLLMOutput?(
...llmOutputs: LLMResult["llmOutput"][]
): LLMResult["llmOutput"];
protected _separateRunnableConfigFromCallOptions(
options?: Partial<CallOptions>
): [RunnableConfig, this["ParsedCallOptions"]] {
const [runnableConfig, callOptions] =
super._separateRunnableConfigFromCallOptions(options);
if (callOptions?.timeout && !callOptions.signal) {
callOptions.signal = AbortSignal.timeout(callOptions.timeout);
}
return [runnableConfig, callOptions as this["ParsedCallOptions"]];
}
/**
* Invokes the chat model with a single input.
* @param input The input for the language model.
* @param options The call options.
* @returns A Promise that resolves to a BaseMessageChunk.
*/
async invoke(
input: BaseLanguageModelInput,
options?: CallOptions
): Promise<BaseMessageChunk> {
const promptValue = BaseChatModel._convertInputToPromptValue(input);
const result = await this.generatePrompt(
[promptValue],
options,
options?.callbacks
);
const chatGeneration = result.generations[0][0] as ChatGeneration;
// TODO: Remove cast after figuring out inheritance
return chatGeneration.message as BaseMessageChunk;
}
// eslint-disable-next-line require-yield
async *_streamResponseChunks(
_messages: BaseMessage[],
_options: this["ParsedCallOptions"],
_runManager?: CallbackManagerForLLMRun
): AsyncGenerator<ChatGenerationChunk> {
throw new Error("Not implemented.");
}
async *_streamIterator(
input: BaseLanguageModelInput,
options?: CallOptions
): AsyncGenerator<BaseMessageChunk> {
// Subclass check required to avoid double callbacks with default implementation
if (
this._streamResponseChunks ===
BaseChatModel.prototype._streamResponseChunks
) {
yield this.invoke(input, options);
} else {
const prompt = BaseChatModel._convertInputToPromptValue(input);
const messages = prompt.toChatMessages();
const [runnableConfig, callOptions] =
this._separateRunnableConfigFromCallOptions(options);
const callbackManager_ = await CallbackManager.configure(
runnableConfig.callbacks,
this.callbacks,
runnableConfig.tags,
this.tags,
runnableConfig.metadata,
this.metadata,
{ verbose: this.verbose }
);
const extra = {
options: callOptions,
invocation_params: this?.invocationParams(callOptions),
batch_size: 1,
};
const runManagers = await callbackManager_?.handleChatModelStart(
this.toJSON(),
[messages],
undefined,
undefined,
extra,
undefined,
undefined,
runnableConfig.runName
);
let generationChunk: ChatGenerationChunk | undefined;
try {
for await (const chunk of this._streamResponseChunks(
messages,
callOptions,
runManagers?.[0]
)) {
yield chunk.message;
if (!generationChunk) {
generationChunk = chunk;
} else {
generationChunk = generationChunk.concat(chunk);
}
}
} catch (err) {
await Promise.all(
(runManagers ?? []).map((runManager) =>
runManager?.handleLLMError(err)
)
);
throw err;
}
await Promise.all(
(runManagers ?? []).map((runManager) =>
runManager?.handleLLMEnd({
// TODO: Remove cast after figuring out inheritance
generations: [[generationChunk as ChatGeneration]],
})
)
);
}
}
/** @ignore */
async _generateUncached(
messages: BaseMessageLike[][],
parsedOptions: this["ParsedCallOptions"],
handledOptions: RunnableConfig
): Promise<LLMResult> {
const baseMessages = messages.map((messageList) =>
messageList.map(coerceMessageLikeToMessage)
);
// create callback manager and start run
const callbackManager_ = await CallbackManager.configure(
handledOptions.callbacks,
this.callbacks,
handledOptions.tags,
this.tags,
handledOptions.metadata,
this.metadata,
{ verbose: this.verbose }
);
const extra = {
options: parsedOptions,
invocation_params: this?.invocationParams(parsedOptions),
batch_size: 1,
};
const runManagers = await callbackManager_?.handleChatModelStart(
this.toJSON(),
baseMessages,
undefined,
undefined,
extra,
undefined,
undefined,
handledOptions.runName
);
// generate results
const results = await Promise.allSettled(
baseMessages.map((messageList, i) =>
this._generate(
messageList,
{ ...parsedOptions, promptIndex: i },
runManagers?.[i]
)
)
);
// handle results
const generations: ChatGeneration[][] = [];
const llmOutputs: LLMResult["llmOutput"][] = [];
await Promise.all(
results.map(async (pResult, i) => {
if (pResult.status === "fulfilled") {
const result = pResult.value;
generations[i] = result.generations;
llmOutputs[i] = result.llmOutput;
return runManagers?.[i]?.handleLLMEnd({
generations: [result.generations],
llmOutput: result.llmOutput,
});
} else {
// status === "rejected"
await runManagers?.[i]?.handleLLMError(pResult.reason);
return Promise.reject(pResult.reason);
}
})
);
// create combined output
const output: LLMResult = {
generations,
llmOutput: llmOutputs.length
? this._combineLLMOutput?.(...llmOutputs)
: undefined,
};
Object.defineProperty(output, RUN_KEY, {
value: runManagers
? { runIds: runManagers?.map((manager) => manager.runId) }
: undefined,
configurable: true,
});
return output;
}
async _generateCached({
messages,
cache,
llmStringKey,
parsedOptions,
handledOptions,
}: ChatModelGenerateCachedParameters<typeof this>): Promise<
LLMResult & { missingPromptIndices: number[] }
> {
const baseMessages = messages.map((messageList) =>
messageList.map(coerceMessageLikeToMessage)
);
// create callback manager and start run
const callbackManager_ = await CallbackManager.configure(
handledOptions.callbacks,
this.callbacks,
handledOptions.tags,
this.tags,
handledOptions.metadata,
this.metadata,
{ verbose: this.verbose }
);
const extra = {
options: parsedOptions,
invocation_params: this?.invocationParams(parsedOptions),
batch_size: 1,
cached: true,
};
const runManagers = await callbackManager_?.handleChatModelStart(
this.toJSON(),
baseMessages,
undefined,
undefined,
extra,
undefined,
undefined,
handledOptions.runName
);
// generate results
const missingPromptIndices: number[] = [];
const results = await Promise.allSettled(
baseMessages.map(async (baseMessage, index) => {
// Join all content into one string for the prompt index
const prompt =
BaseChatModel._convertInputToPromptValue(baseMessage).toString();
const result = await cache.lookup(prompt, llmStringKey);
if (result == null) {
missingPromptIndices.push(index);
}
return result;
})
);
// Map run managers to the results before filtering out null results
// Null results are just absent from the cache.
const cachedResults = results
.map((result, index) => ({ result, runManager: runManagers?.[index] }))
.filter(
({ result }) =>
(result.status === "fulfilled" && result.value != null) ||
result.status === "rejected"
);
// Handle results and call run managers
const generations: Generation[][] = [];
await Promise.all(
cachedResults.map(async ({ result: promiseResult, runManager }, i) => {
if (promiseResult.status === "fulfilled") {
const result = promiseResult.value as Generation[];
generations[i] = result;
if (result.length) {
await runManager?.handleLLMNewToken(result[0].text);
}
return runManager?.handleLLMEnd({
generations: [result],
});
} else {
// status === "rejected"
await runManager?.handleLLMError(promiseResult.reason);
return Promise.reject(promiseResult.reason);
}
})
);
const output = {
generations,
missingPromptIndices,
};
// This defines RUN_KEY as a non-enumerable property on the output object
// so that it is not serialized when the output is stringified, and so that
// it isnt included when listing the keys of the output object.
Object.defineProperty(output, RUN_KEY, {
value: runManagers
? { runIds: runManagers?.map((manager) => manager.runId) }
: undefined,
configurable: true,
});
return output;
}
/**
* Generates chat based on the input messages.
* @param messages An array of arrays of BaseMessage instances.
* @param options The call options or an array of stop sequences.
* @param callbacks The callbacks for the language model.
* @returns A Promise that resolves to an LLMResult.
*/
async generate(
messages: BaseMessageLike[][],
options?: string[] | CallOptions,
callbacks?: Callbacks
): Promise<LLMResult> {
// parse call options
let parsedOptions: CallOptions | undefined;
if (Array.isArray(options)) {
parsedOptions = { stop: options } as CallOptions;
} else {
parsedOptions = options;
}
const baseMessages = messages.map((messageList) =>
messageList.map(coerceMessageLikeToMessage)
);
const [runnableConfig, callOptions] =
this._separateRunnableConfigFromCallOptions(parsedOptions);
runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks;
if (!this.cache) {
return this._generateUncached(baseMessages, callOptions, runnableConfig);
}
const { cache } = this;
const llmStringKey =
this._getSerializedCacheKeyParametersForCall(callOptions);
const { generations, missingPromptIndices } = await this._generateCached({
messages: baseMessages,
cache,
llmStringKey,
parsedOptions: callOptions,
handledOptions: runnableConfig,
});
let llmOutput = {};
if (missingPromptIndices.length > 0) {
const results = await this._generateUncached(
missingPromptIndices.map((i) => baseMessages[i]),
callOptions,
runnableConfig
);
await Promise.all(
results.generations.map(async (generation, index) => {
const promptIndex = missingPromptIndices[index];
generations[promptIndex] = generation;
// Join all content into one string for the prompt index
const prompt = BaseChatModel._convertInputToPromptValue(
baseMessages[promptIndex]
).toString();
return cache.update(prompt, llmStringKey, generation);
})
);
llmOutput = results.llmOutput ?? {};
}
return { generations, llmOutput } as LLMResult;
}
/**
* Get the parameters used to invoke the model
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
invocationParams(_options?: this["ParsedCallOptions"]): any {
return {};
}
_modelType(): string {
return "base_chat_model" as const;
}
abstract _llmType(): string;
/**
* @deprecated
* Return a json-like object representing this LLM.
*/
serialize(): SerializedLLM {
return {
...this.invocationParams(),
_type: this._llmType(),
_model: this._modelType(),
};
}
/**
* Generates a prompt based on the input prompt values.
* @param promptValues An array of BasePromptValue instances.
* @param options The call options or an array of stop sequences.
* @param callbacks The callbacks for the language model.
* @returns A Promise that resolves to an LLMResult.
*/
async generatePrompt(
promptValues: BasePromptValueInterface[],
options?: string[] | CallOptions,
callbacks?: Callbacks
): Promise<LLMResult> {
const promptMessages: BaseMessage[][] = promptValues.map((promptValue) =>
promptValue.toChatMessages()
);
return this.generate(promptMessages, options, callbacks);
}
abstract _generate(
messages: BaseMessage[],
options: this["ParsedCallOptions"],
runManager?: CallbackManagerForLLMRun
): Promise<ChatResult>;
/**
* @deprecated Use .invoke() instead. Will be removed in 0.2.0.
*
* Makes a single call to the chat model.
* @param messages An array of BaseMessage instances.
* @param options The call options or an array of stop sequences.
* @param callbacks The callbacks for the language model.
* @returns A Promise that resolves to a BaseMessage.
*/
async call(
messages: BaseMessageLike[],
options?: string[] | CallOptions,
callbacks?: Callbacks
): Promise<BaseMessage> {
const result = await this.generate(
[messages.map(coerceMessageLikeToMessage)],
options,
callbacks
);
const generations = result.generations as ChatGeneration[][];
return generations[0][0].message;
}
/**
* @deprecated Use .invoke() instead. Will be removed in 0.2.0.
*
* Makes a single call to the chat model with a prompt value.
* @param promptValue The value of the prompt.
* @param options The call options or an array of stop sequences.
* @param callbacks The callbacks for the language model.
* @returns A Promise that resolves to a BaseMessage.
*/
async callPrompt(
promptValue: BasePromptValueInterface,
options?: string[] | CallOptions,
callbacks?: Callbacks
): Promise<BaseMessage> {
const promptMessages: BaseMessage[] = promptValue.toChatMessages();
return this.call(promptMessages, options, callbacks);
}
/**
* @deprecated Use .invoke() instead. Will be removed in 0.2.0.
*
* Predicts the next message based on the input messages.
* @param messages An array of BaseMessage instances.
* @param options The call options or an array of stop sequences.
* @param callbacks The callbacks for the language model.
* @returns A Promise that resolves to a BaseMessage.
*/
async predictMessages(
messages: BaseMessage[],
options?: string[] | CallOptions,
callbacks?: Callbacks
): Promise<BaseMessage> {
return this.call(messages, options, callbacks);
}
/**
* @deprecated Use .invoke() instead. Will be removed in 0.2.0.
*
* Predicts the next message based on a text input.
* @param text The text input.
* @param options The call options or an array of stop sequences.
* @param callbacks The callbacks for the language model.
* @returns A Promise that resolves to a string.
*/
async predict(
text: string,
options?: string[] | CallOptions,
callbacks?: Callbacks
): Promise<string> {
const message = new HumanMessage(text);
const result = await this.call([message], options, callbacks);
if (typeof result.content !== "string") {
throw new Error("Cannot use predict when output is not a string.");
}
return result.content;
}
}
/**
* An abstract class that extends BaseChatModel and provides a simple
* implementation of _generate.
*/
export abstract class SimpleChatModel<
CallOptions extends BaseChatModelCallOptions = BaseChatModelCallOptions
> extends BaseChatModel<CallOptions> {
abstract _call(
messages: BaseMessage[],
options: this["ParsedCallOptions"],
runManager?: CallbackManagerForLLMRun
): Promise<string>;
async _generate(
messages: BaseMessage[],
options: this["ParsedCallOptions"],
runManager?: CallbackManagerForLLMRun
): Promise<ChatResult> {
const text = await this._call(messages, options, runManager);
const message = new AIMessage(text);
if (typeof message.content !== "string") {
throw new Error(
"Cannot generate with a simple chat model when output is not a string."
);
}
return {
generations: [
{
text: message.content,
message,
},
],
};
}
}