Elffuss BraidHub

kikocis/continue public

main · 20.9 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 get contextLength() {
273 const DEFAULT_OLLAMA_CONTEXT_LENGTH = 8192; // twice of https://github.com/ollama/ollama/blob/29ddfc2cab7f5a83a96c3133094f67b22e4f27d1/envconfig/config.go#L185
274 return this._contextLength ?? DEFAULT_OLLAMA_CONTEXT_LENGTH;
275 }
276
277 private _getModelFileParams(
278 options: CompletionOptions,
279 ): OllamaModelFileParams {
280 return {
281 temperature: options.temperature,
282 top_p: options.topP,
283 top_k: options.topK,
284 num_predict: options.maxTokens,
285 stop: options.stop,
286 num_ctx: this.contextLength,
287 mirostat: options.mirostat,
288 num_thread: options.numThreads,
289 use_mmap: options.useMmap,
290 min_p: options.minP,
291 num_gpu: options.numGpu,
292 };
293 }
294
295 private _convertToOllamaMessage(message: ChatMessage): OllamaChatMessage {
296 const ollamaMessage: OllamaChatMessage = {
297 role: message.role,
298 content: "",
299 };
300
301 ollamaMessage.content = renderChatMessage(message);
302 if (Array.isArray(message.content)) {
303 const images: string[] = [];
304 message.content.forEach((part) => {
305 if (part.type === "imageUrl" && part.imageUrl) {
306 const image = part.imageUrl?.url.split(",").at(-1);
307 if (image) {
308 images.push(image);
309 }
310 }
311 });
312 if (images.length > 0) {
313 ollamaMessage.images = images;
314 }
315 }
316
317 return ollamaMessage;
318 }
319
320 private _getGenerateOptions(
321 options: CompletionOptions,
322 prompt: string,
323 suffix?: string,
324 ): OllamaRawOptions {
325 return {
326 model: this._getModel(),
327 prompt,
328 suffix,
329 raw: options.raw,
330 options: this._getModelFileParams(options),
331 keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
332 stream: options.stream,
333 // Not supported yet: context, images, system, template, format
334 };
335 }
336
337 private getEndpoint(endpoint: string): URL {
338 let base = this.apiBase;
339 if (process.env.IS_BINARY) {
340 base = base?.replace("localhost", "127.0.0.1");
341 }
342
343 return new URL(endpoint, base);
344 }
345
346 protected async *_streamComplete(
347 prompt: string,
348 signal: AbortSignal,
349 options: CompletionOptions,
350 ): AsyncGenerator<string> {
351 const headers: Record<string, string> = {
352 "Content-Type": "application/json",
353 };
354
355 if (this.apiKey) {
356 headers.Authorization = `Bearer ${this.apiKey}`;
357 }
358 const response = await this.fetch(this.getEndpoint("api/generate"), {
359 method: "POST",
360 headers: headers,
361 body: JSON.stringify(this._getGenerateOptions(options, prompt)),
362 signal,
363 });
364
365 let buffer = "";
366 for await (const value of streamResponse(response)) {
367 // Append the received chunk to the buffer
368 buffer += value;
369 // Split the buffer into individual JSON chunks
370 const chunks = buffer.split("\n");
371 buffer = chunks.pop() ?? "";
372
373 for (let i = 0; i < chunks.length; i++) {
374 const chunk = chunks[i];
375 if (chunk.trim() !== "") {
376 try {
377 const j = JSON.parse(chunk) as OllamaRawResponse;
378 if ("error" in j) {
379 throw new Error(j.error);
380 }
381 j.response ??= "";
382 yield j.response;
383 } catch (e) {
384 throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
385 }
386 }
387 }
388 }
389 }
390
391 protected async *_streamChat(
392 messages: ChatMessage[],
393 signal: AbortSignal,
394 options: CompletionOptions,
395 ): AsyncGenerator<ChatMessage> {
396 const ollamaMessages = messages.map(this._convertToOllamaMessage);
397 const chatOptions: OllamaChatOptions = {
398 model: this._getModel(),
399 messages: ollamaMessages,
400 options: this._getModelFileParams(options),
401 think: options.reasoning,
402 keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
403 stream: options.stream,
404 // format: options.format, // Not currently in base completion options
405 };
406 // This logic is because tools can ONLY be included with user message for ollama
407 if (options.tools?.length && ollamaMessages.at(-1)?.role === "user") {
408 chatOptions.tools = options.tools.map((tool) => ({
409 type: "function",
410 function: {
411 name: tool.function.name,
412 description: tool.function.description,
413 parameters: tool.function.parameters,
414 },
415 }));
416 }
417 const headers: Record<string, string> = {
418 "Content-Type": "application/json",
419 };
420
421 if (this.apiKey) {
422 headers.Authorization = `Bearer ${this.apiKey}`;
423 }
424 const response = await this.fetch(this.getEndpoint("api/chat"), {
425 method: "POST",
426 headers: headers,
427 body: JSON.stringify(chatOptions),
428 signal,
429 });
430
431 function convertChatMessage(res: OllamaChatResponse): ChatMessage[] {
432 if ("error" in res) {
433 throw new Error(res.error);
434 }
435
436 const { role, content, thinking, tool_calls: toolCalls } = res.message;
437
438 if (role === "tool") {
439 throw new Error(
440 "Unexpected message received from Ollama with role = tool",
441 );
442 }
443
444 if (role === "assistant") {
445 const thinkingMessage: ThinkingChatMessage | null = thinking
446 ? { role: "thinking", content: thinking }
447 : null;
448
449 if (thinkingMessage && !content) {
450 // When Streaming you can't have both thinking and content
451 return [thinkingMessage];
452 }
453 // Either not thinking, or not streaming
454 const chatMessage: ChatMessage = { role: "assistant", content };
455
456 if (toolCalls?.length) {
457 // Continue handles the response as a tool call delta but
458 // But ollama returns the full object in one response with no streaming
459 chatMessage.toolCalls = toolCalls.map((tc) => ({
460 type: "function",
461 id: `tc_${uuidv4()}`, // Generate a proper UUID with a prefix
462 function: {
463 name: tc.function.name,
464 arguments: JSON.stringify(tc.function.arguments),
465 },
466 }));
467 }
468
469 // Return both thinking and chat messages if applicable
470 return thinkingMessage ? [thinkingMessage, chatMessage] : [chatMessage];
471 }
472
473 // Fallback for all other roles
474 return [{ role, content }];
475 }
476
477 if (chatOptions.stream === false) {
478 if (response.status === 499) {
479 return; // Aborted by user
480 }
481 const json = (await response.json()) as OllamaChatResponse;
482 for (const msg of convertChatMessage(json)) {
483 yield msg;
484 }
485 } else {
486 let buffer = "";
487 for await (const value of streamResponse(response)) {
488 // Append the received chunk to the buffer
489 buffer += value;
490 // Split the buffer into individual JSON chunks
491 const chunks = buffer.split("\n");
492 buffer = chunks.pop() ?? "";
493
494 for (let i = 0; i < chunks.length; i++) {
495 const chunk = chunks[i];
496 if (chunk.trim() !== "") {
497 try {
498 const j = JSON.parse(chunk) as OllamaChatResponse;
499 for (const msg of convertChatMessage(j)) {
500 yield msg;
501 }
502 } catch (e) {
503 throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
504 }
505 }
506 }
507 }
508 }
509 }
510
511 supportsFim(): boolean {
512 return this.fimSupported;
513 }
514
515 protected async *_streamFim(
516 prefix: string,
517 suffix: string,
518 signal: AbortSignal,
519 options: CompletionOptions,
520 ): AsyncGenerator<string> {
521 const headers: Record<string, string> = {
522 "Content-Type": "application/json",
523 };
524
525 if (this.apiKey) {
526 headers.Authorization = `Bearer ${this.apiKey}`;
527 }
528 const response = await this.fetch(this.getEndpoint("api/generate"), {
529 method: "POST",
530 headers: headers,
531 body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)),
532 signal,
533 });
534
535 let buffer = "";
536 for await (const value of streamResponse(response)) {
537 // Append the received chunk to the buffer
538 buffer += value;
539 // Split the buffer into individual JSON chunks
540 const chunks = buffer.split("\n");
541 buffer = chunks.pop() ?? "";
542
543 for (let i = 0; i < chunks.length; i++) {
544 const chunk = chunks[i];
545 if (chunk.trim() !== "") {
546 try {
547 const j = JSON.parse(chunk);
548 if ("response" in j) {
549 yield j.response;
550 } else if ("error" in j) {
551 throw new Error(j.error);
552 }
553 } catch (e) {
554 throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
555 }
556 }
557 }
558 }
559 }
560
561 async listModels(): Promise<string[]> {
562 const headers: Record<string, string> = {
563 "Content-Type": "application/json",
564 };
565
566 if (this.apiKey) {
567 headers.Authorization = `Bearer ${this.apiKey}`;
568 }
569 const response = await this.fetch(
570 // localhost was causing fetch failed in pkg binary only for this Ollama endpoint
571 this.getEndpoint("api/tags"),
572 {
573 method: "GET",
574 headers: headers,
575 },
576 );
577 const data = await response.json();
578 if (response.ok) {
579 return data.models.map((model: any) => model.name);
580 } else {
581 throw new Error(
582 "Failed to list Ollama models. Make sure Ollama is running.",
583 );
584 }
585 }
586
587 protected async _embed(chunks: string[]): Promise<number[][]> {
588 const headers: Record<string, string> = {
589 "Content-Type": "application/json",
590 };
591
592 if (this.apiKey) {
593 headers.Authorization = `Bearer ${this.apiKey}`;
594 }
595 const resp = await this.fetch(new URL("api/embed", this.apiBase), {
596 method: "POST",
597 body: JSON.stringify({
598 model: this.model,
599 input: chunks,
600 }),
601 headers: headers,
602 });
603
604 if (!resp.ok) {
605 throw new Error(`Failed to embed chunk: ${await resp.text()}`);
606 }
607
608 const data = await resp.json();
609 const embedding: number[][] = data.embeddings;
610
611 if (!embedding || embedding.length === 0) {
612 throw new Error("Ollama generated empty embedding");
613 }
614 return embedding;
615 }
616
617 public async installModel(
618 modelName: string,
619 signal: AbortSignal,
620 progressReporter?: (task: string, increment: number, total: number) => void,
621 ): Promise<any> {
622 const modelInfo = await getRemoteModelInfo(modelName, signal);
623 if (!modelInfo) {
624 throw new Error(`'${modelName}' not found in the Ollama registry!`);
625 }
626
627 const release = await Ollama.modelsBeingInstalledMutex.acquire();
628 try {
629 if (Ollama.modelsBeingInstalled.has(modelName)) {
630 throw new Error(`Model '${modelName}' is already being installed.`);
631 }
632 Ollama.modelsBeingInstalled.add(modelName);
633 } finally {
634 release();
635 }
636
637 try {
638 const response = await fetch(this.getEndpoint("api/pull"), {
639 method: "POST",
640 headers: {
641 "Content-Type": "application/json",
642 Authorization: `Bearer ${this.apiKey}`,
643 },
644 body: JSON.stringify({ name: modelName }),
645 signal,
646 });
647
648 const reader = response.body?.getReader();
649 //TODO: generate proper progress based on modelInfo size
650 while (true) {
651 const { done, value } = (await reader?.read()) || {
652 done: true,
653 value: undefined,
654 };
655 if (done) {
656 break;
657 }
658
659 const chunk = new TextDecoder().decode(value);
660 const lines = chunk.split("\n").filter(Boolean);
661 for (const line of lines) {
662 const data = JSON.parse(line);
663 progressReporter?.(data.status, data.completed, data.total);
664 }
665 }
666 } finally {
667 const release = await Ollama.modelsBeingInstalledMutex.acquire();
668 try {
669 Ollama.modelsBeingInstalled.delete(modelName);
670 } finally {
671 release();
672 }
673 }
674 }
675
676 public async isInstallingModel(modelName: string): Promise<boolean> {
677 const release = await Ollama.modelsBeingInstalledMutex.acquire();
678 try {
679 return Ollama.modelsBeingInstalled.has(modelName);
680 } finally {
681 release();
682 }
683 }
684}
685
686export default Ollama;