@langchain/core 0.1.23 → 0.1.25-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/messages/index.cjs +3 -0
- package/dist/messages/index.d.ts +1 -0
- package/dist/messages/index.js +3 -0
- package/dist/output_parsers/xml.cjs +10 -19
- package/dist/output_parsers/xml.d.ts +2 -4
- package/dist/output_parsers/xml.js +10 -16
- package/dist/prompts/image.cjs +6 -0
- package/dist/prompts/image.d.ts +1 -0
- package/dist/prompts/image.js +6 -0
- package/dist/prompts/index.cjs +1 -0
- package/dist/prompts/index.d.ts +1 -0
- package/dist/prompts/index.js +1 -0
- package/dist/runnables/remote.cjs +378 -0
- package/dist/runnables/remote.d.ts +31 -0
- package/dist/runnables/remote.js +374 -0
- package/dist/utils/event_source_parse.cjs +210 -0
- package/dist/utils/event_source_parse.d.ts +39 -0
- package/dist/utils/event_source_parse.js +203 -0
- package/dist/utils/sax-js/sax.cjs +1557 -0
- package/dist/utils/sax-js/sax.d.ts +2 -0
- package/dist/utils/sax-js/sax.js +1554 -0
- package/package.json +27 -3
- package/runnables/remote.cjs +1 -0
- package/runnables/remote.d.cts +1 -0
- package/runnables/remote.d.ts +1 -0
- package/runnables/remote.js +1 -0
- package/utils/event_source_parse.cjs +1 -0
- package/utils/event_source_parse.d.cts +1 -0
- package/utils/event_source_parse.d.ts +1 -0
- package/utils/event_source_parse.js +1 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Runnable, RunnableBatchOptions } from "./base.js";
|
|
2
|
+
import type { RunnableConfig } from "./config.js";
|
|
3
|
+
import { CallbackManagerForChainRun } from "../callbacks/manager.js";
|
|
4
|
+
import { type LogStreamCallbackHandlerInput, type RunLogPatch } from "../tracers/log_stream.js";
|
|
5
|
+
import { IterableReadableStream } from "../utils/stream.js";
|
|
6
|
+
type RemoteRunnableOptions = {
|
|
7
|
+
timeout?: number;
|
|
8
|
+
headers?: Record<string, unknown>;
|
|
9
|
+
};
|
|
10
|
+
export declare class RemoteRunnable<RunInput, RunOutput, CallOptions extends RunnableConfig> extends Runnable<RunInput, RunOutput, CallOptions> {
|
|
11
|
+
private url;
|
|
12
|
+
private options?;
|
|
13
|
+
lc_namespace: string[];
|
|
14
|
+
constructor(fields: {
|
|
15
|
+
url: string;
|
|
16
|
+
options?: RemoteRunnableOptions;
|
|
17
|
+
});
|
|
18
|
+
private post;
|
|
19
|
+
invoke(input: RunInput, options?: Partial<CallOptions>): Promise<RunOutput>;
|
|
20
|
+
_batch(inputs: RunInput[], options?: Partial<CallOptions>[], _?: (CallbackManagerForChainRun | undefined)[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
|
|
21
|
+
batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions & {
|
|
22
|
+
returnExceptions?: false;
|
|
23
|
+
}): Promise<RunOutput[]>;
|
|
24
|
+
batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions & {
|
|
25
|
+
returnExceptions: true;
|
|
26
|
+
}): Promise<(RunOutput | Error)[]>;
|
|
27
|
+
batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
|
|
28
|
+
stream(input: RunInput, options?: Partial<CallOptions>): Promise<IterableReadableStream<RunOutput>>;
|
|
29
|
+
streamLog(input: RunInput, options?: Partial<CallOptions>, streamOptions?: Omit<LogStreamCallbackHandlerInput, "autoClose">): AsyncGenerator<RunLogPatch>;
|
|
30
|
+
}
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import { Runnable } from "./base.js";
|
|
2
|
+
import { Document } from "../documents/index.js";
|
|
3
|
+
import { ChatPromptValue, StringPromptValue } from "../prompt_values.js";
|
|
4
|
+
import { LogStreamCallbackHandler, } from "../tracers/log_stream.js";
|
|
5
|
+
import { AIMessage, AIMessageChunk, ChatMessage, ChatMessageChunk, FunctionMessage, FunctionMessageChunk, HumanMessage, HumanMessageChunk, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, isBaseMessage, } from "../messages/index.js";
|
|
6
|
+
import { GenerationChunk, ChatGenerationChunk, RUN_KEY } from "../outputs.js";
|
|
7
|
+
import { getBytes, getLines, getMessages, convertEventStreamToIterableReadableDataStream, } from "../utils/event_source_parse.js";
|
|
8
|
+
import { IterableReadableStream } from "../utils/stream.js";
|
|
9
|
+
function isSuperset(set, subset) {
|
|
10
|
+
for (const elem of subset) {
|
|
11
|
+
if (!set.has(elem)) {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
18
|
+
function revive(obj) {
|
|
19
|
+
if (Array.isArray(obj))
|
|
20
|
+
return obj.map(revive);
|
|
21
|
+
if (typeof obj === "object") {
|
|
22
|
+
// eslint-disable-next-line no-instanceof/no-instanceof
|
|
23
|
+
if (!obj || obj instanceof Date) {
|
|
24
|
+
return obj;
|
|
25
|
+
}
|
|
26
|
+
const keysArr = Object.keys(obj);
|
|
27
|
+
const keys = new Set(keysArr);
|
|
28
|
+
if (isSuperset(keys, new Set(["page_content", "metadata"]))) {
|
|
29
|
+
return new Document({
|
|
30
|
+
pageContent: obj.page_content,
|
|
31
|
+
metadata: obj.metadata,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
if (isSuperset(keys, new Set(["content", "type", "additional_kwargs"]))) {
|
|
35
|
+
if (obj.type === "HumanMessage" || obj.type === "human") {
|
|
36
|
+
return new HumanMessage({
|
|
37
|
+
content: obj.content,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
if (obj.type === "SystemMessage" || obj.type === "system") {
|
|
41
|
+
return new SystemMessage({
|
|
42
|
+
content: obj.content,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
if (obj.type === "ChatMessage" || obj.type === "chat") {
|
|
46
|
+
return new ChatMessage({
|
|
47
|
+
content: obj.content,
|
|
48
|
+
role: obj.role,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
if (obj.type === "FunctionMessage" || obj.type === "function") {
|
|
52
|
+
return new FunctionMessage({
|
|
53
|
+
content: obj.content,
|
|
54
|
+
name: obj.name,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
if (obj.type === "ToolMessage" || obj.type === "tool") {
|
|
58
|
+
return new ToolMessage({
|
|
59
|
+
content: obj.content,
|
|
60
|
+
tool_call_id: obj.tool_call_id,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
if (obj.type === "AIMessage" || obj.type === "ai") {
|
|
64
|
+
return new AIMessage({
|
|
65
|
+
content: obj.content,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
if (obj.type === "HumanMessageChunk") {
|
|
69
|
+
return new HumanMessageChunk({
|
|
70
|
+
content: obj.content,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
if (obj.type === "SystemMessageChunk") {
|
|
74
|
+
return new SystemMessageChunk({
|
|
75
|
+
content: obj.content,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
if (obj.type === "ChatMessageChunk") {
|
|
79
|
+
return new ChatMessageChunk({
|
|
80
|
+
content: obj.content,
|
|
81
|
+
role: obj.role,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
if (obj.type === "FunctionMessageChunk") {
|
|
85
|
+
return new FunctionMessageChunk({
|
|
86
|
+
content: obj.content,
|
|
87
|
+
name: obj.name,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
if (obj.type === "ToolMessageChunk") {
|
|
91
|
+
return new ToolMessageChunk({
|
|
92
|
+
content: obj.content,
|
|
93
|
+
tool_call_id: obj.tool_call_id,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
if (obj.type === "AIMessageChunk") {
|
|
97
|
+
return new AIMessageChunk({
|
|
98
|
+
content: obj.content,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (isSuperset(keys, new Set(["text", "generation_info", "type"]))) {
|
|
103
|
+
if (obj.type === "ChatGenerationChunk") {
|
|
104
|
+
return new ChatGenerationChunk({
|
|
105
|
+
message: revive(obj.message),
|
|
106
|
+
text: obj.text,
|
|
107
|
+
generationInfo: obj.generation_info,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
else if (obj.type === "ChatGeneration") {
|
|
111
|
+
return {
|
|
112
|
+
message: revive(obj.message),
|
|
113
|
+
text: obj.text,
|
|
114
|
+
generationInfo: obj.generation_info,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
else if (obj.type === "GenerationChunk") {
|
|
118
|
+
return new GenerationChunk({
|
|
119
|
+
text: obj.text,
|
|
120
|
+
generationInfo: obj.generation_info,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
else if (obj.type === "Generation") {
|
|
124
|
+
return {
|
|
125
|
+
text: obj.text,
|
|
126
|
+
generationInfo: obj.generation_info,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (isSuperset(keys, new Set(["tool", "tool_input", "log", "type"]))) {
|
|
131
|
+
if (obj.type === "AgentAction") {
|
|
132
|
+
return {
|
|
133
|
+
tool: obj.tool,
|
|
134
|
+
toolInput: obj.tool_input,
|
|
135
|
+
log: obj.log,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (isSuperset(keys, new Set(["return_values", "log", "type"]))) {
|
|
140
|
+
if (obj.type === "AgentFinish") {
|
|
141
|
+
return {
|
|
142
|
+
returnValues: obj.return_values,
|
|
143
|
+
log: obj.log,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (isSuperset(keys, new Set(["generations", "run", "type"]))) {
|
|
148
|
+
if (obj.type === "LLMResult") {
|
|
149
|
+
return {
|
|
150
|
+
generations: revive(obj.generations),
|
|
151
|
+
llmOutput: obj.llm_output,
|
|
152
|
+
[RUN_KEY]: obj.run,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (isSuperset(keys, new Set(["messages"]))) {
|
|
157
|
+
// TODO: Start checking for type: ChatPromptValue and ChatPromptValueConcrete
|
|
158
|
+
// when LangServe bug is fixed
|
|
159
|
+
return new ChatPromptValue({
|
|
160
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
161
|
+
messages: obj.messages.map((msg) => revive(msg)),
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
if (isSuperset(keys, new Set(["text"]))) {
|
|
165
|
+
// TODO: Start checking for type: StringPromptValue
|
|
166
|
+
// when LangServe bug is fixed
|
|
167
|
+
return new StringPromptValue(obj.text);
|
|
168
|
+
}
|
|
169
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
170
|
+
const innerRevive = (key) => [
|
|
171
|
+
key,
|
|
172
|
+
revive(obj[key]),
|
|
173
|
+
];
|
|
174
|
+
const rtn = Object.fromEntries(keysArr.map(innerRevive));
|
|
175
|
+
return rtn;
|
|
176
|
+
}
|
|
177
|
+
return obj;
|
|
178
|
+
}
|
|
179
|
+
function deserialize(str) {
|
|
180
|
+
const obj = JSON.parse(str);
|
|
181
|
+
return revive(obj);
|
|
182
|
+
}
|
|
183
|
+
function removeCallbacks(options) {
|
|
184
|
+
const rest = { ...options };
|
|
185
|
+
delete rest.callbacks;
|
|
186
|
+
return rest;
|
|
187
|
+
}
|
|
188
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
189
|
+
function serialize(input) {
|
|
190
|
+
if (Array.isArray(input))
|
|
191
|
+
return input.map(serialize);
|
|
192
|
+
if (isBaseMessage(input)) {
|
|
193
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
194
|
+
const serializedMessage = {
|
|
195
|
+
content: input.content,
|
|
196
|
+
type: input._getType(),
|
|
197
|
+
additional_kwargs: input.additional_kwargs,
|
|
198
|
+
name: input.name,
|
|
199
|
+
example: false,
|
|
200
|
+
};
|
|
201
|
+
if (ToolMessage.isInstance(input)) {
|
|
202
|
+
serializedMessage.tool_call_id = input.tool_call_id;
|
|
203
|
+
}
|
|
204
|
+
else if (ChatMessage.isInstance(input)) {
|
|
205
|
+
serializedMessage.role = input.role;
|
|
206
|
+
}
|
|
207
|
+
return serializedMessage;
|
|
208
|
+
}
|
|
209
|
+
if (typeof input === "object") {
|
|
210
|
+
// eslint-disable-next-line no-instanceof/no-instanceof
|
|
211
|
+
if (!input || input instanceof Date) {
|
|
212
|
+
return input;
|
|
213
|
+
}
|
|
214
|
+
const keysArr = Object.keys(input);
|
|
215
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
216
|
+
const innerSerialize = (key) => [
|
|
217
|
+
key,
|
|
218
|
+
serialize(input[key]),
|
|
219
|
+
];
|
|
220
|
+
const rtn = Object.fromEntries(keysArr.map(innerSerialize));
|
|
221
|
+
return rtn;
|
|
222
|
+
}
|
|
223
|
+
return input;
|
|
224
|
+
}
|
|
225
|
+
export class RemoteRunnable extends Runnable {
|
|
226
|
+
constructor(fields) {
|
|
227
|
+
super(fields);
|
|
228
|
+
Object.defineProperty(this, "url", {
|
|
229
|
+
enumerable: true,
|
|
230
|
+
configurable: true,
|
|
231
|
+
writable: true,
|
|
232
|
+
value: void 0
|
|
233
|
+
});
|
|
234
|
+
Object.defineProperty(this, "options", {
|
|
235
|
+
enumerable: true,
|
|
236
|
+
configurable: true,
|
|
237
|
+
writable: true,
|
|
238
|
+
value: void 0
|
|
239
|
+
});
|
|
240
|
+
Object.defineProperty(this, "lc_namespace", {
|
|
241
|
+
enumerable: true,
|
|
242
|
+
configurable: true,
|
|
243
|
+
writable: true,
|
|
244
|
+
value: ["langchain", "schema", "runnable", "remote"]
|
|
245
|
+
});
|
|
246
|
+
const { url, options } = fields;
|
|
247
|
+
this.url = url.replace(/\/$/, ""); // remove trailing slash
|
|
248
|
+
this.options = options;
|
|
249
|
+
}
|
|
250
|
+
async post(path, body) {
|
|
251
|
+
return fetch(`${this.url}${path}`, {
|
|
252
|
+
method: "POST",
|
|
253
|
+
body: JSON.stringify(serialize(body)),
|
|
254
|
+
headers: {
|
|
255
|
+
"Content-Type": "application/json",
|
|
256
|
+
...this.options?.headers,
|
|
257
|
+
},
|
|
258
|
+
signal: AbortSignal.timeout(this.options?.timeout ?? 60000),
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
async invoke(input, options) {
|
|
262
|
+
const [config, kwargs] = this._separateRunnableConfigFromCallOptions(options);
|
|
263
|
+
const response = await this.post("/invoke", {
|
|
264
|
+
input,
|
|
265
|
+
config: removeCallbacks(config),
|
|
266
|
+
kwargs: kwargs ?? {},
|
|
267
|
+
});
|
|
268
|
+
return revive((await response.json()).output);
|
|
269
|
+
}
|
|
270
|
+
async _batch(inputs, options, _, batchOptions) {
|
|
271
|
+
if (batchOptions?.returnExceptions) {
|
|
272
|
+
throw new Error("returnExceptions is not supported for remote clients");
|
|
273
|
+
}
|
|
274
|
+
const configsAndKwargsArray = options?.map((opts) => this._separateRunnableConfigFromCallOptions(opts));
|
|
275
|
+
const [configs, kwargs] = configsAndKwargsArray?.reduce(([pc, pk], [c, k]) => [
|
|
276
|
+
[...pc, c],
|
|
277
|
+
[...pk, k],
|
|
278
|
+
], [[], []]) ?? [undefined, undefined];
|
|
279
|
+
const response = await this.post("/batch", {
|
|
280
|
+
inputs,
|
|
281
|
+
config: (configs ?? [])
|
|
282
|
+
.map(removeCallbacks)
|
|
283
|
+
.map((config) => ({ ...config, ...batchOptions })),
|
|
284
|
+
kwargs,
|
|
285
|
+
});
|
|
286
|
+
const body = await response.json();
|
|
287
|
+
if (!body.output)
|
|
288
|
+
throw new Error("Invalid response from remote runnable");
|
|
289
|
+
return revive(body.output);
|
|
290
|
+
}
|
|
291
|
+
async batch(inputs, options, batchOptions) {
|
|
292
|
+
if (batchOptions?.returnExceptions) {
|
|
293
|
+
throw Error("returnExceptions is not supported for remote clients");
|
|
294
|
+
}
|
|
295
|
+
return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions);
|
|
296
|
+
}
|
|
297
|
+
async stream(input, options) {
|
|
298
|
+
const [config, kwargs] = this._separateRunnableConfigFromCallOptions(options);
|
|
299
|
+
const response = await this.post("/stream", {
|
|
300
|
+
input,
|
|
301
|
+
config: removeCallbacks(config),
|
|
302
|
+
kwargs,
|
|
303
|
+
});
|
|
304
|
+
if (!response.ok) {
|
|
305
|
+
const json = await response.json();
|
|
306
|
+
const error = new Error(`RemoteRunnable call failed with status code ${response.status}: ${json.message}`);
|
|
307
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
308
|
+
error.response = response;
|
|
309
|
+
throw error;
|
|
310
|
+
}
|
|
311
|
+
const { body } = response;
|
|
312
|
+
if (!body) {
|
|
313
|
+
throw new Error("Could not begin remote stream. Please check the given URL and try again.");
|
|
314
|
+
}
|
|
315
|
+
const stream = new ReadableStream({
|
|
316
|
+
async start(controller) {
|
|
317
|
+
const enqueueLine = getMessages((msg) => {
|
|
318
|
+
if (msg.data)
|
|
319
|
+
controller.enqueue(deserialize(msg.data));
|
|
320
|
+
});
|
|
321
|
+
const onLine = (line, fieldLength, flush) => {
|
|
322
|
+
enqueueLine(line, fieldLength, flush);
|
|
323
|
+
if (flush)
|
|
324
|
+
controller.close();
|
|
325
|
+
};
|
|
326
|
+
await getBytes(body, getLines(onLine));
|
|
327
|
+
},
|
|
328
|
+
});
|
|
329
|
+
return IterableReadableStream.fromReadableStream(stream);
|
|
330
|
+
}
|
|
331
|
+
async *streamLog(input, options, streamOptions) {
|
|
332
|
+
const [config, kwargs] = this._separateRunnableConfigFromCallOptions(options);
|
|
333
|
+
const stream = new LogStreamCallbackHandler({
|
|
334
|
+
...streamOptions,
|
|
335
|
+
autoClose: false,
|
|
336
|
+
});
|
|
337
|
+
const { callbacks } = config;
|
|
338
|
+
if (callbacks === undefined) {
|
|
339
|
+
config.callbacks = [stream];
|
|
340
|
+
}
|
|
341
|
+
else if (Array.isArray(callbacks)) {
|
|
342
|
+
config.callbacks = callbacks.concat([stream]);
|
|
343
|
+
}
|
|
344
|
+
else {
|
|
345
|
+
const copiedCallbacks = callbacks.copy();
|
|
346
|
+
copiedCallbacks.inheritableHandlers.push(stream);
|
|
347
|
+
config.callbacks = copiedCallbacks;
|
|
348
|
+
}
|
|
349
|
+
// The type is in camelCase but the API only accepts snake_case.
|
|
350
|
+
const camelCaseStreamOptions = {
|
|
351
|
+
include_names: streamOptions?.includeNames,
|
|
352
|
+
include_types: streamOptions?.includeTypes,
|
|
353
|
+
include_tags: streamOptions?.includeTags,
|
|
354
|
+
exclude_names: streamOptions?.excludeNames,
|
|
355
|
+
exclude_types: streamOptions?.excludeTypes,
|
|
356
|
+
exclude_tags: streamOptions?.excludeTags,
|
|
357
|
+
};
|
|
358
|
+
const response = await this.post("/stream_log", {
|
|
359
|
+
input,
|
|
360
|
+
config: removeCallbacks(config),
|
|
361
|
+
kwargs,
|
|
362
|
+
...camelCaseStreamOptions,
|
|
363
|
+
diff: false,
|
|
364
|
+
});
|
|
365
|
+
const { body } = response;
|
|
366
|
+
if (!body) {
|
|
367
|
+
throw new Error("Could not begin remote stream log. Please check the given URL and try again.");
|
|
368
|
+
}
|
|
369
|
+
const runnableStream = convertEventStreamToIterableReadableDataStream(body);
|
|
370
|
+
for await (const log of runnableStream) {
|
|
371
|
+
yield revive(JSON.parse(log));
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.convertEventStreamToIterableReadableDataStream = exports.getMessages = exports.getLines = exports.getBytes = exports.EventStreamContentType = void 0;
|
|
4
|
+
/* eslint-disable prefer-template */
|
|
5
|
+
/* eslint-disable default-case */
|
|
6
|
+
/* eslint-disable no-plusplus */
|
|
7
|
+
// Adapted from https://github.com/gfortaine/fetch-event-source/blob/main/src/parse.ts
|
|
8
|
+
// due to a packaging issue in the original.
|
|
9
|
+
// MIT License
|
|
10
|
+
const stream_js_1 = require("./stream.cjs");
|
|
11
|
+
exports.EventStreamContentType = "text/event-stream";
|
|
12
|
+
/**
|
|
13
|
+
* Converts a ReadableStream into a callback pattern.
|
|
14
|
+
* @param stream The input ReadableStream.
|
|
15
|
+
* @param onChunk A function that will be called on each new byte chunk in the stream.
|
|
16
|
+
* @returns {Promise<void>} A promise that will be resolved when the stream closes.
|
|
17
|
+
*/
|
|
18
|
+
async function getBytes(stream, onChunk) {
|
|
19
|
+
const reader = stream.getReader();
|
|
20
|
+
// CHANGED: Introduced a "flush" mechanism to process potential pending messages when the stream ends.
|
|
21
|
+
// This change is essential to ensure that we capture every last piece of information from streams,
|
|
22
|
+
// such as those from Azure OpenAI, which may not terminate with a blank line. Without this
|
|
23
|
+
// mechanism, we risk ignoring a possibly significant last message.
|
|
24
|
+
// See https://github.com/langchain-ai/langchainjs/issues/1299 for details.
|
|
25
|
+
// eslint-disable-next-line no-constant-condition
|
|
26
|
+
while (true) {
|
|
27
|
+
const result = await reader.read();
|
|
28
|
+
if (result.done) {
|
|
29
|
+
onChunk(new Uint8Array(), true);
|
|
30
|
+
break;
|
|
31
|
+
}
|
|
32
|
+
onChunk(result.value);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
exports.getBytes = getBytes;
|
|
36
|
+
/**
|
|
37
|
+
* Parses arbitary byte chunks into EventSource line buffers.
|
|
38
|
+
* Each line should be of the format "field: value" and ends with \r, \n, or \r\n.
|
|
39
|
+
* @param onLine A function that will be called on each new EventSource line.
|
|
40
|
+
* @returns A function that should be called for each incoming byte chunk.
|
|
41
|
+
*/
|
|
42
|
+
function getLines(onLine) {
|
|
43
|
+
let buffer;
|
|
44
|
+
let position; // current read position
|
|
45
|
+
let fieldLength; // length of the `field` portion of the line
|
|
46
|
+
let discardTrailingNewline = false;
|
|
47
|
+
// return a function that can process each incoming byte chunk:
|
|
48
|
+
return function onChunk(arr, flush) {
|
|
49
|
+
if (flush) {
|
|
50
|
+
onLine(arr, 0, true);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (buffer === undefined) {
|
|
54
|
+
buffer = arr;
|
|
55
|
+
position = 0;
|
|
56
|
+
fieldLength = -1;
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
// we're still parsing the old line. Append the new bytes into buffer:
|
|
60
|
+
buffer = concat(buffer, arr);
|
|
61
|
+
}
|
|
62
|
+
const bufLength = buffer.length;
|
|
63
|
+
let lineStart = 0; // index where the current line starts
|
|
64
|
+
while (position < bufLength) {
|
|
65
|
+
if (discardTrailingNewline) {
|
|
66
|
+
if (buffer[position] === 10 /* ControlChars.NewLine */) {
|
|
67
|
+
lineStart = ++position; // skip to next char
|
|
68
|
+
}
|
|
69
|
+
discardTrailingNewline = false;
|
|
70
|
+
}
|
|
71
|
+
// start looking forward till the end of line:
|
|
72
|
+
let lineEnd = -1; // index of the \r or \n char
|
|
73
|
+
for (; position < bufLength && lineEnd === -1; ++position) {
|
|
74
|
+
switch (buffer[position]) {
|
|
75
|
+
case 58 /* ControlChars.Colon */:
|
|
76
|
+
if (fieldLength === -1) {
|
|
77
|
+
// first colon in line
|
|
78
|
+
fieldLength = position - lineStart;
|
|
79
|
+
}
|
|
80
|
+
break;
|
|
81
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
82
|
+
// @ts-ignore:7029 \r case below should fallthrough to \n:
|
|
83
|
+
case 13 /* ControlChars.CarriageReturn */:
|
|
84
|
+
discardTrailingNewline = true;
|
|
85
|
+
// eslint-disable-next-line no-fallthrough
|
|
86
|
+
case 10 /* ControlChars.NewLine */:
|
|
87
|
+
lineEnd = position;
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (lineEnd === -1) {
|
|
92
|
+
// We reached the end of the buffer but the line hasn't ended.
|
|
93
|
+
// Wait for the next arr and then continue parsing:
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
// we've reached the line end, send it out:
|
|
97
|
+
onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
|
|
98
|
+
lineStart = position; // we're now on the next line
|
|
99
|
+
fieldLength = -1;
|
|
100
|
+
}
|
|
101
|
+
if (lineStart === bufLength) {
|
|
102
|
+
buffer = undefined; // we've finished reading it
|
|
103
|
+
}
|
|
104
|
+
else if (lineStart !== 0) {
|
|
105
|
+
// Create a new view into buffer beginning at lineStart so we don't
|
|
106
|
+
// need to copy over the previous lines when we get the new arr:
|
|
107
|
+
buffer = buffer.subarray(lineStart);
|
|
108
|
+
position -= lineStart;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
exports.getLines = getLines;
|
|
113
|
+
/**
|
|
114
|
+
* Parses line buffers into EventSourceMessages.
|
|
115
|
+
* @param onId A function that will be called on each `id` field.
|
|
116
|
+
* @param onRetry A function that will be called on each `retry` field.
|
|
117
|
+
* @param onMessage A function that will be called on each message.
|
|
118
|
+
* @returns A function that should be called for each incoming line buffer.
|
|
119
|
+
*/
|
|
120
|
+
function getMessages(onMessage, onId, onRetry) {
|
|
121
|
+
let message = newMessage();
|
|
122
|
+
const decoder = new TextDecoder();
|
|
123
|
+
// return a function that can process each incoming line buffer:
|
|
124
|
+
return function onLine(line, fieldLength, flush) {
|
|
125
|
+
if (flush) {
|
|
126
|
+
if (!isEmpty(message)) {
|
|
127
|
+
onMessage?.(message);
|
|
128
|
+
message = newMessage();
|
|
129
|
+
}
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (line.length === 0) {
|
|
133
|
+
// empty line denotes end of message. Trigger the callback and start a new message:
|
|
134
|
+
onMessage?.(message);
|
|
135
|
+
message = newMessage();
|
|
136
|
+
}
|
|
137
|
+
else if (fieldLength > 0) {
|
|
138
|
+
// exclude comments and lines with no values
|
|
139
|
+
// line is of format "<field>:<value>" or "<field>: <value>"
|
|
140
|
+
// https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
|
|
141
|
+
const field = decoder.decode(line.subarray(0, fieldLength));
|
|
142
|
+
const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* ControlChars.Space */ ? 2 : 1);
|
|
143
|
+
const value = decoder.decode(line.subarray(valueOffset));
|
|
144
|
+
switch (field) {
|
|
145
|
+
case "data":
|
|
146
|
+
// if this message already has data, append the new value to the old.
|
|
147
|
+
// otherwise, just set to the new value:
|
|
148
|
+
message.data = message.data ? message.data + "\n" + value : value; // otherwise,
|
|
149
|
+
break;
|
|
150
|
+
case "event":
|
|
151
|
+
message.event = value;
|
|
152
|
+
break;
|
|
153
|
+
case "id":
|
|
154
|
+
onId?.((message.id = value));
|
|
155
|
+
break;
|
|
156
|
+
case "retry": {
|
|
157
|
+
const retry = parseInt(value, 10);
|
|
158
|
+
if (!Number.isNaN(retry)) {
|
|
159
|
+
// per spec, ignore non-integers
|
|
160
|
+
onRetry?.((message.retry = retry));
|
|
161
|
+
}
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
exports.getMessages = getMessages;
|
|
169
|
+
function concat(a, b) {
|
|
170
|
+
const res = new Uint8Array(a.length + b.length);
|
|
171
|
+
res.set(a);
|
|
172
|
+
res.set(b, a.length);
|
|
173
|
+
return res;
|
|
174
|
+
}
|
|
175
|
+
function newMessage() {
|
|
176
|
+
// data, event, and id must be initialized to empty strings:
|
|
177
|
+
// https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
|
|
178
|
+
// retry should be initialized to undefined so we return a consistent shape
|
|
179
|
+
// to the js engine all the time: https://mathiasbynens.be/notes/shapes-ics#takeaways
|
|
180
|
+
return {
|
|
181
|
+
data: "",
|
|
182
|
+
event: "",
|
|
183
|
+
id: "",
|
|
184
|
+
retry: undefined,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
function convertEventStreamToIterableReadableDataStream(stream) {
|
|
188
|
+
const dataStream = new ReadableStream({
|
|
189
|
+
async start(controller) {
|
|
190
|
+
const enqueueLine = getMessages((msg) => {
|
|
191
|
+
if (msg.data)
|
|
192
|
+
controller.enqueue(msg.data);
|
|
193
|
+
});
|
|
194
|
+
const onLine = (line, fieldLength, flush) => {
|
|
195
|
+
enqueueLine(line, fieldLength, flush);
|
|
196
|
+
if (flush)
|
|
197
|
+
controller.close();
|
|
198
|
+
};
|
|
199
|
+
await getBytes(stream, getLines(onLine));
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
return stream_js_1.IterableReadableStream.fromReadableStream(dataStream);
|
|
203
|
+
}
|
|
204
|
+
exports.convertEventStreamToIterableReadableDataStream = convertEventStreamToIterableReadableDataStream;
|
|
205
|
+
function isEmpty(message) {
|
|
206
|
+
return (message.data === "" &&
|
|
207
|
+
message.event === "" &&
|
|
208
|
+
message.id === "" &&
|
|
209
|
+
message.retry === undefined);
|
|
210
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { IterableReadableStream } from "./stream.js";
|
|
2
|
+
export declare const EventStreamContentType = "text/event-stream";
|
|
3
|
+
/**
|
|
4
|
+
* Represents a message sent in an event stream
|
|
5
|
+
* https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format
|
|
6
|
+
*/
|
|
7
|
+
export interface EventSourceMessage {
|
|
8
|
+
/** The event ID to set the EventSource object's last event ID value. */
|
|
9
|
+
id: string;
|
|
10
|
+
/** A string identifying the type of event described. */
|
|
11
|
+
event: string;
|
|
12
|
+
/** The event data */
|
|
13
|
+
data: string;
|
|
14
|
+
/** The reconnection interval (in milliseconds) to wait before retrying the connection */
|
|
15
|
+
retry?: number;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Converts a ReadableStream into a callback pattern.
|
|
19
|
+
* @param stream The input ReadableStream.
|
|
20
|
+
* @param onChunk A function that will be called on each new byte chunk in the stream.
|
|
21
|
+
* @returns {Promise<void>} A promise that will be resolved when the stream closes.
|
|
22
|
+
*/
|
|
23
|
+
export declare function getBytes(stream: ReadableStream<Uint8Array>, onChunk: (arr: Uint8Array, flush?: boolean) => void): Promise<void>;
|
|
24
|
+
/**
|
|
25
|
+
* Parses arbitary byte chunks into EventSource line buffers.
|
|
26
|
+
* Each line should be of the format "field: value" and ends with \r, \n, or \r\n.
|
|
27
|
+
* @param onLine A function that will be called on each new EventSource line.
|
|
28
|
+
* @returns A function that should be called for each incoming byte chunk.
|
|
29
|
+
*/
|
|
30
|
+
export declare function getLines(onLine: (line: Uint8Array, fieldLength: number, flush?: boolean) => void): (arr: Uint8Array, flush?: boolean) => void;
|
|
31
|
+
/**
|
|
32
|
+
* Parses line buffers into EventSourceMessages.
|
|
33
|
+
* @param onId A function that will be called on each `id` field.
|
|
34
|
+
* @param onRetry A function that will be called on each `retry` field.
|
|
35
|
+
* @param onMessage A function that will be called on each message.
|
|
36
|
+
* @returns A function that should be called for each incoming line buffer.
|
|
37
|
+
*/
|
|
38
|
+
export declare function getMessages(onMessage?: (msg: EventSourceMessage) => void, onId?: (id: string) => void, onRetry?: (retry: number) => void): (line: Uint8Array, fieldLength: number, flush?: boolean) => void;
|
|
39
|
+
export declare function convertEventStreamToIterableReadableDataStream(stream: ReadableStream): IterableReadableStream<any>;
|