From ccba2ed8f8ad3ca412eb1bedd5558ce9e6e953bd Mon Sep 17 00:00:00 2001 From: loupzeur <20752997+loupzeur@users.noreply.github.com> Date: Wed, 5 Mar 2025 00:46:26 +0200 Subject: [PATCH] feat(ollama): use official ollama library (#1859) Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com> --- package-lock.json | 16 +++ package.json | 1 + src/api/providers/ollama.ts | 29 ++--- src/api/transform/ollama-format.ts | 109 ++++++++++++++++++ src/core/webview/ClineProvider.ts | 6 + src/shared/api.ts | 1 + .../src/components/settings/ApiOptions.tsx | 7 ++ 7 files changed, 152 insertions(+), 17 deletions(-) create mode 100644 src/api/transform/ollama-format.ts diff --git a/package-lock.json b/package-lock.json index 1a4b84f4..5e28dd04 100644 --- a/package-lock.json +++ b/package-lock.json @@ -37,6 +37,7 @@ "isbinaryfile": "^5.0.2", "mammoth": "^1.8.0", "monaco-vscode-textmate-theme-converter": "^0.1.7", + "ollama": "^0.5.13", "open-graph-scraper": "^6.9.0", "openai": "^4.83.0", "os-name": "^6.0.0", @@ -11064,6 +11065,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/ollama": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/ollama/-/ollama-0.5.13.tgz", + "integrity": "sha512-qK3eE2GjMYjCiTknEJfAHjbUzUqgVtf9qtzjxWrkwBZgBG7kOB6Z4+Ov4fbvDjmKKHv+rpuTsWFg4jZvVjNBtQ==", + "license": "MIT", + "dependencies": { + "whatwg-fetch": "^3.6.20" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -13414,6 +13424,12 @@ "node": ">=18" } }, + "node_modules/whatwg-fetch": { + "version": "3.6.20", + "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-3.6.20.tgz", + "integrity": "sha512-EqhiFU6daOA8kpjOWTL0olhVOF3i7OrFzSYiGsEMB8GcXS+RrzauAERX65xMeNWVqxA6HXH2m69Z9LaKKdisfg==", + "license": "MIT" + }, "node_modules/whatwg-mimetype": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", diff --git a/package.json b/package.json index 443efd96..68786966 100644 --- a/package.json +++ b/package.json @@ -290,6 +290,7 @@ "isbinaryfile": "^5.0.2", "mammoth": "^1.8.0", "monaco-vscode-textmate-theme-converter": "^0.1.7", + "ollama": "^0.5.13", "open-graph-scraper": "^6.9.0", "openai": "^4.83.0", "os-name": "^6.0.0", diff --git a/src/api/providers/ollama.ts b/src/api/providers/ollama.ts index 7668bd39..9b69ce49 100644 --- a/src/api/providers/ollama.ts +++ b/src/api/providers/ollama.ts @@ -1,40 +1,35 @@ import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI from "openai" +import { Message, Ollama } from "ollama" import { ApiHandler } from "../" import { ApiHandlerOptions, ModelInfo, openAiModelInfoSaneDefaults } from "../../shared/api" -import { convertToOpenAiMessages } from "../transform/openai-format" +import { convertToOllamaMessages } from "../transform/ollama-format" import { ApiStream } from "../transform/stream" export class OllamaHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: Ollama constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: (this.options.ollamaBaseUrl || "http://localhost:11434") + "/v1", - apiKey: "ollama", - }) + this.client = new Ollama({ host: this.options.ollamaBaseUrl || "http://localhost:11434" }) } async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { - const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ - { role: "system", content: systemPrompt }, - ...convertToOpenAiMessages(messages), - ] + const ollamaMessages: Message[] = [{ role: "system", content: systemPrompt }, ...convertToOllamaMessages(messages)] - const stream = await this.client.chat.completions.create({ + const stream = await this.client.chat({ model: this.getModel().id, - messages: openAiMessages, - temperature: 0, + messages: ollamaMessages, stream: true, + options: { + num_ctx: Number(this.options.ollamaApiOptionsCtxNum) || 32768, + }, }) for await (const chunk of stream) { - const delta = chunk.choices[0]?.delta - if (delta?.content) { + if (typeof chunk.message.content === "string") { yield { type: "text", - text: delta.content, + text: chunk.message.content, } } } diff --git a/src/api/transform/ollama-format.ts b/src/api/transform/ollama-format.ts new file mode 100644 index 00000000..4f6bde4f --- /dev/null +++ b/src/api/transform/ollama-format.ts @@ -0,0 +1,109 @@ +import { Anthropic } from "@anthropic-ai/sdk" +import { Message } from "ollama" + +export function convertToOllamaMessages(anthropicMessages: Anthropic.Messages.MessageParam[]): Message[] { + const ollamaMessages: Message[] = [] + + for (const anthropicMessage of anthropicMessages) { + if (typeof anthropicMessage.content === "string") { + ollamaMessages.push({ + role: anthropicMessage.role, + content: anthropicMessage.content, + }) + } else { + if (anthropicMessage.role === "user") { + const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{ + nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] + toolMessages: Anthropic.ToolResultBlockParam[] + }>( + (acc, part) => { + if (part.type === "tool_result") { + acc.toolMessages.push(part) + } else if (part.type === "text" || part.type === "image") { + acc.nonToolMessages.push(part) + } + return acc + }, + { nonToolMessages: [], toolMessages: [] }, + ) + + // Process tool result messages FIRST since they must follow the tool use messages + let toolResultImages: string[] = [] + toolMessages.forEach((toolMessage) => { + // The Anthropic SDK allows tool results to be a string or an array of text and image blocks, enabling rich and structured content. In contrast, the Ollama SDK only supports tool results as a single string, so we map the Anthropic tool result parts into one concatenated string to maintain compatibility. + let content: string + + if (typeof toolMessage.content === "string") { + content = toolMessage.content + } else { + content = + toolMessage.content + ?.map((part) => { + if (part.type === "image") { + toolResultImages.push(`data:${part.source.media_type};base64,${part.source.data}`) + return "(see following user message for image)" + } + return part.text + }) + .join("\n") ?? "" + } + ollamaMessages.push({ + role: "user", + images: toolResultImages.length > 0 ? toolResultImages : undefined, + content: content, + }) + }) + + // Process non-tool messages + if (nonToolMessages.length > 0) { + ollamaMessages.push({ + role: "user", + content: nonToolMessages + .map((part) => { + if (part.type === "image") { + return `data:${part.source.media_type};base64,${part.source.data}` + } + return part.text + }) + .join("\n"), + }) + } + } else if (anthropicMessage.role === "assistant") { + const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{ + nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] + toolMessages: Anthropic.ToolUseBlockParam[] + }>( + (acc, part) => { + if (part.type === "tool_use") { + acc.toolMessages.push(part) + } else if (part.type === "text" || part.type === "image") { + acc.nonToolMessages.push(part) + } // assistant cannot send tool_result messages + return acc + }, + { nonToolMessages: [], toolMessages: [] }, + ) + + // Process non-tool messages + let content: string = "" + if (nonToolMessages.length > 0) { + content = nonToolMessages + .map((part) => { + if (part.type === "image") { + return "" // impossible as the assistant cannot send images + } + return part.text + }) + .join("\n") + } + + ollamaMessages.push({ + role: "assistant", + content, + }) + } + } + } + + return ollamaMessages +} diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 5705e53b..ae73ff21 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -79,6 +79,7 @@ type GlobalStateKey = | "openAiModelInfo" | "ollamaModelId" | "ollamaBaseUrl" + | "ollamaApiOptionsCtxNum" | "lmStudioModelId" | "lmStudioBaseUrl" | "anthropicBaseUrl" @@ -579,6 +580,7 @@ export class ClineProvider implements vscode.WebviewViewProvider { openAiModelInfo, ollamaModelId, ollamaBaseUrl, + ollamaApiOptionsCtxNum, lmStudioModelId, lmStudioBaseUrl, anthropicBaseUrl, @@ -624,6 +626,7 @@ export class ClineProvider implements vscode.WebviewViewProvider { await this.updateGlobalState("openAiModelInfo", openAiModelInfo) await this.updateGlobalState("ollamaModelId", ollamaModelId) await this.updateGlobalState("ollamaBaseUrl", ollamaBaseUrl) + await this.updateGlobalState("ollamaApiOptionsCtxNum", ollamaApiOptionsCtxNum) await this.updateGlobalState("lmStudioModelId", lmStudioModelId) await this.updateGlobalState("lmStudioBaseUrl", lmStudioBaseUrl) await this.updateGlobalState("anthropicBaseUrl", anthropicBaseUrl) @@ -1880,6 +1883,7 @@ Here is the project's README to help you get started:\n\n${mcpDetails.readmeCont openAiModelInfo, ollamaModelId, ollamaBaseUrl, + ollamaApiOptionsCtxNum, lmStudioModelId, lmStudioBaseUrl, anthropicBaseUrl, @@ -1938,6 +1942,7 @@ Here is the project's README to help you get started:\n\n${mcpDetails.readmeCont this.getGlobalState("openAiModelInfo") as Promise, this.getGlobalState("ollamaModelId") as Promise, this.getGlobalState("ollamaBaseUrl") as Promise, + this.getGlobalState("ollamaApiOptionsCtxNum") as Promise, this.getGlobalState("lmStudioModelId") as Promise, this.getGlobalState("lmStudioBaseUrl") as Promise, this.getGlobalState("anthropicBaseUrl") as Promise, @@ -2019,6 +2024,7 @@ Here is the project's README to help you get started:\n\n${mcpDetails.readmeCont openAiModelInfo, ollamaModelId, ollamaBaseUrl, + ollamaApiOptionsCtxNum, lmStudioModelId, lmStudioBaseUrl, anthropicBaseUrl, diff --git a/src/shared/api.ts b/src/shared/api.ts index fdfa799b..0ac794ce 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -44,6 +44,7 @@ export interface ApiHandlerOptions { openAiModelInfo?: ModelInfo ollamaModelId?: string ollamaBaseUrl?: string + ollamaApiOptionsCtxNum?: string lmStudioModelId?: string lmStudioBaseUrl?: string geminiApiKey?: string diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 245cebb8..b73195d3 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -1133,6 +1133,13 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is placeholder={"e.g. llama3.1"}> Model ID + + Model Context Window + {ollamaModels.length > 0 && (