All files ollama-client.ts

91.37% Statements 106/116
72.22% Branches 39/54
87.5% Functions 14/16
90.9% Lines 100/110

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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277      2x 2x           2x       59x     59x 59x 59x             20x             3x 3x                       25x   25x 25x                           25x 8x 5x 5x       5x 4x 4x     4x 4x 4x 4x 4x     4x           4x           5x 2x   3x     13x 1x     12x 12x 1x     11x 11x 11x 11x 11x   11x 11x 19x 19x   10x   10x 10x   10x 68x   67x 67x 14x   13x 13x       13x 13x   54x 1x     53x 53x 1x     52x               9x 1x 1x 1x   1x 1x 1x                         11x       25x         5x                 8x 8x 8x                           8x 4x 3x 3x       3x 2x 2x     2x 2x 2x 2x 2x     2x           2x           3x   1x     4x 4x         8x         15x 1x         18x 1x     17x 17x              
// src/ollama-client.ts
 
import type { OllamaMessage, OllamaTool } from './types';
import { ApiError } from './types';
import { Logger } from './utils';
 
interface OllamaChatResponse {
  message?: Partial<OllamaMessage>;
}
 
export class OllamaClient {
  private baseURL: string;
  private model: string;
  private fetchFn: typeof fetch;
  private readonly maxRetries: number = 3;
 
  constructor(baseURL: string, model: string, fetchFn?: typeof fetch) {
    this.baseURL = baseURL;
    this.model = model;
    this.fetchFn = fetchFn ?? fetch;
  }
 
  async *streamChat(
    messages: OllamaMessage[],
    tools: OllamaTool[] = []
  ): AsyncGenerator<OllamaMessage, void, unknown> {
    yield* this.streamChatWithRetry(messages, tools, 0);
  }
 
  async streamChatAsPromise(
    messages: OllamaMessage[],
    tools: OllamaTool[] = []
  ): Promise<OllamaMessage[]> {
    const chunks: OllamaMessage[] = [];
    for await (const chunk of this.streamChat(messages, tools)) {
      chunks.push(chunk);
    }
    return chunks;
  }
 
  private async *streamChatWithRetry(
    messages: OllamaMessage[],
    tools: OllamaTool[] = [],
    attempt: number = 0
  ): AsyncGenerator<OllamaMessage, void, unknown> {
    // Create a local controller for this request instead of using the instance variable
    const controller = new AbortController();
 
    try {
      const response = await this.fetchFn(`${this.baseURL}/api/chat`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model: this.model,
          messages,
          tools,
          stream: true,
        }),
        signal: controller.signal,
      });
 
      if (!response.ok) {
        if (response.status >= 500 && attempt < this.maxRetries) {
          const retryDelay = Math.pow(2, attempt) * 100;
          Logger.warn(
            `Network error (status ${response.status}), retrying in ${retryDelay}ms (attempt ${attempt + 1}/${this.maxRetries})`,
            'ollama-client'
          );
          if (attempt < this.maxRetries - 1) {
            const retryTimeout = new Promise((resolve) => setTimeout(resolve, retryDelay));
            const abortListener = () => {
              Logger.info('Retry aborted by user', 'ollama-client');
            };
            const signal = controller.signal;
            if (signal) {
              signal.addEventListener('abort', abortListener);
              try {
                await Promise.race([
                  retryTimeout,
                  new Promise<void>((resolve) => {
                    signal.addEventListener('abort', () => resolve(), {
                      once: true,
                    });
                  }),
                ]);
              } finally {
                signal.removeEventListener('abort', abortListener);
              }
            } else E{
              await retryTimeout;
            }
          }
          yield* this.streamChatWithRetry(messages, tools, attempt + 1);
          return;
        }
        throw new ApiError(`Ollama API error: ${response.status}`, response.status);
      }
 
      if (!response.body) {
        throw new Error('No response body');
      }
 
      const contentType = response.headers.get('content-type');
      if (!contentType || (!contentType.includes('ndjson') && !contentType.includes('json'))) {
        throw new Error('Invalid response format');
      }
 
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';
      let malformedCount = 0;
      const maxMalformed = 50;
 
      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
 
          buffer += decoder.decode(value, { stream: true });
 
          const lines = buffer.split('\n');
          buffer = lines.pop() ?? '';
 
          for (const line of lines) {
            if (!line.trim()) continue;
 
            try {
              const parsed = JSON.parse(line) as Record<string, unknown>;
              this.throwIfOllamaError(parsed);
 
              const message = this.toOllamaMessage(parsed.message);
              Iif (!message) {
                continue;
              }
 
              malformedCount = 0;
              yield message;
            } catch (error) {
              if (error instanceof Error && error.message.startsWith('Ollama error:')) {
                throw error;
              }
 
              malformedCount++;
              if (malformedCount > maxMalformed) {
                throw new Error('Too many malformed chunks in stream');
              }
 
              Logger.warn(
                `Skipped malformed chunk: ${line.substring(0, 80)}... - ${(error as Error).message}`,
                'ollama-client'
              );
            }
          }
        }
 
        if (buffer.trim()) {
          try {
            const parsed = JSON.parse(buffer) as Record<string, unknown>;
            this.throwIfOllamaError(parsed);
 
            const message = this.toOllamaMessage(parsed.message);
            if (message) {
              yield message;
            }
          } catch (error) {
            Iif (error instanceof Error && error.message.startsWith('Ollama error:')) {
              throw error;
            }
            Logger.warn(
              `Failed to parse final chunk: ${buffer.substring(0, 80)}...`,
              'ollama-client'
            );
          }
        }
      } finally {
        reader.releaseLock();
      }
    } finally {
      // Abort the local controller
      controller.abort();
    }
  }
 
  async chat(messages: OllamaMessage[], tools: OllamaTool[] = []): Promise<OllamaMessage> {
    return this.chatWithRetry(messages, tools, 0);
  }
 
  private async chatWithRetry(
    messages: OllamaMessage[],
    tools: OllamaTool[] = [],
    attempt: number = 0
  ): Promise<OllamaMessage> {
    // Create a local controller for this request instead of using the instance variable
    const controller = new AbortController();
    try {
      const response = await this.fetchFn(`${this.baseURL}/api/chat`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model: this.model,
          messages,
          tools,
          stream: false,
        }),
        signal: controller.signal,
      });
 
      if (!response.ok) {
        if (response.status >= 500 && attempt < this.maxRetries) {
          const retryDelay = Math.pow(2, attempt) * 100;
          Logger.warn(
            `Network error (status ${response.status}), retrying in ${retryDelay}ms (attempt ${attempt + 1}/${this.maxRetries})`,
            'ollama-client'
          );
          if (attempt < this.maxRetries - 1) {
            const retryTimeout = new Promise((resolve) => setTimeout(resolve, retryDelay));
            const abortListener = () => {
              Logger.info('Retry aborted by user', 'ollama-client');
            };
            const signal = controller.signal;
            if (signal) {
              signal.addEventListener('abort', abortListener);
              try {
                await Promise.race([
                  retryTimeout,
                  new Promise<void>((resolve) => {
                    signal.addEventListener('abort', () => resolve(), {
                      once: true,
                    });
                  }),
                ]);
              } finally {
                signal.removeEventListener('abort', abortListener);
              }
            } else E{
              await retryTimeout;
            }
          }
          return this.chatWithRetry(messages, tools, attempt + 1);
        }
        throw new ApiError(`Ollama API error: ${response.status}`, response.status);
      }
 
      const data = (await response.json()) as OllamaChatResponse;
      return (
        this.toOllamaMessage(data.message) ?? { role: 'assistant', content: '', tool_calls: [] }
      );
    } finally {
      // Abort the local controller
      controller.abort();
    }
  }
 
  private throwIfOllamaError(parsed: Record<string, unknown>): void {
    if (parsed.error) {
      throw new Error(`Ollama error: ${String(parsed.error)}`);
    }
  }
 
  private toOllamaMessage(value: unknown): OllamaMessage | null {
    if (!value || typeof value !== 'object') {
      return null;
    }
 
    const record = value as Partial<OllamaMessage>;
    return {
      role: record.role ?? 'assistant',
      content: typeof record.content === 'string' ? record.content : '',
      tool_calls: record.tool_calls ?? [],
    };
  }
}