vtcode-llm 0.187.0

LLM provider abstraction, client implementations, and streaming for VT Code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! Ollama provider implementation
//!
//! Adapted from [openai/codex] `codex-ollama` (Apache-2.0).
//! Copyright 2025 OpenAI. See the repository `THIRD-PARTY-NOTICES` file for
//! full attribution.
//!
//! [openai/codex]: https://github.com/openai/codex

use crate::client::LLMClient;
use crate::provider::{
    ContentPart, FinishReason, LLMError, LLMProvider, LLMRequest, LLMResponse, LLMStream, LLMStreamEvent, Message,
    MessageContent, MessageRole, ToolCall, ToolChoice, ToolDefinition, Usage,
};
use anyhow::Result;
use async_stream::try_stream;
use async_trait::async_trait;
use futures::StreamExt;
use hashbrown::HashMap;
use reqwest::Client as HttpClient;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use vtcode_config::TimeoutsConfig;
use vtcode_config::constants::{env_vars, models, urls};
use vtcode_config::core::{AnthropicConfig, ModelConfig, PromptCachingConfig};

pub(crate) mod client;
pub(crate) mod parser;
pub mod pull;
pub(crate) mod url;

pub(crate) use client::OllamaClient;
pub(crate) use parser::pull_events_from_value;
pub(crate) use pull::{CliPullProgressReporter, OllamaPullEvent, OllamaPullProgressReporter, TuiPullProgressReporter};
pub(crate) use url::{base_url_to_host_root, is_openai_compatible_base_url};

use super::common::{
    assistant_interleaved_history_text, collect_history_system_directives, extract_reasoning_text_from_detail_values,
    extract_reasoning_text_from_serialized_details, is_minimax_m2_model, merge_system_prompt_with_history_directives,
    override_base_url, parse_client_prompt_common, resolve_model, serialize_reasoning_detail_values,
};
use super::error_handling::{format_network_error, format_parse_error};
use super::local_readiness::{invalidate_readiness_cache, resolve_local_model};
use super::local_server::LocalProvider;

/// Prepare the local OSS environment when using Ollama.
///
/// - Ensures a local Ollama server is reachable.
/// - Checks if the model exists locally and pulls it if missing.
///
mod manage;
mod response;
mod stream;
mod wire;

pub use manage::fetch_ollama_models;
use manage::{OLLAMA_CONNECTION_ERROR, ensure_oss_ready, ollama_model_name_from_fields};
use wire::{OllamaChatRequest, OllamaChatResponse, OllamaErrorResponse};
mod payload;

pub struct OllamaProvider {
    http_client: HttpClient,
    base_url: String,
    model: String,
    api_key: Option<String>,
    model_behavior: Option<ModelConfig>,
}

impl OllamaProvider {
    fn merged_system_prompt(request: &LLMRequest) -> Option<String> {
        const HISTORY_DIRECTIVES_SECTION_HEADER: &str = "[History Directives]";
        let directives = collect_history_system_directives(request);
        merge_system_prompt_with_history_directives(
            request.system_prompt.as_ref().map(|prompt| prompt.as_ref()),
            &directives,
            HISTORY_DIRECTIVES_SECTION_HEADER,
        )
    }

    pub fn new(api_key: String) -> Self {
        Self::with_model(api_key, models::ollama::DEFAULT_MODEL.to_string())
    }

    fn with_model(api_key: String, model: String) -> Self {
        Self::with_model_internal(model, None, Some(api_key), None)
    }

    pub fn new_with_client(
        api_key: String,
        model: String,
        http_client: reqwest::Client,
        base_url: String,
        _timeouts: TimeoutsConfig,
    ) -> Self {
        Self {
            http_client,
            base_url,
            model,
            api_key: Some(api_key),
            model_behavior: None,
        }
    }

    pub fn from_config(
        api_key: Option<String>,
        model: Option<String>,
        base_url: Option<String>,
        _prompt_cache: Option<PromptCachingConfig>,
        _timeouts: Option<TimeoutsConfig>,
        _anthropic: Option<AnthropicConfig>,
        model_behavior: Option<ModelConfig>,
    ) -> Self {
        let resolved_model = resolve_model(model, models::ollama::DEFAULT_MODEL);
        Self::with_model_internal(resolved_model, base_url, api_key, model_behavior)
    }

    fn normalize_api_key(api_key: Option<String>) -> Option<String> {
        api_key.and_then(|value| {
            let trimmed = value.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_string())
            }
        })
    }

    fn with_model_internal(
        model: String,
        base_url: Option<String>,
        api_key: Option<String>,
        model_behavior: Option<ModelConfig>,
    ) -> Self {
        let normalized_api_key = Self::normalize_api_key(api_key);
        let is_cloud_model = model.contains(":cloud") || model.contains("-cloud");

        let default_base = if is_cloud_model {
            urls::OLLAMA_CLOUD_API_BASE
        } else {
            urls::OLLAMA_API_BASE
        };

        let resolved_base = override_base_url(default_base, base_url, Some(env_vars::OLLAMA_BASE_URL));
        let target_is_local = super::local_server::is_local_base_url(&resolved_base);

        // Never send API keys to local endpoints; keep keys for cloud/remote targets
        let effective_api_key = if target_is_local { None } else { normalized_api_key };

        Self {
            http_client: vtcode_commons::http::create_default_client(),
            base_url: resolved_base,
            model,
            api_key: effective_api_key,
            model_behavior,
        }
    }

    fn chat_url(&self) -> String {
        format!("{}/api/chat", self.base_url.trim_end_matches('/'))
    }

    fn authorized_post(&self, url: String) -> reqwest::RequestBuilder {
        let builder = self.http_client.post(url);
        if let Some(api_key) = &self.api_key {
            builder.bearer_auth(api_key)
        } else {
            builder
        }
    }

    fn parse_client_prompt(&self, prompt: &str) -> LLMRequest {
        parse_client_prompt_common(prompt, &self.model, |value| self.parse_chat_request(value))
    }

    /// Verify the server is up and the model is available before generating.
    /// Returns the (possibly substituted) model id or a structured error with a
    /// recovery command (`ollama pull <model>` / `/local start ollama`).
    ///
    /// `VTCODE_LOCAL_AUTOPULL` is deliberately strict (`1`/`true`, no
    /// whitespace/casing slack) because enabling it side-effects: a missing
    /// model triggers a network `ollama pull` at generate time. Widening to
    /// the canonical tri-state set (canonical parser, `parse_bool_env_value`)
    /// would silently enable downloads for casual values (`yes`/`on`). Keep a
    /// minimal literal comparison; the canonical parser governs the non-wire,
    /// non-side-effecting flags.
    async fn ensure_ready(&self, requested: &str) -> Result<String, LLMError> {
        let autopull = std::env::var("VTCODE_LOCAL_AUTOPULL")
            .ok()
            .is_some_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));

        match resolve_local_model(LocalProvider::Ollama, requested, Some(&self.base_url)).await {
            Ok(model) => Ok(model),
            Err(err) if autopull => {
                let model = match &err {
                    super::local_readiness::LocalReadinessError::ModelMissing { model, .. } => model.clone(),
                    _ => return Err(err.to_llm_error("Ollama")),
                };
                match ensure_oss_ready(Some(&model), Some(self.base_url.clone())).await {
                    Ok(()) => {
                        invalidate_readiness_cache();
                        Ok(model)
                    }
                    Err(_) => Err(err.to_llm_error("Ollama")),
                }
            }
            Err(err) => Err(err.to_llm_error("Ollama")),
        }
    }

    fn parse_chat_request(&self, value: &Value) -> Option<LLMRequest> {
        let messages_value = value.get("messages")?.as_array()?;
        let mut system_prompt = value
            .get("system")
            .and_then(|entry| entry.as_str())
            .filter(|text| !text.trim().is_empty())
            .map(|text| text.to_string());
        let mut messages = Vec::new();

        for entry in messages_value {
            let role = entry
                .get("role")
                .and_then(|r| r.as_str())
                .unwrap_or(vtcode_config::constants::message_roles::USER);
            let content = entry
                .get("content")
                .map(|c| match c {
                    Value::String(text) => text.to_string(),
                    other => other.to_string(),
                })
                .unwrap_or_default();

            if content.trim().is_empty() {
                continue;
            }

            match role {
                "system" => {
                    if system_prompt.is_none() {
                        system_prompt = Some(content);
                    }
                }
                "assistant" => messages.push(Message::assistant(content)),
                "user" => messages.push(Message::user(content)),
                _ => {}
            }
        }

        if messages.is_empty() {
            return None;
        }

        let tools = value
            .get("tools")
            .and_then(|entry| serde_json::from_value::<Vec<ToolDefinition>>(entry.clone()).ok());

        Some(LLMRequest {
            messages: std::sync::Arc::new(messages),
            system_prompt: system_prompt.map(std::sync::Arc::from),
            tools: tools.map(std::sync::Arc::new),
            model: value
                .get("model")
                .and_then(|m| m.as_str())
                .filter(|m| !m.trim().is_empty())
                .map(|m| m.to_string())
                .unwrap_or_else(|| self.model.clone()),
            max_tokens: value
                .get("max_tokens")
                .and_then(|entry| entry.as_u64())
                .map(|value| value as u32),
            temperature: value
                .get("temperature")
                .and_then(|entry| entry.as_f64())
                .map(|value| value as f32),
            stream: value.get("stream").and_then(|entry| entry.as_bool()).unwrap_or(false),
            ..Default::default()
        })
    }

    fn authorized_post_with_key(http_client: &HttpClient, url: &str, api_key: Option<&str>) -> reqwest::RequestBuilder {
        let builder = http_client.post(url.to_string());
        if let Some(value) = api_key {
            builder.bearer_auth(value)
        } else {
            builder
        }
    }

    async fn request_non_stream_response(
        http_client: &HttpClient,
        url: &str,
        api_key: Option<&str>,
        payload: &OllamaChatRequest,
        model: String,
    ) -> Result<LLMResponse, LLMError> {
        let response = Self::authorized_post_with_key(http_client, url, api_key)
            .json(payload)
            .send()
            .await
            .map_err(|e| format_network_error("Ollama", &e))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = crate::providers::common::read_provider_error_body(response).await;
            let error_message =
                Self::extract_error(&body).unwrap_or_else(|| format!("Ollama request failed ({status}): {body}"));
            return Err(LLMError::Provider { message: error_message, metadata: None });
        }

        let parsed = response
            .json::<OllamaChatResponse>()
            .await
            .map_err(|e| format_parse_error("Ollama", &e))?;
        Self::response_from_chat_payload(model, parsed)
    }

    fn extract_error(body: &str) -> Option<String> {
        serde_json::from_str::<OllamaErrorResponse>(body)
            .ok()
            .and_then(|resp| resp.error)
    }
}

#[async_trait]
impl LLMProvider for OllamaProvider {
    fn name(&self) -> &str {
        "ollama"
    }

    fn supports_streaming(&self) -> bool {
        true
    }

    fn supports_non_streaming(&self, _model: &str) -> bool {
        // Pinned so the stream-timeout fallback cannot silently regress.
        true
    }

    fn supports_tools(&self, _model: &str) -> bool {
        true
    }

    fn supports_reasoning(&self, model: &str) -> bool {
        // Codex-inspired robustness: Setting model_supports_reasoning to false
        // does NOT disable it for known reasoning models.
        models::ollama::REASONING_MODELS.contains(&model)
            || self
                .model_behavior
                .as_ref()
                .and_then(|b| b.model_supports_reasoning)
                .unwrap_or(false)
    }

    fn supports_reasoning_effort(&self, model: &str) -> bool {
        // Same robustness logic for reasoning effort
        models::ollama::REASONING_LEVEL_MODELS.contains(&model)
            || self
                .model_behavior
                .as_ref()
                .and_then(|b| b.model_supports_reasoning_effort)
                .unwrap_or(false)
    }

    async fn generate(&self, mut request: LLMRequest) -> Result<LLMResponse, LLMError> {
        self.validate_request(&request)?;
        if request.model.is_empty() {
            request.model = self.model.clone();
        }
        let resolved = self.ensure_ready(&request.model).await?;
        request.model = resolved;
        let model = request.model.clone();
        let payload = self.build_payload(&request, false)?;
        let url = self.chat_url();
        Self::request_non_stream_response(&self.http_client, &url, self.api_key.as_deref(), &payload, model).await
    }

    async fn stream(&self, request: LLMRequest) -> Result<LLMStream, LLMError> {
        self.stream_inner(request).await
    }
    fn supported_models(&self) -> Vec<String> {
        models::ollama::SUPPORTED_MODELS.iter().map(|model| model.to_string()).collect()
    }

    fn validate_request(&self, request: &LLMRequest) -> Result<(), LLMError> {
        if let Some(tool_choice) = &request.tool_choice {
            match tool_choice {
                ToolChoice::Auto | ToolChoice::None | ToolChoice::AllowedTools(_) => {}
                _ => {
                    return Err(LLMError::InvalidRequest {
                        message: "Ollama does not support explicit tool_choice overrides".to_string(),
                        metadata: None,
                    });
                }
            }
        }

        if request.parallel_tool_calls.is_some() || request.parallel_tool_config.is_some() {
            return Err(LLMError::InvalidRequest {
                message: "Ollama does not support parallel tool configuration".to_string(),
                metadata: None,
            });
        }

        for message in request.messages.iter() {
            if matches!(message.role, MessageRole::Tool) && message.tool_call_id.is_none() {
                return Err(LLMError::InvalidRequest {
                    message: "Ollama tool responses must include tool_call_id".to_string(),
                    metadata: None,
                });
            }
        }

        Ok(())
    }
}

#[async_trait]
impl LLMClient for OllamaProvider {
    async fn generate(&mut self, prompt: &str) -> Result<LLMResponse, LLMError> {
        let mut request = self.parse_client_prompt(prompt);
        if request.model.is_empty() {
            request.model = self.model.clone();
        }
        Ok(LLMProvider::generate(self, request).await?)
    }

    fn model_id(&self) -> &str {
        &self.model
    }
}

#[cfg(test)]
mod tests;