-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
remote.ts
491 lines (464 loc) Β· 14.5 KB
/
remote.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
import { Runnable, RunnableBatchOptions } from "./base.js";
import type { RunnableConfig } from "./config.js";
import { Document } from "../documents/index.js";
import { CallbackManagerForChainRun } from "../callbacks/manager.js";
import { ChatPromptValue, StringPromptValue } from "../prompt_values.js";
import {
LogStreamCallbackHandler,
type LogStreamCallbackHandlerInput,
type RunLogPatch,
} from "../tracers/log_stream.js";
import {
AIMessage,
AIMessageChunk,
ChatMessage,
ChatMessageChunk,
FunctionMessage,
FunctionMessageChunk,
HumanMessage,
HumanMessageChunk,
SystemMessage,
SystemMessageChunk,
ToolMessage,
ToolMessageChunk,
isBaseMessage,
} from "../messages/index.js";
import { GenerationChunk, ChatGenerationChunk, RUN_KEY } from "../outputs.js";
import {
getBytes,
getLines,
getMessages,
convertEventStreamToIterableReadableDataStream,
} from "../utils/event_source_parse.js";
import { IterableReadableStream } from "../utils/stream.js";
type RemoteRunnableOptions = {
timeout?: number;
headers?: Record<string, unknown>;
};
function isSuperset(set: Set<string>, subset: Set<string>) {
for (const elem of subset) {
if (!set.has(elem)) {
return false;
}
}
return true;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function revive(obj: any): any {
if (Array.isArray(obj)) return obj.map(revive);
if (typeof obj === "object") {
// eslint-disable-next-line no-instanceof/no-instanceof
if (!obj || obj instanceof Date) {
return obj;
}
const keysArr = Object.keys(obj);
const keys = new Set(keysArr);
if (isSuperset(keys, new Set(["page_content", "metadata"]))) {
return new Document({
pageContent: obj.page_content,
metadata: obj.metadata,
});
}
if (isSuperset(keys, new Set(["content", "type", "additional_kwargs"]))) {
if (obj.type === "HumanMessage" || obj.type === "human") {
return new HumanMessage({
content: obj.content,
});
}
if (obj.type === "SystemMessage" || obj.type === "system") {
return new SystemMessage({
content: obj.content,
});
}
if (obj.type === "ChatMessage" || obj.type === "chat") {
return new ChatMessage({
content: obj.content,
role: obj.role,
});
}
if (obj.type === "FunctionMessage" || obj.type === "function") {
return new FunctionMessage({
content: obj.content,
name: obj.name,
});
}
if (obj.type === "ToolMessage" || obj.type === "tool") {
return new ToolMessage({
content: obj.content,
tool_call_id: obj.tool_call_id,
});
}
if (obj.type === "AIMessage" || obj.type === "ai") {
return new AIMessage({
content: obj.content,
});
}
if (obj.type === "HumanMessageChunk") {
return new HumanMessageChunk({
content: obj.content,
});
}
if (obj.type === "SystemMessageChunk") {
return new SystemMessageChunk({
content: obj.content,
});
}
if (obj.type === "ChatMessageChunk") {
return new ChatMessageChunk({
content: obj.content,
role: obj.role,
});
}
if (obj.type === "FunctionMessageChunk") {
return new FunctionMessageChunk({
content: obj.content,
name: obj.name,
});
}
if (obj.type === "ToolMessageChunk") {
return new ToolMessageChunk({
content: obj.content,
tool_call_id: obj.tool_call_id,
});
}
if (obj.type === "AIMessageChunk") {
return new AIMessageChunk({
content: obj.content,
});
}
}
if (isSuperset(keys, new Set(["text", "generation_info", "type"]))) {
if (obj.type === "ChatGenerationChunk") {
return new ChatGenerationChunk({
message: revive(obj.message),
text: obj.text,
generationInfo: obj.generation_info,
});
} else if (obj.type === "ChatGeneration") {
return {
message: revive(obj.message),
text: obj.text,
generationInfo: obj.generation_info,
};
} else if (obj.type === "GenerationChunk") {
return new GenerationChunk({
text: obj.text,
generationInfo: obj.generation_info,
});
} else if (obj.type === "Generation") {
return {
text: obj.text,
generationInfo: obj.generation_info,
};
}
}
if (isSuperset(keys, new Set(["tool", "tool_input", "log", "type"]))) {
if (obj.type === "AgentAction") {
return {
tool: obj.tool,
toolInput: obj.tool_input,
log: obj.log,
};
}
}
if (isSuperset(keys, new Set(["return_values", "log", "type"]))) {
if (obj.type === "AgentFinish") {
return {
returnValues: obj.return_values,
log: obj.log,
};
}
}
if (isSuperset(keys, new Set(["generations", "run", "type"]))) {
if (obj.type === "LLMResult") {
return {
generations: revive(obj.generations),
llmOutput: obj.llm_output,
[RUN_KEY]: obj.run,
};
}
}
if (isSuperset(keys, new Set(["messages"]))) {
// TODO: Start checking for type: ChatPromptValue and ChatPromptValueConcrete
// when LangServe bug is fixed
return new ChatPromptValue({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
messages: obj.messages.map((msg: any) => revive(msg)),
});
}
if (isSuperset(keys, new Set(["text"]))) {
// TODO: Start checking for type: StringPromptValue
// when LangServe bug is fixed
return new StringPromptValue(obj.text);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const innerRevive: (key: string) => [string, any] = (key: string) => [
key,
revive(obj[key]),
];
const rtn = Object.fromEntries(keysArr.map(innerRevive));
return rtn;
}
return obj;
}
function deserialize<RunOutput>(str: string): RunOutput {
const obj = JSON.parse(str);
return revive(obj);
}
function removeCallbacks(
options?: RunnableConfig
): Omit<RunnableConfig, "callbacks"> {
const rest = { ...options };
delete rest.callbacks;
return rest;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function serialize<RunInput>(input: RunInput): any {
if (Array.isArray(input)) return input.map(serialize);
if (isBaseMessage(input)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const serializedMessage: Record<string, any> = {
content: input.content,
type: input._getType(),
additional_kwargs: input.additional_kwargs,
name: input.name,
example: false,
};
if (ToolMessage.isInstance(input)) {
serializedMessage.tool_call_id = input.tool_call_id;
} else if (ChatMessage.isInstance(input)) {
serializedMessage.role = input.role;
}
return serializedMessage;
}
if (typeof input === "object") {
// eslint-disable-next-line no-instanceof/no-instanceof
if (!input || input instanceof Date) {
return input;
}
const keysArr = Object.keys(input);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const innerSerialize: (key: string) => [string, any] = (key: string) => [
key,
serialize((input as Record<string, unknown>)[key]),
];
const rtn = Object.fromEntries(keysArr.map(innerSerialize));
return rtn;
}
return input;
}
export class RemoteRunnable<
RunInput,
RunOutput,
CallOptions extends RunnableConfig
> extends Runnable<RunInput, RunOutput, CallOptions> {
private url: string;
private options?: RemoteRunnableOptions;
lc_namespace = ["langchain", "schema", "runnable", "remote"];
constructor(fields: { url: string; options?: RemoteRunnableOptions }) {
super(fields);
const { url, options } = fields;
this.url = url.replace(/\/$/, ""); // remove trailing slash
this.options = options;
}
private async post<Body>(path: string, body: Body) {
return fetch(`${this.url}${path}`, {
method: "POST",
body: JSON.stringify(serialize(body)),
headers: {
"Content-Type": "application/json",
...this.options?.headers,
},
signal: AbortSignal.timeout(this.options?.timeout ?? 60000),
});
}
async invoke(
input: RunInput,
options?: Partial<CallOptions>
): Promise<RunOutput> {
const [config, kwargs] =
this._separateRunnableConfigFromCallOptions(options);
const response = await this.post<{
input: RunInput;
config?: RunnableConfig;
kwargs?: Omit<Partial<CallOptions>, keyof RunnableConfig>;
}>("/invoke", {
input,
config: removeCallbacks(config),
kwargs: kwargs ?? {},
});
return revive((await response.json()).output) as RunOutput;
}
async _batch(
inputs: RunInput[],
options?: Partial<CallOptions>[],
_?: (CallbackManagerForChainRun | undefined)[],
batchOptions?: RunnableBatchOptions
): Promise<(RunOutput | Error)[]> {
if (batchOptions?.returnExceptions) {
throw new Error("returnExceptions is not supported for remote clients");
}
const configsAndKwargsArray = options?.map((opts) =>
this._separateRunnableConfigFromCallOptions(opts)
);
const [configs, kwargs] = configsAndKwargsArray?.reduce(
([pc, pk], [c, k]) =>
[
[...pc, c],
[...pk, k],
] as [
RunnableConfig[],
Omit<Partial<CallOptions>, keyof RunnableConfig>[]
],
[[], []] as [
RunnableConfig[],
Omit<Partial<CallOptions>, keyof RunnableConfig>[]
]
) ?? [undefined, undefined];
const response = await this.post<{
inputs: RunInput[];
config?: (RunnableConfig & RunnableBatchOptions)[];
kwargs?: Omit<Partial<CallOptions>, keyof RunnableConfig>[];
}>("/batch", {
inputs,
config: (configs ?? [])
.map(removeCallbacks)
.map((config) => ({ ...config, ...batchOptions })),
kwargs,
});
const body = await response.json();
if (!body.output) throw new Error("Invalid response from remote runnable");
return revive(body.output);
}
async batch(
inputs: RunInput[],
options?: Partial<CallOptions> | Partial<CallOptions>[],
batchOptions?: RunnableBatchOptions & { returnExceptions?: false }
): Promise<RunOutput[]>;
async batch(
inputs: RunInput[],
options?: Partial<CallOptions> | Partial<CallOptions>[],
batchOptions?: RunnableBatchOptions & { returnExceptions: true }
): Promise<(RunOutput | Error)[]>;
async batch(
inputs: RunInput[],
options?: Partial<CallOptions> | Partial<CallOptions>[],
batchOptions?: RunnableBatchOptions
): Promise<(RunOutput | Error)[]>;
async batch(
inputs: RunInput[],
options?: Partial<CallOptions> | Partial<CallOptions>[],
batchOptions?: RunnableBatchOptions
): Promise<(RunOutput | Error)[]> {
if (batchOptions?.returnExceptions) {
throw Error("returnExceptions is not supported for remote clients");
}
return this._batchWithConfig(
this._batch.bind(this),
inputs,
options,
batchOptions
);
}
async stream(
input: RunInput,
options?: Partial<CallOptions>
): Promise<IterableReadableStream<RunOutput>> {
const [config, kwargs] =
this._separateRunnableConfigFromCallOptions(options);
const response = await this.post<{
input: RunInput;
config?: RunnableConfig;
kwargs?: Omit<Partial<CallOptions>, keyof RunnableConfig>;
}>("/stream", {
input,
config: removeCallbacks(config),
kwargs,
});
if (!response.ok) {
const json = await response.json();
const error = new Error(
`RemoteRunnable call failed with status code ${response.status}: ${json.message}`
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(error as any).response = response;
throw error;
}
const { body } = response;
if (!body) {
throw new Error(
"Could not begin remote stream. Please check the given URL and try again."
);
}
const stream = new ReadableStream({
async start(controller) {
const enqueueLine = getMessages((msg) => {
if (msg.data) controller.enqueue(deserialize(msg.data));
});
const onLine = (
line: Uint8Array,
fieldLength: number,
flush?: boolean
) => {
enqueueLine(line, fieldLength, flush);
if (flush) controller.close();
};
await getBytes(body, getLines(onLine));
},
});
return IterableReadableStream.fromReadableStream(stream);
}
async *streamLog(
input: RunInput,
options?: Partial<CallOptions>,
streamOptions?: Omit<LogStreamCallbackHandlerInput, "autoClose">
): AsyncGenerator<RunLogPatch> {
const [config, kwargs] =
this._separateRunnableConfigFromCallOptions(options);
const stream = new LogStreamCallbackHandler({
...streamOptions,
autoClose: false,
});
const { callbacks } = config;
if (callbacks === undefined) {
config.callbacks = [stream];
} else if (Array.isArray(callbacks)) {
config.callbacks = callbacks.concat([stream]);
} else {
const copiedCallbacks = callbacks.copy();
copiedCallbacks.inheritableHandlers.push(stream);
config.callbacks = copiedCallbacks;
}
// The type is in camelCase but the API only accepts snake_case.
const camelCaseStreamOptions = {
include_names: streamOptions?.includeNames,
include_types: streamOptions?.includeTypes,
include_tags: streamOptions?.includeTags,
exclude_names: streamOptions?.excludeNames,
exclude_types: streamOptions?.excludeTypes,
exclude_tags: streamOptions?.excludeTags,
};
const response = await this.post<{
input: RunInput;
config?: RunnableConfig;
kwargs?: Omit<Partial<CallOptions>, keyof RunnableConfig>;
diff: false;
}>("/stream_log", {
input,
config: removeCallbacks(config),
kwargs,
...camelCaseStreamOptions,
diff: false,
});
const { body } = response;
if (!body) {
throw new Error(
"Could not begin remote stream log. Please check the given URL and try again."
);
}
const runnableStream = convertEventStreamToIterableReadableDataStream(body);
for await (const log of runnableStream) {
yield revive(JSON.parse(log));
}
}
}