|
| 1 | +/** |
| 2 | + * Ollama provider implementation |
| 3 | + */ |
| 4 | + |
| 5 | +import { TokenUsage } from '../../tokens.js'; |
| 6 | +import { LLMProvider } from '../provider.js'; |
| 7 | +import { |
| 8 | + GenerateOptions, |
| 9 | + LLMResponse, |
| 10 | + Message, |
| 11 | + ProviderOptions, |
| 12 | +} from '../types.js'; |
| 13 | + |
| 14 | +/** |
| 15 | + * Ollama-specific options |
| 16 | + */ |
| 17 | +export interface OllamaOptions extends ProviderOptions { |
| 18 | + baseUrl?: string; |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * Ollama provider implementation |
| 23 | + */ |
| 24 | +export class OllamaProvider implements LLMProvider { |
| 25 | + name: string = 'ollama'; |
| 26 | + provider: string = 'ollama.chat'; |
| 27 | + model: string; |
| 28 | + private baseUrl: string; |
| 29 | + |
| 30 | + constructor(model: string, options: OllamaOptions = {}) { |
| 31 | + this.model = model; |
| 32 | + this.baseUrl = |
| 33 | + options.baseUrl || |
| 34 | + process.env.OLLAMA_BASE_URL || |
| 35 | + 'http://localhost:11434'; |
| 36 | + |
| 37 | + // Ensure baseUrl doesn't end with a slash |
| 38 | + if (this.baseUrl.endsWith('/')) { |
| 39 | + this.baseUrl = this.baseUrl.slice(0, -1); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Generate text using Ollama API |
| 45 | + */ |
| 46 | + async generateText(options: GenerateOptions): Promise<LLMResponse> { |
| 47 | + const { |
| 48 | + messages, |
| 49 | + functions, |
| 50 | + temperature = 0.7, |
| 51 | + maxTokens, |
| 52 | + topP, |
| 53 | + frequencyPenalty, |
| 54 | + presencePenalty, |
| 55 | + } = options; |
| 56 | + |
| 57 | + // Format messages for Ollama API |
| 58 | + const formattedMessages = this.formatMessages(messages); |
| 59 | + |
| 60 | + try { |
| 61 | + // Prepare request options |
| 62 | + const requestOptions: any = { |
| 63 | + model: this.model, |
| 64 | + messages: formattedMessages, |
| 65 | + stream: false, |
| 66 | + options: { |
| 67 | + temperature: temperature, |
| 68 | + // Ollama uses top_k instead of top_p, but we'll include top_p if provided |
| 69 | + ...(topP !== undefined && { top_p: topP }), |
| 70 | + ...(frequencyPenalty !== undefined && { |
| 71 | + frequency_penalty: frequencyPenalty, |
| 72 | + }), |
| 73 | + ...(presencePenalty !== undefined && { |
| 74 | + presence_penalty: presencePenalty, |
| 75 | + }), |
| 76 | + }, |
| 77 | + }; |
| 78 | + |
| 79 | + // Add max_tokens if provided |
| 80 | + if (maxTokens !== undefined) { |
| 81 | + requestOptions.options.num_predict = maxTokens; |
| 82 | + } |
| 83 | + |
| 84 | + // Add functions/tools if provided |
| 85 | + if (functions && functions.length > 0) { |
| 86 | + requestOptions.tools = functions.map((fn) => ({ |
| 87 | + name: fn.name, |
| 88 | + description: fn.description, |
| 89 | + parameters: fn.parameters, |
| 90 | + })); |
| 91 | + } |
| 92 | + |
| 93 | + // Make the API request |
| 94 | + const response = await fetch(`${this.baseUrl}/api/chat`, { |
| 95 | + method: 'POST', |
| 96 | + headers: { |
| 97 | + 'Content-Type': 'application/json', |
| 98 | + }, |
| 99 | + body: JSON.stringify(requestOptions), |
| 100 | + }); |
| 101 | + |
| 102 | + if (!response.ok) { |
| 103 | + const errorText = await response.text(); |
| 104 | + throw new Error(`Ollama API error: ${response.status} ${errorText}`); |
| 105 | + } |
| 106 | + |
| 107 | + const data = await response.json(); |
| 108 | + |
| 109 | + // Extract content and tool calls |
| 110 | + const content = data.message?.content || ''; |
| 111 | + const toolCalls = |
| 112 | + data.message?.tool_calls?.map((toolCall: any) => ({ |
| 113 | + id: |
| 114 | + toolCall.id || |
| 115 | + `tool-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`, |
| 116 | + name: toolCall.name, |
| 117 | + content: JSON.stringify(toolCall.args || toolCall.arguments || {}), |
| 118 | + })) || []; |
| 119 | + |
| 120 | + // Create token usage from response data |
| 121 | + const tokenUsage = new TokenUsage(); |
| 122 | + tokenUsage.input = data.prompt_eval_count || 0; |
| 123 | + tokenUsage.output = data.eval_count || 0; |
| 124 | + |
| 125 | + return { |
| 126 | + text: content, |
| 127 | + toolCalls: toolCalls, |
| 128 | + tokenUsage: tokenUsage, |
| 129 | + }; |
| 130 | + } catch (error) { |
| 131 | + throw new Error(`Error calling Ollama API: ${(error as Error).message}`); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + /** |
| 136 | + * Format messages for Ollama API |
| 137 | + */ |
| 138 | + private formatMessages(messages: Message[]): any[] { |
| 139 | + return messages.map((msg) => { |
| 140 | + if ( |
| 141 | + msg.role === 'user' || |
| 142 | + msg.role === 'assistant' || |
| 143 | + msg.role === 'system' |
| 144 | + ) { |
| 145 | + return { |
| 146 | + role: msg.role, |
| 147 | + content: msg.content, |
| 148 | + }; |
| 149 | + } else if (msg.role === 'tool_result') { |
| 150 | + // Ollama expects tool results as a 'tool' role |
| 151 | + return { |
| 152 | + role: 'tool', |
| 153 | + content: msg.content, |
| 154 | + tool_call_id: msg.tool_use_id, |
| 155 | + }; |
| 156 | + } else if (msg.role === 'tool_use') { |
| 157 | + // We'll convert tool_use to assistant messages with tool_calls |
| 158 | + return { |
| 159 | + role: 'assistant', |
| 160 | + content: '', |
| 161 | + tool_calls: [ |
| 162 | + { |
| 163 | + id: msg.id, |
| 164 | + name: msg.name, |
| 165 | + arguments: msg.content, |
| 166 | + }, |
| 167 | + ], |
| 168 | + }; |
| 169 | + } |
| 170 | + // Default fallback for unknown message types |
| 171 | + return { |
| 172 | + role: 'user', |
| 173 | + content: (msg as any).content || '', |
| 174 | + }; |
| 175 | + }); |
| 176 | + } |
| 177 | +} |
0 commit comments