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 | 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 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 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 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 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 1x 1x 1x 1x 1x | import { IOllamaClient } from './contracts/IOllamaClient';
import { Logger } from './logger';
/**
* Represents a local Ollama model.
*/
export interface OllamaModel {
name: string;
size: number;
digest: string;
modified_at: string;
}
/**
* Represents a running Ollama process.
*/
export interface OllamaProcess {
name: string;
model: string;
size: number;
digest: string;
details: {
parent_model: string;
format: string;
family: string;
families: string[];
parameter_size: string;
quantization_level: string;
};
expires_at: string;
size_vram: number;
}
/**
* Response from /api/show
*/
export interface OllamaShowResponse {
modelfile: string;
parameters: string;
template: string;
details: {
parent_model: string;
format: string;
family: string;
families: string[];
parameter_size: string;
quantization_level: string;
};
messages?: { role: string; content: string }[];
}
/**
* Error response from Ollama API
*/
interface OllamaErrorResponse {
error: string;
}
/**
* Options for model generation/chat
*/
export interface OllamaOptions {
num_gpu?: number;
num_thread?: number;
use_mmap?: boolean;
use_mlock?: boolean;
num_ctx?: number;
num_predict?: number;
temperature?: number;
top_p?: number;
top_k?: number;
repeat_penalty?: number;
seed?: number;
stop?: string[];
[key: string]: string | number | boolean | string[] | undefined;
}
/**
* Base structure for streaming responses
*/
interface BaseStreamResponse {
error?: string;
status?: string;
}
export interface OllamaChatResponse extends BaseStreamResponse {
model: string;
created_at: string;
message?: {
role: string;
content: string;
};
done: boolean;
}
export interface OllamaPullResponse extends BaseStreamResponse {
completed?: number;
total?: number;
}
export interface OllamaCreateResponse extends BaseStreamResponse {
status?: string;
}
/**
* Robust Ollama API Client.
* Uses native fetch (Node 18+) and AsyncGenerators for streaming.
*/
export class OllamaApi implements IOllamaClient {
private readonly baseUrl: string;
constructor(baseUrl: string = 'http://localhost:11434') {
this.baseUrl = baseUrl;
}
/**
* Lists all models available locally.
*/
async listModels(): Promise<OllamaModel[]> {
const response = await this._request<{ models: OllamaModel[] }>('/api/tags');
return response.models || [];
}
/**
* Lists all models currently loaded in memory.
*/
async listRunning(): Promise<OllamaProcess[]> {
const response = await this._request<{ models: OllamaProcess[] }>('/api/ps');
return response.models || [];
}
/**
* Fetches detailed information about a model.
*/
async showModel(model: string): Promise<OllamaShowResponse> {
return this._request<OllamaShowResponse>('/api/show', {
method: 'POST',
body: JSON.stringify({ model }),
});
}
/**
* Deletes a model from the local system.
*/
async deleteModel(model: string): Promise<void> {
await this._request('/api/delete', {
method: 'DELETE',
body: JSON.stringify({ name: model }),
});
}
/**
* Unloads a model from memory.
*/
async stopModel(model: string): Promise<void> {
await this._request('/api/generate', {
method: 'POST',
body: JSON.stringify({ model, prompt: '', stream: false, keep_alive: 0 }),
});
}
/**
* Loads a model into memory.
*/
async startModel(model: string): Promise<void> {
await this._request('/api/generate', {
method: 'POST',
body: JSON.stringify({ model, prompt: '', stream: false }),
});
}
/**
* Downloads a model from the Ollama library.
*/
async pullModel(
model: string,
onProgress: (status: string, completed?: number, total?: number) => void,
): Promise<void> {
for await (const part of this._requestStream<OllamaPullResponse>('/api/pull', {
method: 'POST',
body: JSON.stringify({ model }),
})) {
if (part.status) {
onProgress(part.status, part.completed, part.total);
}
}
}
/**
* Creates a new model instance from a base model.
*/
async createModel(options: {
model: string;
from?: string;
parameters?: OllamaOptions;
system?: string;
template?: string;
}): Promise<void> {
for await (const part of this._requestStream<OllamaCreateResponse>('/api/create', {
method: 'POST',
body: JSON.stringify(options),
})) {
if (part.error) {
throw new Error(part.error);
}
}
}
/**
* Initiates a chat session with a model.
*/
async chat(
model: string,
messages: { role: string; content: string }[],
onToken: (token: string) => void,
options?: OllamaOptions,
): Promise<void> {
for await (const part of this._requestStream<OllamaChatResponse>('/api/chat', {
method: 'POST',
body: JSON.stringify({ model, messages, options, stream: true }),
})) {
if (part.message?.content) {
onToken(part.message.content);
}
}
}
/**
* Unified request handler for standard JSON endpoints.
*/
private async _request<T>(path: string, options: RequestInit = {}): Promise<T> {
const url = `${this.baseUrl}${path}`;
const response = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
...options.headers,
},
});
if (!response.ok) {
let errorMsg = `HTTP ${response.status}: ${response.statusText}`;
try {
const body = (await response.json()) as OllamaErrorResponse;
if (body && typeof body === 'object' && body.error) {
errorMsg = body.error;
}
} catch {
// Ignore parse errors for error bodies
}
Logger.error(`Ollama API error at ${path}: ${errorMsg}`);
throw new Error(errorMsg);
}
// Some endpoints return 200 but no body (like delete)
if (response.status === 200 && (options.method === 'DELETE' || path === '/api/delete')) {
return {} as T;
}
return (await response.json()) as T;
}
/**
* Unified request handler for streaming newline-delimited JSON endpoints.
*/
private async *_requestStream<T extends BaseStreamResponse>(
path: string,
options: RequestInit = {},
): AsyncGenerator<T> {
const url = `${this.baseUrl}${path}`;
const response = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
...options.headers,
},
});
if (!response.ok) {
let errorMsg = `HTTP ${response.status}: ${response.statusText}`;
try {
const body = (await response.json()) as OllamaErrorResponse;
if (body && typeof body === 'object' && body.error) {
errorMsg = body.error;
}
} catch {
// Ignore
}
throw new Error(errorMsg);
}
if (!response.body) {
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
// Keep the last partial line in the buffer
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.trim()) {
continue;
}
try {
const json = JSON.parse(line) as T;
if (json.error) {
throw new Error(json.error);
}
yield json;
} catch (e: unknown) {
if (e instanceof SyntaxError) {
// Ignore partial JSON
continue;
}
throw e;
}
}
}
} finally {
reader.releaseLock();
}
}
}
|