vtcode-llm 0.187.0

LLM provider abstraction, client implementations, and streaming for VT Code
Documentation
//! Ollama server readiness: local install checks, tag discovery, and model listing.

use super::*;
use crate::provider::{
    ContentPart, FinishReason, LLMError, 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};

use crate::providers::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 crate::providers::error_handling::{format_network_error, format_parse_error};
use crate::providers::local_readiness::{invalidate_readiness_cache, resolve_local_model};
use crate::providers::local_server::LocalProvider;

/// Adapted from OpenAI Codex's codex-ollama/src/lib.rs
pub(super) async fn ensure_oss_ready(model: Option<&str>, base_url: Option<String>) -> std::io::Result<()> {
    let target_model = model.unwrap_or(models::ollama::DEFAULT_MODEL);

    let resolved_base_url = override_base_url(urls::OLLAMA_API_BASE, base_url, Some(env_vars::OLLAMA_BASE_URL));

    // Verify local Ollama is reachable
    let ollama_client = OllamaClient::try_from_base_url(&resolved_base_url).await?;

    // If the model is not present locally, pull it
    match ollama_client.fetch_models().await {
        Ok(existing_models) => {
            if !existing_models.iter().any(|m| m == target_model) {
                tracing::info!("Model '{target_model}' not found locally, pulling...");
                let mut reporter = CliPullProgressReporter::new();
                ollama_client.pull_with_reporter(target_model, &mut reporter).await?;
            }
        }
        Err(e) => {
            tracing::warn!("Failed to list Ollama models: {e}");
            // Continue anyway; model might exist but listing failed
        }
    }

    Ok(())
}

#[derive(Debug, Deserialize, Serialize)]
pub(super) struct OllamaTagsResponse {
    pub(super) models: Vec<OllamaTag>,
}

#[derive(Debug, Deserialize, Serialize)]
pub(super) struct OllamaTag {
    pub(super) name: Option<String>,
    pub(super) model: Option<String>,
    pub(super) modified_at: Option<String>,
    pub(super) size: Option<u64>,
    pub(super) digest: Option<String>,
    pub(super) details: Option<OllamaModelDetails>,
}

#[derive(Debug, Deserialize, Serialize)]
pub(super) struct OllamaModelDetails {
    pub(super) format: Option<String>,
    pub(super) family: Option<String>,
    pub(super) families: Option<Vec<String>>,
    pub(super) parameter_size: Option<String>,
    pub(super) quantization_level: Option<String>,
}

pub(super) fn ollama_model_name_from_fields<'a>(name: Option<&'a str>, model: Option<&'a str>) -> Option<&'a str> {
    name.or(model).map(str::trim).filter(|value| !value.is_empty())
}

pub(super) const OLLAMA_CONNECTION_ERROR: &str = "No running Ollama server detected. Start it with: `ollama serve` (after installing)\n\
     Install instructions: https://github.com/ollama/ollama?tab=readme-ov-file";

/// Fetches available local Ollama models from the Ollama API endpoint
pub async fn fetch_ollama_models(base_url: Option<String>) -> Result<Vec<String>, anyhow::Error> {
    use vtcode_config::constants::{env_vars, urls};

    let resolved_base_url = override_base_url(urls::OLLAMA_API_BASE, base_url, Some(env_vars::OLLAMA_BASE_URL));

    // Construct the tags endpoint URL
    let tags_url = format!("{resolved_base_url}/api/tags");

    // Create HTTP client with connection timeout
    let client = vtcode_commons::http::create_client_with_timeout(std::time::Duration::from_secs(5));

    // Make GET request to fetch models
    let response = client
        .get(&tags_url)
        .header("Content-Type", "application/json")
        .send()
        .await
        .map_err(|e| {
            // Connection refused is the expected state when Ollama isn't
            // running — log at debug so startup stays quiet for users without
            // local servers. The error is still propagated to the caller.
            tracing::debug!("Failed to connect to Ollama server: {e:?}");
            anyhow::anyhow!(OLLAMA_CONNECTION_ERROR)
        })?;

    if !response.status().is_success() {
        return Err(anyhow::anyhow!(
            "Failed to fetch Ollama models: HTTP {}. {}",
            response.status(),
            if response.status() == reqwest::StatusCode::NOT_FOUND {
                "Ensure Ollama server is running."
            } else {
                ""
            }
        ));
    }

    // Parse the response
    let tags_response: OllamaTagsResponse = response
        .json()
        .await
        .map_err(|e| anyhow::anyhow!("Failed to parse Ollama models response: {e}"))?;

    // Extract model names
    let model_names: Vec<String> = tags_response
        .models
        .into_iter()
        .filter_map(|model| {
            ollama_model_name_from_fields(model.name.as_deref(), model.model.as_deref()).map(str::to_string)
        })
        .collect();

    Ok(model_names)
}