Elffuss BraidHub

kikocis/continue public

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