Skip to main content

vtcode_llm/providers/ollama/
mod.rs

1//! Ollama provider implementation
2//!
3//! Adapted from [openai/codex] `codex-ollama` (Apache-2.0).
4//! Copyright 2025 OpenAI. See the repository `THIRD-PARTY-NOTICES` file for
5//! full attribution.
6//!
7//! [openai/codex]: https://github.com/openai/codex
8
9use crate::client::LLMClient;
10use crate::provider::{
11    ContentPart, FinishReason, LLMError, LLMProvider, LLMRequest, LLMResponse, LLMStream, LLMStreamEvent, Message,
12    MessageContent, MessageRole, ToolCall, ToolChoice, ToolDefinition, Usage,
13};
14use anyhow::Result;
15use async_stream::try_stream;
16use async_trait::async_trait;
17use futures::StreamExt;
18use hashbrown::HashMap;
19use reqwest::Client as HttpClient;
20use serde::{Deserialize, Serialize};
21use serde_json::{Map, Value};
22use vtcode_config::TimeoutsConfig;
23use vtcode_config::constants::{env_vars, models, urls};
24use vtcode_config::core::{AnthropicConfig, ModelConfig, PromptCachingConfig};
25
26pub(crate) mod client;
27pub(crate) mod parser;
28pub mod pull;
29pub(crate) mod url;
30
31pub(crate) use client::OllamaClient;
32pub(crate) use parser::pull_events_from_value;
33pub(crate) use pull::{CliPullProgressReporter, OllamaPullEvent, OllamaPullProgressReporter, TuiPullProgressReporter};
34pub(crate) use url::{base_url_to_host_root, is_openai_compatible_base_url};
35
36use super::common::{
37    assistant_interleaved_history_text, collect_history_system_directives, extract_reasoning_text_from_detail_values,
38    extract_reasoning_text_from_serialized_details, is_minimax_m2_model, merge_system_prompt_with_history_directives,
39    override_base_url, parse_client_prompt_common, resolve_model, serialize_reasoning_detail_values,
40};
41use super::error_handling::{format_network_error, format_parse_error};
42use super::local_readiness::{invalidate_readiness_cache, resolve_local_model};
43use super::local_server::LocalProvider;
44
45/// Prepare the local OSS environment when using Ollama.
46///
47/// - Ensures a local Ollama server is reachable.
48/// - Checks if the model exists locally and pulls it if missing.
49///
50mod manage;
51mod response;
52mod stream;
53mod wire;
54
55pub use manage::fetch_ollama_models;
56use manage::{OLLAMA_CONNECTION_ERROR, ensure_oss_ready, ollama_model_name_from_fields};
57use wire::{OllamaChatRequest, OllamaChatResponse, OllamaErrorResponse};
58mod payload;
59
60pub struct OllamaProvider {
61    http_client: HttpClient,
62    base_url: String,
63    model: String,
64    api_key: Option<String>,
65    model_behavior: Option<ModelConfig>,
66}
67
68impl OllamaProvider {
69    fn merged_system_prompt(request: &LLMRequest) -> Option<String> {
70        const HISTORY_DIRECTIVES_SECTION_HEADER: &str = "[History Directives]";
71        let directives = collect_history_system_directives(request);
72        merge_system_prompt_with_history_directives(
73            request.system_prompt.as_ref().map(|prompt| prompt.as_ref()),
74            &directives,
75            HISTORY_DIRECTIVES_SECTION_HEADER,
76        )
77    }
78
79    pub fn new(api_key: String) -> Self {
80        Self::with_model(api_key, models::ollama::DEFAULT_MODEL.to_string())
81    }
82
83    fn with_model(api_key: String, model: String) -> Self {
84        Self::with_model_internal(model, None, Some(api_key), None)
85    }
86
87    pub fn new_with_client(
88        api_key: String,
89        model: String,
90        http_client: reqwest::Client,
91        base_url: String,
92        _timeouts: TimeoutsConfig,
93    ) -> Self {
94        Self {
95            http_client,
96            base_url,
97            model,
98            api_key: Some(api_key),
99            model_behavior: None,
100        }
101    }
102
103    pub fn from_config(
104        api_key: Option<String>,
105        model: Option<String>,
106        base_url: Option<String>,
107        _prompt_cache: Option<PromptCachingConfig>,
108        _timeouts: Option<TimeoutsConfig>,
109        _anthropic: Option<AnthropicConfig>,
110        model_behavior: Option<ModelConfig>,
111    ) -> Self {
112        let resolved_model = resolve_model(model, models::ollama::DEFAULT_MODEL);
113        Self::with_model_internal(resolved_model, base_url, api_key, model_behavior)
114    }
115
116    fn normalize_api_key(api_key: Option<String>) -> Option<String> {
117        api_key.and_then(|value| {
118            let trimmed = value.trim();
119            if trimmed.is_empty() {
120                None
121            } else {
122                Some(trimmed.to_string())
123            }
124        })
125    }
126
127    fn with_model_internal(
128        model: String,
129        base_url: Option<String>,
130        api_key: Option<String>,
131        model_behavior: Option<ModelConfig>,
132    ) -> Self {
133        let normalized_api_key = Self::normalize_api_key(api_key);
134        let is_cloud_model = model.contains(":cloud") || model.contains("-cloud");
135
136        let default_base = if is_cloud_model {
137            urls::OLLAMA_CLOUD_API_BASE
138        } else {
139            urls::OLLAMA_API_BASE
140        };
141
142        let resolved_base = override_base_url(default_base, base_url, Some(env_vars::OLLAMA_BASE_URL));
143        let target_is_local = super::local_server::is_local_base_url(&resolved_base);
144
145        // Never send API keys to local endpoints; keep keys for cloud/remote targets
146        let effective_api_key = if target_is_local { None } else { normalized_api_key };
147
148        Self {
149            http_client: vtcode_commons::http::create_default_client(),
150            base_url: resolved_base,
151            model,
152            api_key: effective_api_key,
153            model_behavior,
154        }
155    }
156
157    fn chat_url(&self) -> String {
158        format!("{}/api/chat", self.base_url.trim_end_matches('/'))
159    }
160
161    fn authorized_post(&self, url: String) -> reqwest::RequestBuilder {
162        let builder = self.http_client.post(url);
163        if let Some(api_key) = &self.api_key {
164            builder.bearer_auth(api_key)
165        } else {
166            builder
167        }
168    }
169
170    fn parse_client_prompt(&self, prompt: &str) -> LLMRequest {
171        parse_client_prompt_common(prompt, &self.model, |value| self.parse_chat_request(value))
172    }
173
174    /// Verify the server is up and the model is available before generating.
175    /// Returns the (possibly substituted) model id or a structured error with a
176    /// recovery command (`ollama pull <model>` / `/local start ollama`).
177    ///
178    /// `VTCODE_LOCAL_AUTOPULL` is deliberately strict (`1`/`true`, no
179    /// whitespace/casing slack) because enabling it side-effects: a missing
180    /// model triggers a network `ollama pull` at generate time. Widening to
181    /// the canonical tri-state set (canonical parser, `parse_bool_env_value`)
182    /// would silently enable downloads for casual values (`yes`/`on`). Keep a
183    /// minimal literal comparison; the canonical parser governs the non-wire,
184    /// non-side-effecting flags.
185    async fn ensure_ready(&self, requested: &str) -> Result<String, LLMError> {
186        let autopull = std::env::var("VTCODE_LOCAL_AUTOPULL")
187            .ok()
188            .is_some_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
189
190        match resolve_local_model(LocalProvider::Ollama, requested, Some(&self.base_url)).await {
191            Ok(model) => Ok(model),
192            Err(err) if autopull => {
193                let model = match &err {
194                    super::local_readiness::LocalReadinessError::ModelMissing { model, .. } => model.clone(),
195                    _ => return Err(err.to_llm_error("Ollama")),
196                };
197                match ensure_oss_ready(Some(&model), Some(self.base_url.clone())).await {
198                    Ok(()) => {
199                        invalidate_readiness_cache();
200                        Ok(model)
201                    }
202                    Err(_) => Err(err.to_llm_error("Ollama")),
203                }
204            }
205            Err(err) => Err(err.to_llm_error("Ollama")),
206        }
207    }
208
209    fn parse_chat_request(&self, value: &Value) -> Option<LLMRequest> {
210        let messages_value = value.get("messages")?.as_array()?;
211        let mut system_prompt = value
212            .get("system")
213            .and_then(|entry| entry.as_str())
214            .filter(|text| !text.trim().is_empty())
215            .map(|text| text.to_string());
216        let mut messages = Vec::new();
217
218        for entry in messages_value {
219            let role = entry
220                .get("role")
221                .and_then(|r| r.as_str())
222                .unwrap_or(vtcode_config::constants::message_roles::USER);
223            let content = entry
224                .get("content")
225                .map(|c| match c {
226                    Value::String(text) => text.to_string(),
227                    other => other.to_string(),
228                })
229                .unwrap_or_default();
230
231            if content.trim().is_empty() {
232                continue;
233            }
234
235            match role {
236                "system" => {
237                    if system_prompt.is_none() {
238                        system_prompt = Some(content);
239                    }
240                }
241                "assistant" => messages.push(Message::assistant(content)),
242                "user" => messages.push(Message::user(content)),
243                _ => {}
244            }
245        }
246
247        if messages.is_empty() {
248            return None;
249        }
250
251        let tools = value
252            .get("tools")
253            .and_then(|entry| serde_json::from_value::<Vec<ToolDefinition>>(entry.clone()).ok());
254
255        Some(LLMRequest {
256            messages: std::sync::Arc::new(messages),
257            system_prompt: system_prompt.map(std::sync::Arc::from),
258            tools: tools.map(std::sync::Arc::new),
259            model: value
260                .get("model")
261                .and_then(|m| m.as_str())
262                .filter(|m| !m.trim().is_empty())
263                .map(|m| m.to_string())
264                .unwrap_or_else(|| self.model.clone()),
265            max_tokens: value
266                .get("max_tokens")
267                .and_then(|entry| entry.as_u64())
268                .map(|value| value as u32),
269            temperature: value
270                .get("temperature")
271                .and_then(|entry| entry.as_f64())
272                .map(|value| value as f32),
273            stream: value.get("stream").and_then(|entry| entry.as_bool()).unwrap_or(false),
274            ..Default::default()
275        })
276    }
277
278    fn authorized_post_with_key(http_client: &HttpClient, url: &str, api_key: Option<&str>) -> reqwest::RequestBuilder {
279        let builder = http_client.post(url.to_string());
280        if let Some(value) = api_key {
281            builder.bearer_auth(value)
282        } else {
283            builder
284        }
285    }
286
287    async fn request_non_stream_response(
288        http_client: &HttpClient,
289        url: &str,
290        api_key: Option<&str>,
291        payload: &OllamaChatRequest,
292        model: String,
293    ) -> Result<LLMResponse, LLMError> {
294        let response = Self::authorized_post_with_key(http_client, url, api_key)
295            .json(payload)
296            .send()
297            .await
298            .map_err(|e| format_network_error("Ollama", &e))?;
299
300        if !response.status().is_success() {
301            let status = response.status();
302            let body = crate::providers::common::read_provider_error_body(response).await;
303            let error_message =
304                Self::extract_error(&body).unwrap_or_else(|| format!("Ollama request failed ({status}): {body}"));
305            return Err(LLMError::Provider { message: error_message, metadata: None });
306        }
307
308        let parsed = response
309            .json::<OllamaChatResponse>()
310            .await
311            .map_err(|e| format_parse_error("Ollama", &e))?;
312        Self::response_from_chat_payload(model, parsed)
313    }
314
315    fn extract_error(body: &str) -> Option<String> {
316        serde_json::from_str::<OllamaErrorResponse>(body)
317            .ok()
318            .and_then(|resp| resp.error)
319    }
320}
321
322#[async_trait]
323impl LLMProvider for OllamaProvider {
324    fn name(&self) -> &str {
325        "ollama"
326    }
327
328    fn supports_streaming(&self) -> bool {
329        true
330    }
331
332    fn supports_non_streaming(&self, _model: &str) -> bool {
333        // Pinned so the stream-timeout fallback cannot silently regress.
334        true
335    }
336
337    fn supports_tools(&self, _model: &str) -> bool {
338        true
339    }
340
341    fn supports_reasoning(&self, model: &str) -> bool {
342        // Codex-inspired robustness: Setting model_supports_reasoning to false
343        // does NOT disable it for known reasoning models.
344        models::ollama::REASONING_MODELS.contains(&model)
345            || self
346                .model_behavior
347                .as_ref()
348                .and_then(|b| b.model_supports_reasoning)
349                .unwrap_or(false)
350    }
351
352    fn supports_reasoning_effort(&self, model: &str) -> bool {
353        // Same robustness logic for reasoning effort
354        models::ollama::REASONING_LEVEL_MODELS.contains(&model)
355            || self
356                .model_behavior
357                .as_ref()
358                .and_then(|b| b.model_supports_reasoning_effort)
359                .unwrap_or(false)
360    }
361
362    async fn generate(&self, mut request: LLMRequest) -> Result<LLMResponse, LLMError> {
363        self.validate_request(&request)?;
364        if request.model.is_empty() {
365            request.model = self.model.clone();
366        }
367        let resolved = self.ensure_ready(&request.model).await?;
368        request.model = resolved;
369        let model = request.model.clone();
370        let payload = self.build_payload(&request, false)?;
371        let url = self.chat_url();
372        Self::request_non_stream_response(&self.http_client, &url, self.api_key.as_deref(), &payload, model).await
373    }
374
375    async fn stream(&self, request: LLMRequest) -> Result<LLMStream, LLMError> {
376        self.stream_inner(request).await
377    }
378    fn supported_models(&self) -> Vec<String> {
379        models::ollama::SUPPORTED_MODELS.iter().map(|model| model.to_string()).collect()
380    }
381
382    fn validate_request(&self, request: &LLMRequest) -> Result<(), LLMError> {
383        if let Some(tool_choice) = &request.tool_choice {
384            match tool_choice {
385                ToolChoice::Auto | ToolChoice::None | ToolChoice::AllowedTools(_) => {}
386                _ => {
387                    return Err(LLMError::InvalidRequest {
388                        message: "Ollama does not support explicit tool_choice overrides".to_string(),
389                        metadata: None,
390                    });
391                }
392            }
393        }
394
395        if request.parallel_tool_calls.is_some() || request.parallel_tool_config.is_some() {
396            return Err(LLMError::InvalidRequest {
397                message: "Ollama does not support parallel tool configuration".to_string(),
398                metadata: None,
399            });
400        }
401
402        for message in request.messages.iter() {
403            if matches!(message.role, MessageRole::Tool) && message.tool_call_id.is_none() {
404                return Err(LLMError::InvalidRequest {
405                    message: "Ollama tool responses must include tool_call_id".to_string(),
406                    metadata: None,
407                });
408            }
409        }
410
411        Ok(())
412    }
413}
414
415#[async_trait]
416impl LLMClient for OllamaProvider {
417    async fn generate(&mut self, prompt: &str) -> Result<LLMResponse, LLMError> {
418        let mut request = self.parse_client_prompt(prompt);
419        if request.model.is_empty() {
420            request.model = self.model.clone();
421        }
422        Ok(LLMProvider::generate(self, request).await?)
423    }
424
425    fn model_id(&self) -> &str {
426        &self.model
427    }
428}
429
430#[cfg(test)]
431mod tests;