All files / src api.ts

100% Statements 311/311
100% Branches 99/99
100% Functions 24/24
100% Lines 311/311

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 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 3631x                         1x 1x 1x   1x 1x   1x 48x 3x 3x 3x 45x 48x               1x 50x 50x 50x 50x 50x 50x 50x 53x 3x 3x 53x 53x 53x 53x 1x 53x 22x 22x 22x 22x 53x 53x 53x 53x 53x 53x 8x 8x 3x 3x 8x 1x 1x 8x 53x 4x 50x   1x 6x 3x 6x   1x 3x 1x 3x   1x 3x 3x 3x 3x 3x   1x 2x 2x 2x 2x 2x 2x 2x   1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   1x 2x 2x 2x 2x 2x 2x 2x   1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x   1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x   1x 30x 1x 1x 29x 29x 29x 29x   30x 47x 47x 18x   18x   18x   47x 54x 14x 54x 19x 19x 19x 19x 1x 1x 19x 19x 54x 18x 30x 1x   1x 1x 1x 1x 1x 1x 1x 1x   1x 11x 11x 11x 11x 11x 20x 20x 15x 20x 14x 14x 14x 20x 11x 11x 3x 3x 3x 11x 11x   1x 1x   1x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 8x 9x   1x 5x 5x 5x 5x 5x 5x 1x 1x 1x 4x 5x 5x   1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 3x   1x 8x 1x 1x 7x 7x 7x   8x 14x 14x 7x   7x 7x   14x 12x 12x 10x 10x 12x   1x 12x 7x 8x 2x 2x 1x   1x 2x 8x 1x  
import { JSON_HEADERS, SSE_EVENT } from "./types";
import type {
    AskResponse,
    DocumentResult,
    GenerationOptions,
    Message,
    ModelsResponse,
    OllamaModelDefaults,
    OllamaPullProgress,
    SSEEvent,
    StatusResponse,
} from "./types";
 
const DEFAULT_TIMEOUT_MS = 15_000;
const RETRY_COUNT = 2;
const RETRY_BACKOFF_MS = 500;
 
export class LilbeeClient {
    constructor(private baseUrl: string) {}
 
    private async assertOk(res: Response): Promise<Response> {
        if (!res.ok) {
            const text = await res.text().catch(() => "");
            throw new Error(`Server responded ${res.status}: ${text}`);
        }
        return res;
    }
 
    /**
     * Fetch with automatic retry on network errors and a default timeout.
     * Does NOT retry on HTTP error responses (4xx/5xx) — only on fetch failures
     * (e.g. connection refused, DNS failure, timeout).
     * SSE streams should pass `stream: true` to skip the timeout.
     */
    async fetchWithRetry(
        url: string,
        init?: RequestInit,
        opts?: { stream?: boolean; signal?: AbortSignal },
    ): Promise<Response> {
        const maxAttempts = RETRY_COUNT + 1;
        let lastError: unknown;
        for (let attempt = 0; attempt < maxAttempts; attempt++) {
            if (attempt > 0) {
                await new Promise((r) => setTimeout(r, RETRY_BACKOFF_MS * attempt));
            }
            try {
                const fetchInit = { ...init };
                let timer: ReturnType<typeof setTimeout> | undefined;
                if (opts?.signal) {
                    fetchInit.signal = opts.signal;
                } else if (!opts?.stream) {
                    const controller = new AbortController();
                    fetchInit.signal = controller.signal;
                    timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
                }
                try {
                    return await this.assertOk(await globalThis.fetch(url, fetchInit));
                } finally {
                    if (timer !== undefined) clearTimeout(timer);
                }
            } catch (err) {
                lastError = err;
                if (err instanceof Error && err.message.startsWith("Server responded")) {
                    throw err;
                }
                if (err instanceof Error && err.name === "AbortError") {
                    throw err;
                }
            }
        }
        throw lastError;
    }
 
    async health(): Promise<{ status: string; version: string }> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/health`);
        return res.json();
    }
 
    async status(): Promise<StatusResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/status`);
        return res.json();
    }
 
    async search(query: string, topK?: number): Promise<DocumentResult[]> {
        const params = new URLSearchParams({ q: query });
        if (topK !== undefined) params.set("top_k", String(topK));
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/search?${params}`);
        return res.json();
    }
 
    async ask(question: string, topK?: number): Promise<AskResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/ask`, {
            method: "POST",
            headers: JSON_HEADERS,
            body: JSON.stringify({ question, top_k: topK ?? 0 }),
        });
        return res.json();
    }
 
    async *askStream(
        question: string,
        topK?: number,
        signal?: AbortSignal,
        options?: GenerationOptions,
    ): AsyncGenerator<SSEEvent> {
        const body: Record<string, unknown> = { question, top_k: topK ?? 0 };
        if (options && Object.keys(options).length > 0) body.options = options;
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/ask/stream`,
            {
                method: "POST",
                headers: JSON_HEADERS,
                body: JSON.stringify(body),
            },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    async chat(question: string, history: Message[], topK?: number): Promise<AskResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/chat`, {
            method: "POST",
            headers: JSON_HEADERS,
            body: JSON.stringify({ question, history, top_k: topK ?? 0 }),
        });
        return res.json();
    }
 
    async *chatStream(
        question: string,
        history: Message[],
        topK?: number,
        signal?: AbortSignal,
        options?: GenerationOptions,
    ): AsyncGenerator<SSEEvent> {
        const body: Record<string, unknown> = { question, history, top_k: topK ?? 0 };
        if (options && Object.keys(options).length > 0) body.options = options;
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/chat/stream`,
            {
                method: "POST",
                headers: JSON_HEADERS,
                body: JSON.stringify(body),
            },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    async *addFiles(
        paths: string[],
        force = false,
        visionModel?: string,
        signal?: AbortSignal,
    ): AsyncGenerator<SSEEvent> {
        const body: Record<string, unknown> = { paths, force };
        if (visionModel) body.vision_model = visionModel;
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/add`,
            {
                method: "POST",
                headers: JSON_HEADERS,
                body: JSON.stringify(body),
            },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    async *syncStream(forceVision = false, signal?: AbortSignal): AsyncGenerator<SSEEvent> {
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/sync`,
            {
                method: "POST",
                headers: JSON_HEADERS,
                body: JSON.stringify({ force_vision: forceVision }),
            },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    async listModels(): Promise<ModelsResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/models`);
        return res.json();
    }
 
    async *pullModel(model: string): AsyncGenerator<SSEEvent> {
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/models/pull`,
            {
                method: "POST",
                headers: JSON_HEADERS,
                body: JSON.stringify({ model }),
            },
            { stream: true },
        );
        yield* this.parseSSE(res);
    }
 
    async setChatModel(model: string): Promise<{ model: string }> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/models/chat`, {
            method: "PUT",
            headers: JSON_HEADERS,
            body: JSON.stringify({ model }),
        });
        return res.json();
    }
 
    async setVisionModel(model: string): Promise<{ model: string }> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/models/vision`, {
            method: "PUT",
            headers: JSON_HEADERS,
            body: JSON.stringify({ model }),
        });
        return res.json();
    }
 
    private async *parseSSE(response: Response): AsyncGenerator<SSEEvent> {
        if (!response.body) {
            throw new Error("Response body is null");
        }
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = "";
        let currentEvent: string = SSE_EVENT.MESSAGE;
 
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            buffer += decoder.decode(value, { stream: true });
 
            const lines = buffer.split("\n");
            // split() always returns at least one element, so pop() is never undefined
            buffer = lines.pop()!;
 
            for (const line of lines) {
                if (line.startsWith("event:")) {
                    currentEvent = (line.startsWith("event: ") ? line.slice(7) : line.slice(6)).trim();
                } else if (line.startsWith("data:")) {
                    const raw = line.startsWith("data: ") ? line.slice(6) : line.slice(5);
                    try {
                        yield { event: currentEvent, data: JSON.parse(raw) };
                    } catch {
                        yield { event: currentEvent, data: raw };
                    }
                    currentEvent = SSE_EVENT.MESSAGE;
                }
            }
        }
    }
}
 
const PARAM_KEY_MAP: Record<string, keyof OllamaModelDefaults> = {
    temperature: "temperature",
    top_p: "top_p",
    top_k: "top_k",
    repeat_penalty: "repeat_penalty",
    num_ctx: "num_ctx",
    seed: "seed",
};
 
export function parseModelParameters(
    parameters: string,
    modelInfo: Record<string, unknown>,
): OllamaModelDefaults {
    const defaults: OllamaModelDefaults = {};
    for (const line of parameters.split("\n")) {
        const parts = line.trim().split(/\s+/);
        if (parts.length < 2) continue;
        const key = PARAM_KEY_MAP[parts[0]];
        if (key) {
            const num = Number(parts[1]);
            if (!isNaN(num)) defaults[key] = num;
        }
    }
    const ctxKey = Object.keys(modelInfo).find((k) => k.endsWith(".context_length"));
    if (ctxKey && !defaults.num_ctx) {
        const val = Number(modelInfo[ctxKey]);
        if (!isNaN(val) && val > 0) defaults.num_ctx = val;
    }
    return defaults;
}
 
export class OllamaClient {
    constructor(private baseUrl: string) {}
 
    async *pull(model: string, signal?: AbortSignal): AsyncGenerator<OllamaPullProgress> {
        const res = await globalThis.fetch(`${this.baseUrl}/api/pull`, {
            method: "POST",
            headers: JSON_HEADERS,
            body: JSON.stringify({ name: model, stream: true }),
            signal,
        });
        if (!res.ok) {
            const text = await res.text().catch(() => "");
            throw new Error(`Ollama responded ${res.status}: ${text}`);
        }
        yield* this.parseNDJSON(res);
    }
 
    async show(model: string): Promise<OllamaModelDefaults> {
        const res = await globalThis.fetch(`${this.baseUrl}/api/show`, {
            method: "POST",
            headers: JSON_HEADERS,
            body: JSON.stringify({ name: model }),
        });
        if (!res.ok) {
            const text = await res.text().catch(() => "");
            throw new Error(`Ollama responded ${res.status}: ${text}`);
        }
        const data = await res.json();
        return parseModelParameters(data.parameters ?? "", data.model_info ?? {});
    }
 
    async delete(model: string): Promise<void> {
        const res = await globalThis.fetch(`${this.baseUrl}/api/delete`, {
            method: "DELETE",
            headers: JSON_HEADERS,
            body: JSON.stringify({ name: model }),
        });
        if (!res.ok) {
            const text = await res.text().catch(() => "");
            throw new Error(`Ollama responded ${res.status}: ${text}`);
        }
    }
 
    private async *parseNDJSON(response: Response): AsyncGenerator<OllamaPullProgress> {
        if (!response.body) {
            throw new Error("Response body is null");
        }
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = "";
 
        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) {
                const trimmed = line.trim();
                if (!trimmed) continue;
                try {
                    yield JSON.parse(trimmed) as OllamaPullProgress;
                } catch {
                    // skip malformed lines
                }
            }
        }
        if (buffer.trim()) {
            try {
                yield JSON.parse(buffer.trim()) as OllamaPullProgress;
            } catch {
                // skip
            }
        }
    }
}