-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
fake.ts
97 lines (80 loc) · 2.09 KB
/
fake.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
import { GenerationChunk } from "@langchain/core/outputs";
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
import { LLM, BaseLLMParams } from "@langchain/core/language_models/llms";
/**
* Interface for the input parameters specific to the Fake List model.
*/
export interface FakeListInput extends BaseLLMParams {
/** Responses to return */
responses: string[];
/** Time to sleep in milliseconds between responses */
sleep?: number;
}
/**
* A fake LLM that returns a predefined list of responses. It can be used for
* testing purposes.
*/
export class FakeListLLM extends LLM {
static lc_name() {
return "FakeListLLM";
}
responses: string[];
i = 0;
sleep?: number;
constructor({ responses, sleep }: FakeListInput) {
super({});
this.responses = responses;
this.sleep = sleep;
}
_llmType() {
return "fake-list";
}
async _call(
_prompt: string,
_options: this["ParsedCallOptions"],
_runManager?: CallbackManagerForLLMRun
): Promise<string> {
const response = this._currentResponse();
this._incrementResponse();
await this._sleepIfRequested();
return response;
}
_currentResponse() {
return this.responses[this.i];
}
_incrementResponse() {
if (this.i < this.responses.length - 1) {
this.i += 1;
} else {
this.i = 0;
}
}
async *_streamResponseChunks(
_input: string,
_options: this["ParsedCallOptions"],
_runManager?: CallbackManagerForLLMRun
): AsyncGenerator<GenerationChunk> {
const response = this._currentResponse();
this._incrementResponse();
for await (const text of response) {
await this._sleepIfRequested();
yield this._createResponseChunk(text);
}
}
async _sleepIfRequested() {
if (this.sleep !== undefined) {
await this._sleep();
}
}
async _sleep() {
return new Promise<void>((resolve) => {
setTimeout(() => resolve(), this.sleep);
});
}
_createResponseChunk(text: string): GenerationChunk {
return new GenerationChunk({
text,
generationInfo: {},
});
}
}