-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathrunnable_interface.test.ts
273 lines (229 loc) Β· 7.48 KB
/
runnable_interface.test.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
/* eslint-disable no-promise-executor-return */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { test, expect } from "@jest/globals";
import { StringOutputParser } from "../../output_parsers/string.js";
import { PromptTemplate } from "../../prompts/prompt.js";
import { RunnableSequence } from "../base.js";
type RunnableBatchOptionsV0 = {
maxConcurrency?: number;
returnExceptions?: boolean;
};
interface RunnableInterfaceV0<RunInput, RunOutput, CallOptions = any> {
invoke(input: RunInput, options?: Partial<CallOptions>): Promise<RunOutput>;
batch(
inputs: RunInput[],
options?: Partial<CallOptions> | Partial<CallOptions>[],
batchOptions?: RunnableBatchOptionsV0 & { returnExceptions?: false }
): Promise<RunOutput[]>;
batch(
inputs: RunInput[],
options?: Partial<CallOptions> | Partial<CallOptions>[],
batchOptions?: RunnableBatchOptionsV0 & { returnExceptions: true }
): Promise<(RunOutput | Error)[]>;
batch(
inputs: RunInput[],
options?: Partial<CallOptions> | Partial<CallOptions>[],
batchOptions?: RunnableBatchOptionsV0
): Promise<(RunOutput | Error)[]>;
batch(
inputs: RunInput[],
options?: Partial<CallOptions> | Partial<CallOptions>[],
batchOptions?: RunnableBatchOptionsV0
): Promise<(RunOutput | Error)[]>;
stream(
input: RunInput,
options?: Partial<CallOptions>
): Promise<IterableReadableStreamV0<RunOutput>>;
transform(
generator: AsyncGenerator<RunInput>,
options: Partial<CallOptions>
): AsyncGenerator<RunOutput>;
getName(suffix?: string): string;
get lc_id(): string[];
}
class IterableReadableStreamV0<T> extends ReadableStream<T> {
public reader: ReadableStreamDefaultReader<T>;
ensureReader() {
if (!this.reader) {
this.reader = this.getReader();
}
}
async next() {
this.ensureReader();
try {
const result = await this.reader.read();
if (result.done) this.reader.releaseLock(); // release lock when stream becomes closed
return {
done: result.done,
value: result.value as T, // Cloudflare Workers typing fix
};
} catch (e) {
this.reader.releaseLock(); // release lock when stream becomes errored
throw e;
}
}
async return() {
this.ensureReader();
// If wrapped in a Node stream, cancel is already called.
if (this.locked) {
const cancelPromise = this.reader.cancel(); // cancel first, but don't await yet
this.reader.releaseLock(); // release lock first
await cancelPromise; // now await it
}
return { done: true, value: undefined as T }; // This cast fixes TS typing, and convention is to ignore final chunk value anyway
}
async throw(e: any): Promise<IteratorResult<T>> {
throw e;
}
[Symbol.asyncIterator]() {
return this as any;
}
static fromReadableStream<T>(stream: ReadableStream<T>) {
// From https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams#reading_the_stream
const reader = stream.getReader();
return new IterableReadableStreamV0<T>({
start(controller) {
return pump();
function pump(): Promise<T | undefined> {
return reader.read().then(({ done, value }) => {
// When no more data needs to be consumed, close the stream
if (done) {
controller.close();
return;
}
// Enqueue the next data chunk into our target stream
controller.enqueue(value);
return pump();
});
}
},
cancel() {
reader.releaseLock();
},
});
}
static fromAsyncGenerator<T>(generator: AsyncGenerator<T>) {
return new IterableReadableStreamV0<T>({
async pull(controller) {
const { value, done } = await generator.next();
// When no more data needs to be consumed, close the stream
if (done) {
controller.close();
}
// Fix: `else if (value)` will hang the streaming when nullish value (e.g. empty string) is pulled
controller.enqueue(value);
},
});
}
}
/**
* Base class for all types of messages in a conversation. It includes
* properties like `content`, `name`, and `additional_kwargs`. It also
* includes methods like `toDict()` and `_getType()`.
*/
class AIMessageV0 {
lc_namespace = ["langchain_core", "messages"];
lc_serializable = true;
/** The content of the message. */
content: string;
/** The name of the message sender in a multi-user chat. */
name?: string;
/** The type of the message. */
_getType() {
return "ai";
}
constructor(content: string) {
this.content = content;
}
}
class StringPromptValueV0 {
lc_namespace = ["langchain_core", "prompt_values"];
lc_serializable = true;
value: string;
constructor(value: string) {
this.value = value;
}
toString() {
return this.value;
}
}
class RunnableV0
implements RunnableInterfaceV0<StringPromptValueV0, AIMessageV0>
{
lc_serializable = true;
protected lc_runnable = true;
async invoke(
input: StringPromptValueV0,
_options?: Partial<any> | undefined
): Promise<AIMessageV0> {
return new AIMessageV0(input.toString());
}
async batch(
inputs: StringPromptValueV0[],
options?: Partial<any> | Partial<any>[] | undefined,
batchOptions?:
| (RunnableBatchOptionsV0 & { returnExceptions?: false | undefined })
| undefined
): Promise<AIMessageV0[]>;
async batch(
inputs: StringPromptValueV0[],
options?: Partial<any> | Partial<any>[] | undefined,
batchOptions?:
| (RunnableBatchOptionsV0 & { returnExceptions: true })
| undefined
): Promise<AIMessageV0[]>;
async batch(
inputs: StringPromptValueV0[],
options?: Partial<any> | Partial<any>[] | undefined,
batchOptions?: RunnableBatchOptionsV0 | undefined
): Promise<AIMessageV0[]>;
async batch(
inputs: StringPromptValueV0[],
options?: Partial<any> | Partial<any>[] | undefined,
batchOptions?: RunnableBatchOptionsV0 | undefined
): Promise<AIMessageV0[]>;
async batch(
_inputs: unknown,
_options?: unknown,
_batchOptions?: unknown
): Promise<AIMessageV0[]> {
return [];
}
async stream(
_input: StringPromptValueV0,
_options?: Partial<any> | undefined
): Promise<IterableReadableStreamV0<any>> {
throw new Error("Not implemented");
}
// eslint-disable-next-line require-yield
async *transform(
_generator: AsyncGenerator<StringPromptValueV0>,
_options: Partial<any>
): AsyncGenerator<AIMessageV0> {
throw new Error("Not implemented");
}
getName(): string {
return "TEST";
}
get lc_id(): string[] {
return ["TEST"];
}
}
test("Pipe with a class that implements a runnable interface", async () => {
const promptTemplate = PromptTemplate.fromTemplate("{input}");
const llm = new RunnableV0();
const outputParser = new StringOutputParser();
const runnable = promptTemplate.pipe(llm).pipe(outputParser);
const result = await runnable.invoke({ input: "Hello world!!" });
console.log(result);
expect(result).toBe("Hello world!!");
});
test("Runnable sequence with a class that implements a runnable interface", async () => {
const promptTemplate = PromptTemplate.fromTemplate("{input}");
const llm = new RunnableV0();
const outputParser = new StringOutputParser();
const runnable = RunnableSequence.from([promptTemplate, llm, outputParser]);
const result = await runnable.invoke({ input: "Hello sequence!!" });
console.log(result);
expect(result).toBe("Hello sequence!!");
});