Elffuss BraidHub

kikocis/continue public

f433400a74a4 · 20.0 KiBRawPermalink
1import { Mutex } from "async-mutex";
2import { JSONSchema7, JSONSchema7Object } from "json-schema";
3import { v4 as uuidv4 } from "uuid";
4
5import { streamResponse } from "@continuedev/fetch";
6import {
7 ChatMessage,
8 ChatMessageRole,
9 CompletionOptions,
10 LLMOptions,
11 ModelInstaller,
12} from "../../index.js";
13import { renderChatMessage } from "../../util/messageContent.js";
14import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
15import { BaseLLM } from "../index.js";
16
17type OllamaChatMessage = {
18 role: ChatMessageRole;
19 content: string;
20 images?: string[] | null;
21 tool_calls?: {
22 function: {
23 name: string;
24 arguments: JSONSchema7Object;
25 };
26 }[];
27};
28
29// See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter
30interface OllamaModelFileParams {
31 mirostat?: number;
32 mirostat_eta?: number;
33 mirostat_tau?: number;
34 num_ctx?: number;
35 repeat_last_n?: number;
36 repeat_penalty?: number;
37 temperature?: number;
38 seed?: number;
39 stop?: string | string[];
40 tfs_z?: number;
41 num_predict?: number;
42 top_k?: number;
43 top_p?: number;
44 min_p?: number;
45 num_gpu?: number;
46
47 // Deprecated or not directly supported here:
48 num_thread?: number;
49 use_mmap?: boolean;
50 num_gqa?: number;
51 num_keep?: number;
52 typical_p?: number;
53 presence_penalty?: number;
54 frequency_penalty?: number;
55 penalize_newline?: boolean;
56 numa?: boolean;
57 num_batch?: number;
58 main_gpu?: number;
59 low_vram?: boolean;
60 vocab_only?: boolean;
61 use_mlock?: boolean;
62}
63
64// See https://github.com/ollama/ollama/blob/main/docs/api.md
65interface OllamaBaseOptions {
66 model: string; // the model name
67 options?: OllamaModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature
68 format?: "json"; // the format to return a response in. Currently, the only accepted value is json
69 stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects
70 keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m)
71}
72
73interface OllamaRawOptions extends OllamaBaseOptions {
74 prompt: string; // the prompt to generate a response for
75 suffix?: string; // the text after the model response
76 images?: string[]; // a list of base64-encoded images (for multimodal models such as llava)
77 system?: string; // system message to (overrides what is defined in the Modelfile)
78 template?: string; // the prompt template to use (overrides what is defined in the Modelfile)
79 context?: string; // the context parameter returned from a previous request to /generate, this can be used to keep a short conversational memory
80 raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API
81}
82
83interface OllamaChatOptions extends OllamaBaseOptions {
84 messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory
85 tools?: OllamaTool[]; // the tools of the chat, this can be used to keep a tool memory
86 // Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false
87 // And correspondingly, tool calls in OllamaChatMessage
88}
89
90type OllamaBaseResponse = {
91 model: string;
92 created_at: string;
93} & (
94 | {
95 done: false;
96 }
97 | {
98 done: true;
99 done_reason: string;
100 total_duration: number; // Time spent generating the response in nanoseconds
101 load_duration: number; // Time spent loading the model in nanoseconds
102 prompt_eval_count: number; // Number of tokens in the prompt
103 prompt_eval_duration: number; // Time spent evaluating the prompt in nanoseconds
104 eval_count: number; // Number of tokens in the response
105 eval_duration: number; // Time spent generating the response in nanoseconds
106 context: number[]; // An encoding of the conversation used in this response; can be sent in the next request to keep conversational memory
107 }
108);
109
110type OllamaErrorResponse = {
111 error: string;
112};
113
114type OllamaRawResponse =
115 | OllamaErrorResponse
116 | (OllamaBaseResponse & {
117 response: string; // the generated response
118 });
119
120type OllamaChatResponse =
121 | OllamaErrorResponse
122 | (OllamaBaseResponse & {
123 message: OllamaChatMessage;
124 });
125
126interface OllamaTool {
127 type: "function";
128 function: {
129 name: string;
130 description?: string;
131 parameters?: JSONSchema7;
132 };
133}
134
135class Ollama extends BaseLLM implements ModelInstaller {
136 static providerName = "ollama";
137 static defaultOptions: Partial<LLMOptions> = {
138 apiBase: "http://localhost:11434/",
139 model: "codellama-7b",
140 maxEmbeddingBatchSize: 64,
141 };
142
143 private static modelsBeingInstalled: Set<string> = new Set();
144 private static modelsBeingInstalledMutex = new Mutex();
145
146 private fimSupported: boolean = false;
147
148 constructor(options: LLMOptions) {
149 super(options);
150
151 if (options.model === "AUTODETECT") {
152 return;
153 }
154 const headers: Record<string, string> = {
155 "Content-Type": "application/json",
156 };
157
158 if (this.apiKey) {
159 headers.Authorization = `Bearer ${this.apiKey}`;
160 }
161
162 this.fetch(this.getEndpoint("api/show"), {
163 method: "POST",
164 headers: headers,
165 body: JSON.stringify({ name: this._getModel() }),
166 })
167 .then(async (response) => {
168 if (response?.status !== 200) {
169 // console.warn(
170 // "Error calling Ollama /api/show endpoint: ",
171 // await response.text(),
172 // );
173 return;
174 }
175 const body = await response.json();
176 if (body.parameters) {
177 const params = [];
178 for (const line of body.parameters.split("\n")) {
179 let parts = line.match(/^(\S+)\s+((?:".*")|\S+)$/);
180 if (parts.length < 2) {
181 continue;
182 }
183 let key = parts[1];
184 let value = parts[2];
185 switch (key) {
186 case "num_ctx":
187 this._contextLength =
188 options.contextLength ?? Number.parseInt(value);
189 break;
190 case "stop":
191 if (!this.completionOptions.stop) {
192 this.completionOptions.stop = [];
193 }
194 try {
195 this.completionOptions.stop.push(JSON.parse(value));
196 } catch (e) {
197 console.warn(
198 `Error parsing stop parameter value "{value}: ${e}`,
199 );
200 }
201 break;
202 default:
203 break;
204 }
205 }
206 }
207
208 /**
209 * There is no API to get the model's FIM capabilities, so we have to
210 * make an educated guess. If a ".Suffix" variable appears in the template
211 * it's a good indication the model supports FIM.
212 */
213 this.fimSupported = !!body?.template?.includes(".Suffix");
214 })
215 .catch((e) => {
216 // console.warn("Error calling the Ollama /api/show endpoint: ", e);
217 });
218 }
219
220 // Map of "continue model name" to Ollama actual model name
221 private modelMap: Record<string, string> = {
222 "mistral-7b": "mistral:7b",
223 "mixtral-8x7b": "mixtral:8x7b",
224 "llama2-7b": "llama2:7b",
225 "llama2-13b": "llama2:13b",
226 "codellama-7b": "codellama:7b",
227 "codellama-13b": "codellama:13b",
228 "codellama-34b": "codellama:34b",
229 "codellama-70b": "codellama:70b",
230 "llama3-8b": "llama3:8b",
231 "llama3-70b": "llama3:70b",
232 "llama3.1-8b": "llama3.1:8b",
233 "llama3.1-70b": "llama3.1:70b",
234 "llama3.1-405b": "llama3.1:405b",
235 "llama3.2-1b": "llama3.2:1b",
236 "llama3.2-3b": "llama3.2:3b",
237 "llama3.2-11b": "llama3.2:11b",
238 "llama3.2-90b": "llama3.2:90b",
239 "phi-2": "phi:2.7b",
240 "phind-codellama-34b": "phind-codellama:34b-v2",
241 "qwen2.5-coder-0.5b": "qwen2.5-coder:0.5b",
242 "qwen2.5-coder-1.5b": "qwen2.5-coder:1.5b",
243 "qwen2.5-coder-3b": "qwen2.5-coder:3b",
244 "qwen2.5-coder-7b": "qwen2.5-coder:7b",
245 "qwen2.5-coder-14b": "qwen2.5-coder:14b",
246 "qwen2.5-coder-32b": "qwen2.5-coder:32b",
247 "wizardcoder-7b": "wizardcoder:7b-python",
248 "wizardcoder-13b": "wizardcoder:13b-python",
249 "wizardcoder-34b": "wizardcoder:34b-python",
250 "zephyr-7b": "zephyr:7b",
251 "codeup-13b": "codeup:13b",
252 "deepseek-1b": "deepseek-coder:1.3b",
253 "deepseek-7b": "deepseek-coder:6.7b",
254 "deepseek-33b": "deepseek-coder:33b",
255 "neural-chat-7b": "neural-chat:7b-v3.3",
256 "starcoder-1b": "starcoder:1b",
257 "starcoder-3b": "starcoder:3b",
258 "starcoder2-3b": "starcoder2:3b",
259 "stable-code-3b": "stable-code:3b",
260 "granite-code-3b": "granite-code:3b",
261 "granite-code-8b": "granite-code:8b",
262 "granite-code-20b": "granite-code:20b",
263 "granite-code-34b": "granite-code:34b",
264 };
265
266 private _getModel() {
267 return this.modelMap[this.model] ?? this.model;
268 }
269
270 private _getModelFileParams(
271 options: CompletionOptions,
272 ): OllamaModelFileParams {
273 return {
274 temperature: options.temperature,
275 top_p: options.topP,
276 top_k: options.topK,
277 num_predict: options.maxTokens,
278 stop: options.stop,
279 num_ctx: this.contextLength,
280 mirostat: options.mirostat,
281 num_thread: options.numThreads,
282 use_mmap: options.useMmap,
283 min_p: options.minP,
284 num_gpu: options.numGpu,
285 };
286 }
287
288 private _convertToOllamaMessage(message: ChatMessage): OllamaChatMessage {
289 const ollamaMessage: OllamaChatMessage = {
290 role: message.role,
291 content: "",
292 };
293
294 ollamaMessage.content = renderChatMessage(message);
295 if (Array.isArray(message.content)) {
296 const images: string[] = [];
297 message.content.forEach((part) => {
298 if (part.type === "imageUrl" && part.imageUrl) {
299 const image = part.imageUrl?.url.split(",").at(-1);
300 if (image) {
301 images.push(image);
302 }
303 }
304 });
305 if (images.length > 0) {
306 ollamaMessage.images = images;
307 }
308 }
309
310 return ollamaMessage;
311 }
312
313 private _getGenerateOptions(
314 options: CompletionOptions,
315 prompt: string,
316 suffix?: string,
317 ): OllamaRawOptions {
318 return {
319 model: this._getModel(),
320 prompt,
321 suffix,
322 raw: options.raw,
323 options: this._getModelFileParams(options),
324 keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
325 stream: options.stream,
326 // Not supported yet: context, images, system, template, format
327 };
328 }
329
330 private getEndpoint(endpoint: string): URL {
331 let base = this.apiBase;
332 if (process.env.IS_BINARY) {
333 base = base?.replace("localhost", "127.0.0.1");
334 }
335
336 return new URL(endpoint, base);
337 }
338
339 protected async *_streamComplete(
340 prompt: string,
341 signal: AbortSignal,
342 options: CompletionOptions,
343 ): AsyncGenerator<string> {
344 const headers: Record<string, string> = {
345 "Content-Type": "application/json",
346 };
347
348 if (this.apiKey) {
349 headers.Authorization = `Bearer ${this.apiKey}`;
350 }
351 const response = await this.fetch(this.getEndpoint("api/generate"), {
352 method: "POST",
353 headers: headers,
354 body: JSON.stringify(this._getGenerateOptions(options, prompt)),
355 signal,
356 });
357
358 let buffer = "";
359 for await (const value of streamResponse(response)) {
360 // Append the received chunk to the buffer
361 buffer += value;
362 // Split the buffer into individual JSON chunks
363 const chunks = buffer.split("\n");
364 buffer = chunks.pop() ?? "";
365
366 for (let i = 0; i < chunks.length; i++) {
367 const chunk = chunks[i];
368 if (chunk.trim() !== "") {
369 try {
370 const j = JSON.parse(chunk) as OllamaRawResponse;
371 if ("error" in j) {
372 throw new Error(j.error);
373 }
374 j.response ??= "";
375 yield j.response;
376 } catch (e) {
377 throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
378 }
379 }
380 }
381 }
382 }
383
384 protected async *_streamChat(
385 messages: ChatMessage[],
386 signal: AbortSignal,
387 options: CompletionOptions,
388 ): AsyncGenerator<ChatMessage> {
389 const ollamaMessages = messages.map(this._convertToOllamaMessage);
390 const chatOptions: OllamaChatOptions = {
391 model: this._getModel(),
392 messages: ollamaMessages,
393 options: this._getModelFileParams(options),
394 keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
395 stream: options.stream,
396 // format: options.format, // Not currently in base completion options
397 };
398 // This logic is because tools can ONLY be included with user message for ollama
399 if (options.tools?.length && ollamaMessages.at(-1)?.role === "user") {
400 chatOptions.tools = options.tools.map((tool) => ({
401 type: "function",
402 function: {
403 name: tool.function.name,
404 description: tool.function.description,
405 parameters: tool.function.parameters,
406 },
407 }));
408 }
409 const headers: Record<string, string> = {
410 "Content-Type": "application/json",
411 };
412
413 if (this.apiKey) {
414 headers.Authorization = `Bearer ${this.apiKey}`;
415 }
416 const response = await this.fetch(this.getEndpoint("api/chat"), {
417 method: "POST",
418 headers: headers,
419 body: JSON.stringify(chatOptions),
420 signal,
421 });
422
423 function convertChatMessage(res: OllamaChatResponse): ChatMessage {
424 if ("error" in res) {
425 throw new Error(res.error);
426 }
427 if (res.message.role === "tool") {
428 throw new Error(
429 "Unexpected message received from ollama with role = tool",
430 );
431 }
432 if (res.message.role === "assistant") {
433 const chatMessage: ChatMessage = {
434 role: "assistant",
435 content: res.message.content,
436 };
437 if (res.message.tool_calls) {
438 // Continue handles the response as a tool call delta but
439 // But ollama returns the full object in one response with no streaming
440 chatMessage.toolCalls = res.message.tool_calls.map((tc) => ({
441 type: "function",
442 id: `tc_${uuidv4()}`, // Generate a proper UUID with a prefix
443 function: {
444 name: tc.function.name,
445 arguments: JSON.stringify(tc.function.arguments),
446 },
447 }));
448 }
449 return chatMessage;
450 } else {
451 return {
452 role: res.message.role,
453 content: res.message.content,
454 };
455 }
456 }
457
458 if (chatOptions.stream === false) {
459 if (response.status === 499) {
460 return; // Aborted by user
461 }
462 const json = (await response.json()) as OllamaChatResponse;
463 yield convertChatMessage(json);
464 } else {
465 let buffer = "";
466 for await (const value of streamResponse(response)) {
467 // Append the received chunk to the buffer
468 buffer += value;
469 // Split the buffer into individual JSON chunks
470 const chunks = buffer.split("\n");
471 buffer = chunks.pop() ?? "";
472
473 for (let i = 0; i < chunks.length; i++) {
474 const chunk = chunks[i];
475 if (chunk.trim() !== "") {
476 try {
477 const j = JSON.parse(chunk) as OllamaChatResponse;
478 const chatMessage = convertChatMessage(j);
479 yield chatMessage;
480 } catch (e) {
481 throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
482 }
483 }
484 }
485 }
486 }
487 }
488
489 supportsFim(): boolean {
490 return this.fimSupported;
491 }
492
493 protected async *_streamFim(
494 prefix: string,
495 suffix: string,
496 signal: AbortSignal,
497 options: CompletionOptions,
498 ): AsyncGenerator<string> {
499 const headers: Record<string, string> = {
500 "Content-Type": "application/json",
501 };
502
503 if (this.apiKey) {
504 headers.Authorization = `Bearer ${this.apiKey}`;
505 }
506 const response = await this.fetch(this.getEndpoint("api/generate"), {
507 method: "POST",
508 headers: headers,
509 body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)),
510 signal,
511 });
512
513 let buffer = "";
514 for await (const value of streamResponse(response)) {
515 // Append the received chunk to the buffer
516 buffer += value;
517 // Split the buffer into individual JSON chunks
518 const chunks = buffer.split("\n");
519 buffer = chunks.pop() ?? "";
520
521 for (let i = 0; i < chunks.length; i++) {
522 const chunk = chunks[i];
523 if (chunk.trim() !== "") {
524 try {
525 const j = JSON.parse(chunk);
526 if ("response" in j) {
527 yield j.response;
528 } else if ("error" in j) {
529 throw new Error(j.error);
530 }
531 } catch (e) {
532 throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
533 }
534 }
535 }
536 }
537 }
538
539 async listModels(): Promise<string[]> {
540 const headers: Record<string, string> = {
541 "Content-Type": "application/json",
542 };
543
544 if (this.apiKey) {
545 headers.Authorization = `Bearer ${this.apiKey}`;
546 }
547 const response = await this.fetch(
548 // localhost was causing fetch failed in pkg binary only for this Ollama endpoint
549 this.getEndpoint("api/tags"),
550 {
551 method: "GET",
552 headers: headers,
553 },
554 );
555 const data = await response.json();
556 if (response.ok) {
557 return data.models.map((model: any) => model.name);
558 } else {
559 throw new Error(
560 "Failed to list Ollama models. Make sure Ollama is running.",
561 );
562 }
563 }
564
565 protected async _embed(chunks: string[]): Promise<number[][]> {
566 const headers: Record<string, string> = {
567 "Content-Type": "application/json",
568 };
569
570 if (this.apiKey) {
571 headers.Authorization = `Bearer ${this.apiKey}`;
572 }
573 const resp = await this.fetch(new URL("api/embed", this.apiBase), {
574 method: "POST",
575 body: JSON.stringify({
576 model: this.model,
577 input: chunks,
578 }),
579 headers: headers,
580 });
581
582 if (!resp.ok) {
583 throw new Error(`Failed to embed chunk: ${await resp.text()}`);
584 }
585
586 const data = await resp.json();
587 const embedding: number[][] = data.embeddings;
588
589 if (!embedding || embedding.length === 0) {
590 throw new Error("Ollama generated empty embedding");
591 }
592 return embedding;
593 }
594
595 public async installModel(
596 modelName: string,
597 signal: AbortSignal,
598 progressReporter?: (task: string, increment: number, total: number) => void,
599 ): Promise<any> {
600 const modelInfo = await getRemoteModelInfo(modelName, signal);
601 if (!modelInfo) {
602 throw new Error(`'${modelName}' not found in the Ollama registry!`);
603 }
604
605 const release = await Ollama.modelsBeingInstalledMutex.acquire();
606 try {
607 if (Ollama.modelsBeingInstalled.has(modelName)) {
608 throw new Error(`Model '${modelName}' is already being installed.`);
609 }
610 Ollama.modelsBeingInstalled.add(modelName);
611 } finally {
612 release();
613 }
614
615 try {
616 const response = await fetch(this.getEndpoint("api/pull"), {
617 method: "POST",
618 headers: {
619 "Content-Type": "application/json",
620 Authorization: `Bearer ${this.apiKey}`,
621 },
622 body: JSON.stringify({ name: modelName }),
623 signal,
624 });
625
626 const reader = response.body?.getReader();
627 //TODO: generate proper progress based on modelInfo size
628 while (true) {
629 const { done, value } = (await reader?.read()) || {
630 done: true,
631 value: undefined,
632 };
633 if (done) {
634 break;
635 }
636
637 const chunk = new TextDecoder().decode(value);
638 const lines = chunk.split("\n").filter(Boolean);
639 for (const line of lines) {
640 const data = JSON.parse(line);
641 progressReporter?.(data.status, data.completed, data.total);
642 }
643 }
644 } finally {
645 const release = await Ollama.modelsBeingInstalledMutex.acquire();
646 try {
647 Ollama.modelsBeingInstalled.delete(modelName);
648 } finally {
649 release();
650 }
651 }
652 }
653
654 public async isInstallingModel(modelName: string): Promise<boolean> {
655 const release = await Ollama.modelsBeingInstalledMutex.acquire();
656 try {
657 return Ollama.modelsBeingInstalled.has(modelName);
658 } finally {
659 release();
660 }
661 }
662}
663
664export default Ollama;