@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.
@@ -0,0 +1,203 @@
1
+ /* eslint-disable prefer-template */
2
+ /* eslint-disable default-case */
3
+ /* eslint-disable no-plusplus */
4
+ // Adapted from https://github.com/gfortaine/fetch-event-source/blob/main/src/parse.ts
5
+ // due to a packaging issue in the original.
6
+ // MIT License
7
+ import { IterableReadableStream } from "./stream.js";
8
+ export const EventStreamContentType = "text/event-stream";
9
+ /**
10
+ * Converts a ReadableStream into a callback pattern.
11
+ * @param stream The input ReadableStream.
12
+ * @param onChunk A function that will be called on each new byte chunk in the stream.
13
+ * @returns {Promise<void>} A promise that will be resolved when the stream closes.
14
+ */
15
+ export async function getBytes(stream, onChunk) {
16
+ const reader = stream.getReader();
17
+ // CHANGED: Introduced a "flush" mechanism to process potential pending messages when the stream ends.
18
+ // This change is essential to ensure that we capture every last piece of information from streams,
19
+ // such as those from Azure OpenAI, which may not terminate with a blank line. Without this
20
+ // mechanism, we risk ignoring a possibly significant last message.
21
+ // See https://github.com/langchain-ai/langchainjs/issues/1299 for details.
22
+ // eslint-disable-next-line no-constant-condition
23
+ while (true) {
24
+ const result = await reader.read();
25
+ if (result.done) {
26
+ onChunk(new Uint8Array(), true);
27
+ break;
28
+ }
29
+ onChunk(result.value);
30
+ }
31
+ }
32
+ /**
33
+ * Parses arbitary byte chunks into EventSource line buffers.
34
+ * Each line should be of the format "field: value" and ends with \r, \n, or \r\n.
35
+ * @param onLine A function that will be called on each new EventSource line.
36
+ * @returns A function that should be called for each incoming byte chunk.
37
+ */
38
+ export function getLines(onLine) {
39
+ let buffer;
40
+ let position; // current read position
41
+ let fieldLength; // length of the `field` portion of the line
42
+ let discardTrailingNewline = false;
43
+ // return a function that can process each incoming byte chunk:
44
+ return function onChunk(arr, flush) {
45
+ if (flush) {
46
+ onLine(arr, 0, true);
47
+ return;
48
+ }
49
+ if (buffer === undefined) {
50
+ buffer = arr;
51
+ position = 0;
52
+ fieldLength = -1;
53
+ }
54
+ else {
55
+ // we're still parsing the old line. Append the new bytes into buffer:
56
+ buffer = concat(buffer, arr);
57
+ }
58
+ const bufLength = buffer.length;
59
+ let lineStart = 0; // index where the current line starts
60
+ while (position < bufLength) {
61
+ if (discardTrailingNewline) {
62
+ if (buffer[position] === 10 /* ControlChars.NewLine */) {
63
+ lineStart = ++position; // skip to next char
64
+ }
65
+ discardTrailingNewline = false;
66
+ }
67
+ // start looking forward till the end of line:
68
+ let lineEnd = -1; // index of the \r or \n char
69
+ for (; position < bufLength && lineEnd === -1; ++position) {
70
+ switch (buffer[position]) {
71
+ case 58 /* ControlChars.Colon */:
72
+ if (fieldLength === -1) {
73
+ // first colon in line
74
+ fieldLength = position - lineStart;
75
+ }
76
+ break;
77
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
78
+ // @ts-ignore:7029 \r case below should fallthrough to \n:
79
+ case 13 /* ControlChars.CarriageReturn */:
80
+ discardTrailingNewline = true;
81
+ // eslint-disable-next-line no-fallthrough
82
+ case 10 /* ControlChars.NewLine */:
83
+ lineEnd = position;
84
+ break;
85
+ }
86
+ }
87
+ if (lineEnd === -1) {
88
+ // We reached the end of the buffer but the line hasn't ended.
89
+ // Wait for the next arr and then continue parsing:
90
+ break;
91
+ }
92
+ // we've reached the line end, send it out:
93
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
94
+ lineStart = position; // we're now on the next line
95
+ fieldLength = -1;
96
+ }
97
+ if (lineStart === bufLength) {
98
+ buffer = undefined; // we've finished reading it
99
+ }
100
+ else if (lineStart !== 0) {
101
+ // Create a new view into buffer beginning at lineStart so we don't
102
+ // need to copy over the previous lines when we get the new arr:
103
+ buffer = buffer.subarray(lineStart);
104
+ position -= lineStart;
105
+ }
106
+ };
107
+ }
108
+ /**
109
+ * Parses line buffers into EventSourceMessages.
110
+ * @param onId A function that will be called on each `id` field.
111
+ * @param onRetry A function that will be called on each `retry` field.
112
+ * @param onMessage A function that will be called on each message.
113
+ * @returns A function that should be called for each incoming line buffer.
114
+ */
115
+ export function getMessages(onMessage, onId, onRetry) {
116
+ let message = newMessage();
117
+ const decoder = new TextDecoder();
118
+ // return a function that can process each incoming line buffer:
119
+ return function onLine(line, fieldLength, flush) {
120
+ if (flush) {
121
+ if (!isEmpty(message)) {
122
+ onMessage?.(message);
123
+ message = newMessage();
124
+ }
125
+ return;
126
+ }
127
+ if (line.length === 0) {
128
+ // empty line denotes end of message. Trigger the callback and start a new message:
129
+ onMessage?.(message);
130
+ message = newMessage();
131
+ }
132
+ else if (fieldLength > 0) {
133
+ // exclude comments and lines with no values
134
+ // line is of format "<field>:<value>" or "<field>: <value>"
135
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
136
+ const field = decoder.decode(line.subarray(0, fieldLength));
137
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* ControlChars.Space */ ? 2 : 1);
138
+ const value = decoder.decode(line.subarray(valueOffset));
139
+ switch (field) {
140
+ case "data":
141
+ // if this message already has data, append the new value to the old.
142
+ // otherwise, just set to the new value:
143
+ message.data = message.data ? message.data + "\n" + value : value; // otherwise,
144
+ break;
145
+ case "event":
146
+ message.event = value;
147
+ break;
148
+ case "id":
149
+ onId?.((message.id = value));
150
+ break;
151
+ case "retry": {
152
+ const retry = parseInt(value, 10);
153
+ if (!Number.isNaN(retry)) {
154
+ // per spec, ignore non-integers
155
+ onRetry?.((message.retry = retry));
156
+ }
157
+ break;
158
+ }
159
+ }
160
+ }
161
+ };
162
+ }
163
+ function concat(a, b) {
164
+ const res = new Uint8Array(a.length + b.length);
165
+ res.set(a);
166
+ res.set(b, a.length);
167
+ return res;
168
+ }
169
+ function newMessage() {
170
+ // data, event, and id must be initialized to empty strings:
171
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
172
+ // retry should be initialized to undefined so we return a consistent shape
173
+ // to the js engine all the time: https://mathiasbynens.be/notes/shapes-ics#takeaways
174
+ return {
175
+ data: "",
176
+ event: "",
177
+ id: "",
178
+ retry: undefined,
179
+ };
180
+ }
181
+ export function convertEventStreamToIterableReadableDataStream(stream) {
182
+ const dataStream = new ReadableStream({
183
+ async start(controller) {
184
+ const enqueueLine = getMessages((msg) => {
185
+ if (msg.data)
186
+ controller.enqueue(msg.data);
187
+ });
188
+ const onLine = (line, fieldLength, flush) => {
189
+ enqueueLine(line, fieldLength, flush);
190
+ if (flush)
191
+ controller.close();
192
+ };
193
+ await getBytes(stream, getLines(onLine));
194
+ },
195
+ });
196
+ return IterableReadableStream.fromReadableStream(dataStream);
197
+ }
198
+ function isEmpty(message) {
199
+ return (message.data === "" &&
200
+ message.event === "" &&
201
+ message.id === "" &&
202
+ message.retry === undefined);
203
+ }