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;
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));
let ollama_client = OllamaClient::try_from_base_url(&resolved_base_url).await?;
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}");
}
}
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";
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));
let tags_url = format!("{resolved_base_url}/api/tags");
let client = vtcode_commons::http::create_client_with_timeout(std::time::Duration::from_secs(5));
let response = client
.get(&tags_url)
.header("Content-Type", "application/json")
.send()
.await
.map_err(|e| {
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 {
""
}
));
}
let tags_response: OllamaTagsResponse = response
.json()
.await
.map_err(|e| anyhow::anyhow!("Failed to parse Ollama models response: {e}"))?;
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)
}