Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | 2x 28x 28x 28x 28x 28x 10x 10x 10x 10x 10x 1x 9x 1x 8x 8x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 12x 12x 7x 7x 7x 7x 7x 61x 61x 61x 9x 9x 1x 8x 53x 1x 1x 1x 52x 52x 52x 1x 51x 2x 2x 2x 7x 7x 5x 5x 5x 5x 5x 1x 4x 4x 4x 4x 21x 3x 3x | import { OllamaMessage, OllamaTool, ToolCall } from './types';
interface FetchResponse {
ok: boolean;
status: number;
headers?: {
get: (name: string) => string | null;
};
body?: {
getReader: () => ReadableStreamDefaultReader<Uint8Array>;
} | null;
json?: () => Promise<any>;
}
interface FetchOptions {
method: string;
headers: Record<string, string>;
body: string;
signal?: AbortSignal;
}
export class OllamaClient {
private url: string;
private model: string;
private abortController: AbortController | null = null;
// Mock fetch function for testing
private fetchFn: typeof fetch = fetch;
constructor(url: string, model: string, fetchFn?: typeof fetch) {
this.url = url;
this.model = model;
if (fetchFn) this.fetchFn = fetchFn;
}
async streamChat(
messages: OllamaMessage[],
tools: OllamaTool[],
timeoutMs: number = 60000
): Promise<AsyncIterable<{ content: string; tool_calls?: ToolCall[] }>> {
this.abortController = new AbortController();
const timeoutId = setTimeout(() => {
this.abortController?.abort();
}, timeoutMs);
let response: FetchResponse;
try {
response = await this.fetchFn(`${this.url}/api/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: this.model,
messages,
tools,
stream: true,
}),
signal: this.abortController.signal,
} as FetchOptions);
} catch (fetchError: any) {
clearTimeout(timeoutId);
this.abortController = null;
Iif (fetchError.name === 'AbortError' || fetchError.code === 'ABORT_ERR') {
throw new Error('Request timeout while connecting to Ollama');
}
throw fetchError;
}
if (!response.ok) {
throw new Error(`Ollama API error: ${response.status}`);
}
if (!response.body) {
throw new Error('No response body');
}
// Validate response structure
const contentType = response.headers?.get('content-type');
if (!contentType?.match(/application\/(x-ndjson|json)/)) {
throw new Error('Invalid response format');
}
const reader = response.body.getReader();
const self = this;
return {
[Symbol.asyncIterator]: async function* () {
const decoder = new TextDecoder();
let buffer = '';
let chunkCount = 0;
let skippedChunks = 0;
const maxChunks = 1000; // Safety limit
const maxSkipped = 50; // Fail if too many chunks are malformed
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
Iif (++chunkCount > maxChunks) {
throw new Error('Response too long, stopped streaming');
}
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
Iif (line.trim() === '') continue;
try {
const data = JSON.parse(line);
if (data.message && typeof data.message === 'object') {
// Validate message structure
if (data.message.error && typeof data.message.error === 'string') {
throw new Error(`Ollama error: ${data.message.error}`);
}
yield {
content: data.message.content || '',
tool_calls: Array.isArray(data.message.tool_calls)
? data.message.tool_calls
: [],
};
}
} catch (parseError) {
// Check if this is an Ollama error (thrown intentionally) vs a parse error
if (parseError instanceof Error && parseError.message.startsWith('Ollama error:')) {
// This is an intentional Ollama error, re-throw it
self.abortController = null;
reader.releaseLock();
throw parseError;
}
// This is a parse error, skip the malformed chunk
skippedChunks++;
console.warn(
`[OllamaClient] Skipped malformed chunk ${skippedChunks}/${maxSkipped}:`,
parseError instanceof Error ? parseError.message : String(parseError)
);
if (skippedChunks > maxSkipped) {
throw new Error(
`Too many malformed response chunks (${skippedChunks}). Connection may be degraded.`
);
}
// Skip invalid chunks but continue streaming
continue;
}
}
}
} catch (streamError) {
self.abortController = null;
Iif (streamError instanceof Error && streamError.name === 'AbortError') {
throw new Error('Streaming request was cancelled');
}
throw streamError;
} finally {
reader.releaseLock();
self.abortController = null;
}
},
};
}
async chat(
messages: OllamaMessage[],
tools: OllamaTool[],
timeoutMs: number = 30000
): Promise<{ content: string; tool_calls?: ToolCall[] }> {
const abortController = new AbortController();
const timeoutId = setTimeout(() => {
abortController.abort();
}, timeoutMs);
const response = await this.fetchFn(`${this.url}/api/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: this.model,
messages,
tools,
stream: false,
}),
signal: abortController.signal,
} as FetchOptions);
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`Ollama API error: ${response.status}`);
}
const responseData = await response.json();
const data = responseData;
const messageData = data.message;
return {
content: messageData?.content || '',
tool_calls: messageData?.tool_calls || [],
};
}
cancelStream(): void {
if (this.abortController) {
this.abortController.abort();
this.abortController = null;
}
}
}
|