reliable-requests 0.2.0 → 0.3.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/CHANGELOG.md +33 -13
- package/LICENSE +21 -21
- package/README.md +207 -99
- package/docs/MODEL_COMPATIBILITY.md +90 -0
- package/docs/STREAM_CONTRACT.md +72 -0
- package/docs/USAGE.md +313 -295
- package/index.d.ts +138 -127
- package/index.js +12 -11
- package/package.json +51 -46
- package/src/endpoint.js +17 -17
- package/src/index.js +128 -128
- package/src/local-chat.js +403 -343
- package/src/metrics.js +46 -46
- package/src/retry.js +48 -48
- package/src/sse.js +93 -93
- package/src/stream-events.js +69 -69
package/src/metrics.js
CHANGED
|
@@ -1,46 +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
|
-
}
|
|
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
CHANGED
|
@@ -1,48 +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
|
-
}
|
|
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
CHANGED
|
@@ -1,93 +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
|
-
}
|
|
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
|
+
}
|
package/src/stream-events.js
CHANGED
|
@@ -1,69 +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
|
-
}
|
|
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
|
+
}
|