-
Notifications
You must be signed in to change notification settings - Fork 2
/
fetch_jsonstream.ts
193 lines (172 loc) · 5.19 KB
/
fetch_jsonstream.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
import autofetch from "./autofetch"; // isomorphic fetch
export interface OllamaAPIError {
error: string;
}
export type OllamaAPIErrorOrResponse = OllamaAPIError | false;
export interface OllamaStreamResponse {
model: string;
created_at: string;
response: string;
context?: number[];
done: boolean;
total_duration?: number;
load_duration?: number;
sample_count?: number;
sample_duration?: number;
prompt_eval_count?: number;
prompt_eval_duration?: number;
eval_count?: number;
eval_duration?: number;
}
export type OllamaStreamCallbackType = (
error: OllamaAPIErrorOrResponse,
response?: OllamaStreamResponse
) => void;
// Helper function to determine environment
const isNode = (): boolean => typeof window === "undefined";
// Helper function to determine if the stream is a browser ReadableStream
function isBrowserReadableStream(
stream: any
): stream is ReadableStream<Uint8Array> {
return !!stream && typeof stream.getReader === "function";
}
// Main class to fetch and process the JSON stream
export default class FetchJSONStream {
private abortController: AbortController;
constructor() {
this.abortController = new AbortController();
}
abort() {
this.abortController.abort();
}
private async processStreamReader(
reader: ReadableStreamDefaultReader<Uint8Array>,
decoder: TextDecoder,
callback: OllamaStreamCallbackType
) {
let buffer = "";
try {
let result;
while (((result = await reader.read()), !result.done)) {
buffer = this.processBuffer(
buffer + decoder.decode(result.value, { stream: true }),
callback
);
}
if (buffer.length > 0) {
this.processBuffer(buffer, callback, true); // Process any remaining data
}
} catch (error) {
if (error instanceof Error) {
callback({ error: error.message });
} else {
callback({ error: String(error) });
}
}
}
private async processNodeStream(
stream: NodeJS.ReadableStream,
decoder: TextDecoder,
callback: OllamaStreamCallbackType
) {
let buffer = "";
stream.on("data", (chunk) => {
buffer = this.processBuffer(
buffer + decoder.decode(chunk, { stream: true }),
callback
);
});
stream.on("end", () => {
if (buffer.length > 0) {
this.processBuffer(buffer, callback, true); // Process any remaining data
}
});
stream.on("error", (error) => {
callback({ error: error.message });
});
}
private processBuffer(
buffer: string,
callback: OllamaStreamCallbackType,
flush: boolean = false
): string {
let newlineIndex;
let lastJson: OllamaStreamResponse | null = null;
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
const line = buffer.slice(0, newlineIndex).trim();
buffer = buffer.slice(newlineIndex + 1);
if (line) {
try {
const json: OllamaStreamResponse = JSON.parse(line);
lastJson = json; // Keep the last valid JSON
callback(false, json);
} catch (error) {
console.error(`Failed to parse JSON line: ${line}`, error);
}
}
}
// Flush the buffer if true, which is the case when the stream ends.
if (flush && buffer.trim()) {
try {
const json: OllamaStreamResponse = JSON.parse(buffer);
callback(false, json);
} catch (error) {
// If there's an error parsing the buffer, check if we had a previous valid JSON object
// and if it indicated that the stream was done.
if (lastJson && lastJson.done) {
callback(false, lastJson);
} else {
console.error(`Failed to parse JSON buffer: ${buffer}`, error);
}
} finally {
buffer = ""; // Clear buffer after processing
}
} else if (lastJson && lastJson.done) {
// If the stream indicated it's done, but no newline was found, clear the buffer.
buffer = "";
}
return buffer;
}
public async fetch(
url: string,
headers: HeadersInit,
postData: string,
callback: OllamaStreamCallbackType
) {
try {
const response = await autofetch(url, {
signal: this.abortController.signal,
method: "POST",
headers: {
"Content-Type": "application/json",
...headers,
},
body: postData,
});
if (!response.ok) {
callback({ error: `HTTP error! status: ${response.status}` });
return;
}
const decoder = new TextDecoder("utf-8");
if (isNode()) {
// Handle Node.js streams
const { Readable } = await import("stream");
if (response.body instanceof Readable) {
return this.processNodeStream(response.body, decoder, callback);
}
} else if (isBrowserReadableStream(response.body)) {
// Handle browser streams
const reader = response.body.getReader();
return this.processStreamReader(reader, decoder, callback);
} else {
callback({ error: "Unrecognized stream type" });
}
} catch (error) {
if (error instanceof Error) {
callback({ error: error.message });
} else {
callback({ error: String(error) });
}
}
}
}