reliable-requests 0.0.0-stage → 0.2.1
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/CHANGELOG.md +19 -0
- package/LICENSE +21 -0
- package/README.md +207 -3
- package/docs/MODEL_COMPATIBILITY.md +56 -0
- package/docs/STREAM_CONTRACT.md +68 -0
- package/docs/USAGE.md +299 -0
- package/index.d.ts +127 -0
- package/index.js +11 -0
- package/package.json +49 -6
- package/src/endpoint.js +17 -0
- package/src/index.js +128 -0
- package/src/local-chat.js +343 -0
- package/src/metrics.js +46 -0
- package/src/retry.js +48 -0
- package/src/sse.js +93 -0
- package/src/stream-events.js +69 -0
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import { reliableRequest, HttpError, RequestTimeoutError } from './index.js';
|
|
2
|
+
import { createLineParser, createSseParser } from './sse.js';
|
|
3
|
+
import { parseEndpoint, isLoopback } from './endpoint.js';
|
|
4
|
+
import { parseEvent, openaiChoice, ollamaMessage, InvalidStreamEventError } from './stream-events.js';
|
|
5
|
+
import {
|
|
6
|
+
isRetryableStatus,
|
|
7
|
+
defaultShouldRetryError,
|
|
8
|
+
retryDelayMs,
|
|
9
|
+
pause,
|
|
10
|
+
abortError,
|
|
11
|
+
discardResponse,
|
|
12
|
+
} from './retry.js';
|
|
13
|
+
|
|
14
|
+
export { InvalidStreamEventError } from './stream-events.js';
|
|
15
|
+
export { StreamLineTooLongError, StreamEventTooLongError } from './sse.js';
|
|
16
|
+
|
|
17
|
+
export class StreamInterruptedError extends Error {
|
|
18
|
+
constructor(message = 'The model stream ended before completion') {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = 'StreamInterruptedError';
|
|
21
|
+
this.code = 'STREAM_INTERRUPTED';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class ModelRedirectError extends Error {
|
|
26
|
+
constructor() {
|
|
27
|
+
super('Model endpoint redirects are not supported');
|
|
28
|
+
this.name = 'ModelRedirectError';
|
|
29
|
+
this.code = 'MODEL_REDIRECT';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class UnsupportedModelOutputError extends Error {
|
|
34
|
+
constructor() {
|
|
35
|
+
super('Tool calls are not supported by this text-only API');
|
|
36
|
+
this.name = 'UnsupportedModelOutputError';
|
|
37
|
+
this.code = 'UNSUPPORTED_MODEL_OUTPUT';
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const DEFAULT_MAX_LINE_CHARS = 262_144;
|
|
42
|
+
const HARD_MAX_LINE_CHARS = 4_194_304;
|
|
43
|
+
const MAX_DECODE_CHUNK_BYTES = 16 * 1024;
|
|
44
|
+
|
|
45
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
46
|
+
const TOOL_FINISH_REASONS = new Set(['tool_calls', 'function_call']);
|
|
47
|
+
|
|
48
|
+
function isRedirect(response) {
|
|
49
|
+
return response.redirected ||
|
|
50
|
+
response.type === 'opaqueredirect' ||
|
|
51
|
+
REDIRECT_STATUSES.has(response.status);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readOpenAIEvent(text) {
|
|
55
|
+
if (text === '[DONE]') return { done: true };
|
|
56
|
+
|
|
57
|
+
const choice = openaiChoice(parseEvent(text, 'openai'));
|
|
58
|
+
const delta = choice?.delta;
|
|
59
|
+
if (delta?.tool_calls?.length || delta?.function_call ||
|
|
60
|
+
TOOL_FINISH_REASONS.has(choice?.finish_reason)) {
|
|
61
|
+
throw new UnsupportedModelOutputError();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return { content: delta?.content, finishReason: choice?.finish_reason };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function readOllamaEvent(text) {
|
|
68
|
+
const event = parseEvent(text, 'ollama');
|
|
69
|
+
const message = ollamaMessage(event);
|
|
70
|
+
if (message?.tool_calls?.length) throw new UnsupportedModelOutputError();
|
|
71
|
+
|
|
72
|
+
return {
|
|
73
|
+
content: message?.content,
|
|
74
|
+
finishReason: event.done_reason,
|
|
75
|
+
done: event.done === true,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function readStream(response, {
|
|
80
|
+
protocol,
|
|
81
|
+
signal,
|
|
82
|
+
onText,
|
|
83
|
+
maxLineChars,
|
|
84
|
+
maxEventChars,
|
|
85
|
+
markNetworkError,
|
|
86
|
+
checkDeadline,
|
|
87
|
+
}) {
|
|
88
|
+
if (!response.body) throw new StreamInterruptedError('The response has no stream');
|
|
89
|
+
|
|
90
|
+
const reader = response.body.getReader();
|
|
91
|
+
const cancelReader = () => { reader.cancel().catch(() => {}); };
|
|
92
|
+
signal.addEventListener('abort', cancelReader, { once: true });
|
|
93
|
+
|
|
94
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
95
|
+
const decode = (bytes, options) => {
|
|
96
|
+
try {
|
|
97
|
+
return decoder.decode(bytes, options);
|
|
98
|
+
} catch {
|
|
99
|
+
throw new InvalidStreamEventError(protocol, 'UTF-8');
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
const readEvent = protocol === 'openai' ? readOpenAIEvent : readOllamaEvent;
|
|
103
|
+
let complete = false;
|
|
104
|
+
let finishReason = null;
|
|
105
|
+
|
|
106
|
+
function onLine(raw) {
|
|
107
|
+
checkDeadline();
|
|
108
|
+
const text = raw.trim();
|
|
109
|
+
if (!text) return;
|
|
110
|
+
|
|
111
|
+
const event = readEvent(text);
|
|
112
|
+
if (typeof event.finishReason === 'string') finishReason = event.finishReason;
|
|
113
|
+
if (typeof event.content === 'string' && event.content) onText(event.content);
|
|
114
|
+
if (event.done) {
|
|
115
|
+
complete = true;
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const parser = protocol === 'openai'
|
|
121
|
+
? createSseParser({ maxLineChars, maxEventChars, onData: onLine })
|
|
122
|
+
: createLineParser({ maxLineChars, onLine });
|
|
123
|
+
|
|
124
|
+
try {
|
|
125
|
+
while (!complete) {
|
|
126
|
+
let chunk;
|
|
127
|
+
try {
|
|
128
|
+
chunk = await reader.read();
|
|
129
|
+
} catch (error) {
|
|
130
|
+
markNetworkError('read');
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
checkDeadline();
|
|
135
|
+
if (signal.aborted) throw abortError();
|
|
136
|
+
const { value, done } = chunk;
|
|
137
|
+
|
|
138
|
+
if (done) {
|
|
139
|
+
let trailing;
|
|
140
|
+
try {
|
|
141
|
+
trailing = decoder.decode();
|
|
142
|
+
} catch {
|
|
143
|
+
throw new StreamInterruptedError('The model stream ended in an incomplete UTF-8 character');
|
|
144
|
+
}
|
|
145
|
+
parser.push(trailing);
|
|
146
|
+
parser.finish(protocol === 'ollama');
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
for (let offset = 0; offset < value.byteLength && !complete; offset += MAX_DECODE_CHUNK_BYTES) {
|
|
151
|
+
checkDeadline();
|
|
152
|
+
const bytes = value.subarray(offset, offset + MAX_DECODE_CHUNK_BYTES);
|
|
153
|
+
parser.push(decode(bytes, { stream: true }));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
checkDeadline();
|
|
158
|
+
if (!complete) throw new StreamInterruptedError();
|
|
159
|
+
return finishReason;
|
|
160
|
+
} finally {
|
|
161
|
+
signal.removeEventListener('abort', cancelReader);
|
|
162
|
+
cancelReader();
|
|
163
|
+
try { reader.releaseLock(); } catch {}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function shouldRetryStream(error, attempt, networkPhase, shouldRetryError) {
|
|
168
|
+
if (error instanceof HttpError) return isRetryableStatus(error.status);
|
|
169
|
+
if (error instanceof StreamInterruptedError) return true;
|
|
170
|
+
if (networkPhase === null) return false;
|
|
171
|
+
|
|
172
|
+
return shouldRetryError(error, {
|
|
173
|
+
attempt,
|
|
174
|
+
method: 'POST',
|
|
175
|
+
phase: networkPhase,
|
|
176
|
+
}) === true;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Retry a text-only local model generation, including a partially delivered stream.
|
|
181
|
+
* onEvent receives attempt, delta, reset, retry, and done events.
|
|
182
|
+
*/
|
|
183
|
+
export async function streamLocalChat({
|
|
184
|
+
endpoint,
|
|
185
|
+
protocol = 'openai',
|
|
186
|
+
model,
|
|
187
|
+
messages,
|
|
188
|
+
timeoutMs = 120_000,
|
|
189
|
+
retries = 2,
|
|
190
|
+
signal,
|
|
191
|
+
onEvent,
|
|
192
|
+
headers,
|
|
193
|
+
fetchImpl = globalThis.fetch,
|
|
194
|
+
shouldRetryError = defaultShouldRetryError,
|
|
195
|
+
allowRemoteRetries = false,
|
|
196
|
+
maxLineChars = DEFAULT_MAX_LINE_CHARS,
|
|
197
|
+
maxEventChars = maxLineChars,
|
|
198
|
+
} = {}) {
|
|
199
|
+
if (protocol !== 'openai' && protocol !== 'ollama') throw new TypeError('protocol must be openai or ollama');
|
|
200
|
+
if (!model || typeof model !== 'string') throw new TypeError('model is required');
|
|
201
|
+
if (!Array.isArray(messages) || !messages.every(m => typeof m?.role === 'string' && typeof m?.content === 'string')) {
|
|
202
|
+
throw new TypeError('messages must contain text-only role/content pairs');
|
|
203
|
+
}
|
|
204
|
+
if (typeof onEvent !== 'function') throw new TypeError('onEvent is required');
|
|
205
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) throw new RangeError('invalid timeoutMs');
|
|
206
|
+
if (!Number.isSafeInteger(retries) || retries < 0) throw new RangeError('invalid retries');
|
|
207
|
+
if (!Number.isSafeInteger(maxLineChars) || maxLineChars < 1 || maxLineChars > HARD_MAX_LINE_CHARS) {
|
|
208
|
+
throw new RangeError('maxLineChars must be an integer between 1 and 4194304');
|
|
209
|
+
}
|
|
210
|
+
if (!Number.isSafeInteger(maxEventChars) || maxEventChars < 1 || maxEventChars > HARD_MAX_LINE_CHARS) {
|
|
211
|
+
throw new RangeError('maxEventChars must be an integer between 1 and 4194304');
|
|
212
|
+
}
|
|
213
|
+
if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
|
|
214
|
+
if (typeof shouldRetryError !== 'function') throw new TypeError('shouldRetryError must be a function');
|
|
215
|
+
const base = parseEndpoint(endpoint);
|
|
216
|
+
if (retries > 0 && !isLoopback(base) && !allowRemoteRetries) {
|
|
217
|
+
throw new Error('Retries for remote servers require allowRemoteRetries: true');
|
|
218
|
+
}
|
|
219
|
+
const url = base;
|
|
220
|
+
const path = url.pathname.replace(/\/+$/, '');
|
|
221
|
+
if (protocol === 'ollama') {
|
|
222
|
+
url.pathname = path + '/api/chat';
|
|
223
|
+
} else {
|
|
224
|
+
const versionPath = path.endsWith('/v1') ? path : path + '/v1';
|
|
225
|
+
url.pathname = versionPath + '/chat/completions';
|
|
226
|
+
}
|
|
227
|
+
url.search = '';
|
|
228
|
+
url.hash = '';
|
|
229
|
+
const requestHeaders = new Headers(headers);
|
|
230
|
+
requestHeaders.set('content-type', 'application/json');
|
|
231
|
+
const payload = { model, messages, stream: true };
|
|
232
|
+
if (protocol === 'openai') payload.n = 1;
|
|
233
|
+
const body = JSON.stringify(payload);
|
|
234
|
+
const controller = new AbortController();
|
|
235
|
+
let expired = false;
|
|
236
|
+
const callerAbort = () => controller.abort();
|
|
237
|
+
if (signal?.aborted) throw abortError();
|
|
238
|
+
signal?.addEventListener('abort', callerAbort, { once: true });
|
|
239
|
+
const started = performance.now();
|
|
240
|
+
const timer = setTimeout(() => {
|
|
241
|
+
expired = true;
|
|
242
|
+
controller.abort();
|
|
243
|
+
}, timeoutMs);
|
|
244
|
+
const remainingMs = () => timeoutMs - (performance.now() - started);
|
|
245
|
+
const checkDeadline = () => {
|
|
246
|
+
if (expired || remainingMs() <= 0) {
|
|
247
|
+
expired = true;
|
|
248
|
+
controller.abort();
|
|
249
|
+
throw new RequestTimeoutError(timeoutMs);
|
|
250
|
+
}
|
|
251
|
+
if (controller.signal.aborted) throw abortError();
|
|
252
|
+
};
|
|
253
|
+
let callbackFailed = false;
|
|
254
|
+
const emit = event => {
|
|
255
|
+
checkDeadline();
|
|
256
|
+
try {
|
|
257
|
+
onEvent(event);
|
|
258
|
+
} catch (error) {
|
|
259
|
+
callbackFailed = true;
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
try {
|
|
264
|
+
for (let attempt = 1; attempt <= retries + 1; attempt++) {
|
|
265
|
+
checkDeadline();
|
|
266
|
+
let partial = false;
|
|
267
|
+
let networkPhase = null;
|
|
268
|
+
emit({ type: 'attempt', attempt });
|
|
269
|
+
try {
|
|
270
|
+
checkDeadline();
|
|
271
|
+
const remaining = Math.max(1, Math.ceil(remainingMs()));
|
|
272
|
+
const finishReason = await reliableRequest(url, {
|
|
273
|
+
method: 'POST',
|
|
274
|
+
body,
|
|
275
|
+
headers: requestHeaders,
|
|
276
|
+
retries: 0,
|
|
277
|
+
redirect: 'manual',
|
|
278
|
+
timeoutMs: remaining,
|
|
279
|
+
signal: controller.signal,
|
|
280
|
+
fetchImpl: async (...args) => {
|
|
281
|
+
let response;
|
|
282
|
+
try {
|
|
283
|
+
response = await fetchImpl(...args);
|
|
284
|
+
} catch (error) {
|
|
285
|
+
networkPhase = 'fetch';
|
|
286
|
+
throw error;
|
|
287
|
+
}
|
|
288
|
+
if (isRedirect(response)) {
|
|
289
|
+
discardResponse(response);
|
|
290
|
+
throw new ModelRedirectError();
|
|
291
|
+
}
|
|
292
|
+
return response;
|
|
293
|
+
},
|
|
294
|
+
consume: (response, readSignal) => readStream(response, {
|
|
295
|
+
protocol,
|
|
296
|
+
signal: readSignal,
|
|
297
|
+
maxLineChars,
|
|
298
|
+
maxEventChars,
|
|
299
|
+
checkDeadline,
|
|
300
|
+
markNetworkError: phase => { networkPhase = phase; },
|
|
301
|
+
onText(text) {
|
|
302
|
+
partial = true;
|
|
303
|
+
emit({ type: 'delta', attempt, text });
|
|
304
|
+
},
|
|
305
|
+
}),
|
|
306
|
+
});
|
|
307
|
+
checkDeadline();
|
|
308
|
+
const completion = finishReason === null ? {} : { finishReason };
|
|
309
|
+
emit({ type: 'done', attempt, ...completion });
|
|
310
|
+
return { attempts: attempt, ...completion };
|
|
311
|
+
} catch (error) {
|
|
312
|
+
if (callbackFailed) throw error;
|
|
313
|
+
if (expired || error instanceof RequestTimeoutError) throw new RequestTimeoutError(timeoutMs);
|
|
314
|
+
if (controller.signal.aborted) throw abortError();
|
|
315
|
+
checkDeadline();
|
|
316
|
+
if (attempt > retries || error?.name === 'AbortError') throw error;
|
|
317
|
+
if (!shouldRetryStream(error, attempt, networkPhase, shouldRetryError)) throw error;
|
|
318
|
+
|
|
319
|
+
const response = error instanceof HttpError ? error.response : undefined;
|
|
320
|
+
if (response) discardResponse(response);
|
|
321
|
+
const delayMs = retryDelayMs({ attempt, response, remainingMs: remainingMs() });
|
|
322
|
+
if (delayMs === null) {
|
|
323
|
+
throw new RequestTimeoutError(timeoutMs, 'Retry delay cannot fit within the ' + timeoutMs + ' ms total timeout');
|
|
324
|
+
}
|
|
325
|
+
emit({ type: 'retry', attempt, error, partial, delayMs });
|
|
326
|
+
checkDeadline();
|
|
327
|
+
try {
|
|
328
|
+
await pause(delayMs, controller.signal);
|
|
329
|
+
} catch (waitError) {
|
|
330
|
+
if (expired) throw new RequestTimeoutError(timeoutMs);
|
|
331
|
+
throw waitError;
|
|
332
|
+
}
|
|
333
|
+
checkDeadline();
|
|
334
|
+
if (partial) emit({ type: 'reset', attempt: attempt + 1 });
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
} finally {
|
|
338
|
+
clearTimeout(timer);
|
|
339
|
+
signal?.removeEventListener('abort', callerAbort);
|
|
340
|
+
controller.abort();
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
package/src/metrics.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional, lightweight stream diagnostics.
|
|
3
|
+
* Characters are JavaScript string lengths, NOT tokens or network bytes.
|
|
4
|
+
* This observer never changes retry behavior and sends no telemetry.
|
|
5
|
+
*/
|
|
6
|
+
export function createStreamMetrics({ now = () => performance.now() } = {}) {
|
|
7
|
+
if (typeof now !== 'function') throw new TypeError('now must be a function');
|
|
8
|
+
const startedAt = now();
|
|
9
|
+
let finishedAt = null;
|
|
10
|
+
const state = {
|
|
11
|
+
attempts: 0, retries: 0, resets: 0, deltaEvents: 0,
|
|
12
|
+
receivedCharacters: 0, visibleCharacters: 0,
|
|
13
|
+
timeToFirstDeltaMs: null, completed: false,
|
|
14
|
+
};
|
|
15
|
+
const elapsed = (end = now()) => Math.max(0, Math.round(end - startedAt));
|
|
16
|
+
return {
|
|
17
|
+
record(event) {
|
|
18
|
+
if (!event || typeof event.type !== 'string') return;
|
|
19
|
+
if (event.type === 'attempt') state.attempts++;
|
|
20
|
+
if (event.type === 'retry') state.retries++;
|
|
21
|
+
if (event.type === 'reset') {
|
|
22
|
+
state.resets++;
|
|
23
|
+
state.visibleCharacters = 0;
|
|
24
|
+
}
|
|
25
|
+
if (event.type === 'delta' && typeof event.text === 'string') {
|
|
26
|
+
if (state.timeToFirstDeltaMs === null) state.timeToFirstDeltaMs = elapsed();
|
|
27
|
+
state.deltaEvents++;
|
|
28
|
+
state.receivedCharacters += event.text.length;
|
|
29
|
+
state.visibleCharacters += event.text.length;
|
|
30
|
+
}
|
|
31
|
+
if (event.type === 'done') {
|
|
32
|
+
state.completed = true;
|
|
33
|
+
if (finishedAt === null) finishedAt = now();
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
finish() {
|
|
37
|
+
if (finishedAt === null) finishedAt = now();
|
|
38
|
+
},
|
|
39
|
+
snapshot() {
|
|
40
|
+
return Object.freeze({
|
|
41
|
+
...state,
|
|
42
|
+
elapsedMs: elapsed(finishedAt === null ? now() : finishedAt),
|
|
43
|
+
});
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
package/src/retry.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
const RETRY_STATUSES = new Set([429, 500, 502, 503, 504]);
|
|
2
|
+
|
|
3
|
+
export const isRetryableStatus = status => RETRY_STATUSES.has(status);
|
|
4
|
+
export const defaultShouldRetryError = error => error instanceof TypeError;
|
|
5
|
+
export const abortError = () => new DOMException('Request cancelled', 'AbortError');
|
|
6
|
+
|
|
7
|
+
export function retryAfterMs(response, now = Date.now()) {
|
|
8
|
+
const value = response?.headers?.get('retry-after')?.trim();
|
|
9
|
+
if (!value) return null;
|
|
10
|
+
if (/^\d+(?:\.\d+)?$/.test(value)) {
|
|
11
|
+
const seconds = Number(value);
|
|
12
|
+
return Number.isFinite(seconds) ? seconds * 1000 : Infinity;
|
|
13
|
+
}
|
|
14
|
+
if (!/[A-Za-z]/.test(value)) return null;
|
|
15
|
+
const date = Date.parse(value);
|
|
16
|
+
return Number.isFinite(date) ? Math.max(0, date - now) : null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function retryDelayMs({ attempt, response, remainingMs, random = Math.random, now = Date.now() }) {
|
|
20
|
+
const retryAfter = retryAfterMs(response, now);
|
|
21
|
+
const backoff = Math.min(250 * 2 ** (attempt - 1), 5_000);
|
|
22
|
+
const jitter = random();
|
|
23
|
+
const delay = Math.ceil(retryAfter === null
|
|
24
|
+
? backoff * (0.8 + 0.2 * jitter)
|
|
25
|
+
: retryAfter + Math.min(backoff * 0.2, 250) * jitter);
|
|
26
|
+
return Number.isFinite(delay) && delay < remainingMs ? delay : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function pause(ms, signal) {
|
|
30
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
31
|
+
return new Promise((resolve, reject) => {
|
|
32
|
+
const cleanup = () => signal.removeEventListener('abort', onAbort);
|
|
33
|
+
const onAbort = () => {
|
|
34
|
+
clearTimeout(timer);
|
|
35
|
+
cleanup();
|
|
36
|
+
reject(signal.reason);
|
|
37
|
+
};
|
|
38
|
+
const timer = setTimeout(() => {
|
|
39
|
+
cleanup();
|
|
40
|
+
resolve();
|
|
41
|
+
}, ms);
|
|
42
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function discardResponse(response) {
|
|
47
|
+
try { response?.body?.cancel?.().catch(() => {}); } catch {}
|
|
48
|
+
}
|
package/src/sse.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export class StreamLineTooLongError extends Error {
|
|
2
|
+
constructor(maxLineChars) {
|
|
3
|
+
super('A model stream line exceeded the ' + maxLineChars + ' character limit');
|
|
4
|
+
this.name = 'StreamLineTooLongError';
|
|
5
|
+
this.code = 'STREAM_LINE_TOO_LONG';
|
|
6
|
+
this.maxLineChars = maxLineChars;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export class StreamEventTooLongError extends Error {
|
|
11
|
+
constructor(maxEventChars) {
|
|
12
|
+
super('A model stream event exceeded the ' + maxEventChars + ' character limit');
|
|
13
|
+
this.name = 'StreamEventTooLongError';
|
|
14
|
+
this.code = 'STREAM_EVENT_TOO_LONG';
|
|
15
|
+
this.maxEventChars = maxEventChars;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createLineParser({ maxLineChars, onLine }) {
|
|
20
|
+
let buffer = '';
|
|
21
|
+
let skipNextLF = false;
|
|
22
|
+
let stopped = false;
|
|
23
|
+
|
|
24
|
+
function push(text) {
|
|
25
|
+
let start = 0;
|
|
26
|
+
if (skipNextLF && text.length) {
|
|
27
|
+
if (text[0] === '\n') start = 1;
|
|
28
|
+
skipNextLF = false;
|
|
29
|
+
}
|
|
30
|
+
while (start < text.length && !stopped) {
|
|
31
|
+
let end = start;
|
|
32
|
+
while (end < text.length && text[end] !== '\r' && text[end] !== '\n') end++;
|
|
33
|
+
if (buffer.length + end - start > maxLineChars) {
|
|
34
|
+
throw new StreamLineTooLongError(maxLineChars);
|
|
35
|
+
}
|
|
36
|
+
buffer += text.slice(start, end);
|
|
37
|
+
if (end === text.length) break;
|
|
38
|
+
const line = buffer;
|
|
39
|
+
buffer = '';
|
|
40
|
+
stopped = onLine(line) === false;
|
|
41
|
+
start = end + 1;
|
|
42
|
+
if (text[end] === '\r') {
|
|
43
|
+
if (text[start] === '\n') start++;
|
|
44
|
+
else if (start === text.length) skipNextLF = true;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function finish(flushTrailing = false) {
|
|
50
|
+
if (!stopped && flushTrailing && buffer.length) onLine(buffer);
|
|
51
|
+
buffer = '';
|
|
52
|
+
stopped = true;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return { push, finish };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function createSseParser({ maxLineChars, maxEventChars, onData }) {
|
|
59
|
+
let data = '';
|
|
60
|
+
let hasData = false;
|
|
61
|
+
const lines = createLineParser({
|
|
62
|
+
maxLineChars,
|
|
63
|
+
onLine(line) {
|
|
64
|
+
if (line === '') {
|
|
65
|
+
if (!hasData) return;
|
|
66
|
+
const event = data;
|
|
67
|
+
data = '';
|
|
68
|
+
hasData = false;
|
|
69
|
+
return onData(event);
|
|
70
|
+
}
|
|
71
|
+
if (line[0] === ':') return;
|
|
72
|
+
const colon = line.indexOf(':');
|
|
73
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
74
|
+
if (field !== 'data') return;
|
|
75
|
+
let value = colon < 0 ? '' : line.slice(colon + 1);
|
|
76
|
+
if (value[0] === ' ') value = value.slice(1);
|
|
77
|
+
const length = data.length + (hasData ? 1 : 0) + value.length;
|
|
78
|
+
if (length > maxEventChars) {
|
|
79
|
+
throw new StreamEventTooLongError(maxEventChars);
|
|
80
|
+
}
|
|
81
|
+
data += (hasData ? '\n' : '') + value;
|
|
82
|
+
hasData = true;
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
return {
|
|
86
|
+
push: lines.push,
|
|
87
|
+
finish() {
|
|
88
|
+
lines.finish();
|
|
89
|
+
data = '';
|
|
90
|
+
hasData = false;
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
export class InvalidStreamEventError extends Error {
|
|
2
|
+
constructor(protocol, field) {
|
|
3
|
+
super('Invalid ' + (protocol === 'openai' ? 'OpenAI-compatible' : 'Ollama') + ' stream event' + (field ? ': ' + field : ''));
|
|
4
|
+
this.name = 'InvalidStreamEventError';
|
|
5
|
+
this.code = 'INVALID_STREAM_EVENT';
|
|
6
|
+
this.field = field;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
11
|
+
const isOptionalText = value => value === undefined || value === null || typeof value === 'string';
|
|
12
|
+
|
|
13
|
+
function requireField(condition, protocol, field) {
|
|
14
|
+
if (!condition) throw new InvalidStreamEventError(protocol, field);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function parseEvent(text, protocol) {
|
|
18
|
+
let event;
|
|
19
|
+
try {
|
|
20
|
+
event = JSON.parse(text);
|
|
21
|
+
} catch {
|
|
22
|
+
throw new InvalidStreamEventError(protocol);
|
|
23
|
+
}
|
|
24
|
+
requireField(isObject(event), protocol, 'event');
|
|
25
|
+
return event;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function openaiChoice(event) {
|
|
29
|
+
const protocol = 'openai';
|
|
30
|
+
if (event.error != null) {
|
|
31
|
+
requireField(typeof event.error === 'string' || isObject(event.error), protocol, 'error');
|
|
32
|
+
if (isObject(event.error)) requireField(isOptionalText(event.error.message), protocol, 'error.message');
|
|
33
|
+
throw new Error(typeof event.error === 'string' ? event.error : event.error.message || 'Model stream error');
|
|
34
|
+
}
|
|
35
|
+
if (event.choices === undefined) return undefined;
|
|
36
|
+
requireField(Array.isArray(event.choices), protocol, 'choices');
|
|
37
|
+
requireField(event.choices.length <= 1, protocol, 'choices (only one generation is supported)');
|
|
38
|
+
if (!event.choices.length) return undefined;
|
|
39
|
+
const choice = event.choices[0];
|
|
40
|
+
requireField(isObject(choice), protocol, 'choices[]');
|
|
41
|
+
requireField(choice.index === undefined || choice.index === 0, protocol, 'choice.index (only index 0 is supported)');
|
|
42
|
+
requireField(isOptionalText(choice.finish_reason), protocol, 'finish_reason');
|
|
43
|
+
const { delta } = choice;
|
|
44
|
+
if (delta != null) {
|
|
45
|
+
requireField(isObject(delta), protocol, 'delta');
|
|
46
|
+
requireField(isOptionalText(delta.content), protocol, 'delta.content');
|
|
47
|
+
requireField(isOptionalText(delta.role), protocol, 'delta.role');
|
|
48
|
+
requireField(delta.tool_calls == null || Array.isArray(delta.tool_calls), protocol, 'delta.tool_calls');
|
|
49
|
+
requireField(delta.function_call == null || isObject(delta.function_call), protocol, 'delta.function_call');
|
|
50
|
+
}
|
|
51
|
+
return choice;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function ollamaMessage(event) {
|
|
55
|
+
const protocol = 'ollama';
|
|
56
|
+
if (event.error != null) {
|
|
57
|
+
requireField(typeof event.error === 'string', protocol, 'error');
|
|
58
|
+
throw new Error(event.error);
|
|
59
|
+
}
|
|
60
|
+
requireField(event.done === undefined || typeof event.done === 'boolean', protocol, 'done');
|
|
61
|
+
requireField(isOptionalText(event.done_reason), protocol, 'done_reason');
|
|
62
|
+
const { message } = event;
|
|
63
|
+
if (message == null) return undefined;
|
|
64
|
+
requireField(isObject(message), protocol, 'message');
|
|
65
|
+
requireField(isOptionalText(message.content), protocol, 'message.content');
|
|
66
|
+
requireField(isOptionalText(message.role), protocol, 'message.role');
|
|
67
|
+
requireField(message.tool_calls == null || Array.isArray(message.tool_calls), protocol, 'message.tool_calls');
|
|
68
|
+
return message;
|
|
69
|
+
}
|