vtcode-llm 0.185.5

LLM provider abstraction, client implementations, and streaming for VT Code
Documentation
//! Ollama response conversion: tool calls, usage, finish reasons, and payload mapping.

use super::wire::{OllamaChatResponse, OllamaResponseToolCall};
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;

impl OllamaProvider {
    pub(super) fn convert_tool_calls(
        tool_calls: Option<Vec<OllamaResponseToolCall>>,
    ) -> Result<Option<Vec<ToolCall>>, LLMError> {
        let Some(tool_calls) = tool_calls else {
            return Ok(None);
        };

        if tool_calls.is_empty() {
            return Ok(None);
        }

        let mut converted = Vec::new();
        for call in tool_calls.into_iter() {
            let function = call.function.ok_or_else(|| LLMError::Provider {
                message: "Ollama response missing function details for tool call".to_string(),
                metadata: None,
            })?;

            let name = function.name.ok_or_else(|| LLMError::Provider {
                message: "Ollama response missing tool function name".to_string(),
                metadata: None,
            })?;

            let arguments_value = function.arguments.unwrap_or_else(|| Value::Object(Map::new()));
            let arguments = match arguments_value {
                Value::String(raw) => raw,
                other => serde_json::to_string(&other).map_err(|err| LLMError::Provider {
                    message: format!("Failed to serialize Ollama tool arguments: {err}"),
                    metadata: None,
                })?,
            };

            // Ollama omits tool-call ids; index-based fallbacks reset every
            // response and collide across assistant messages downstream.
            let id = crate::providers::shared::generate_tool_call_id();

            converted.push(ToolCall::function(id, name, arguments));
        }

        Ok(Some(converted))
    }

    pub(super) fn usage_from_counts(prompt_tokens: Option<u32>, completion_tokens: Option<u32>) -> Option<Usage> {
        if prompt_tokens.is_none() && completion_tokens.is_none() {
            return None;
        }

        let prompt = prompt_tokens.unwrap_or_default();
        let completion = completion_tokens.unwrap_or_default();
        Some(Usage {
            prompt_tokens: prompt,
            completion_tokens: completion,
            total_tokens: prompt + completion,
            cached_prompt_tokens: None,
            cache_creation_tokens: None,
            cache_read_tokens: None,
            iterations: None,
        })
    }

    pub(super) fn finish_reason_from(reason: Option<&str>) -> FinishReason {
        match reason {
            Some("stop") | None => FinishReason::Stop,
            Some("length") => FinishReason::Length,
            Some("tool_calls") => FinishReason::ToolCalls,
            Some(other) => FinishReason::Error(other.to_string()),
        }
    }

    pub(super) fn build_response(
        content: Option<String>,
        tool_calls: Option<Vec<ToolCall>>,
        reasoning: Option<String>,
        reasoning_details: Option<Vec<String>>,
        model: String,
        finish_reason: Option<&str>,
        prompt_tokens: Option<u32>,
        completion_tokens: Option<u32>,
    ) -> LLMResponse {
        let mut finish = Self::finish_reason_from(finish_reason);
        if tool_calls.as_ref().is_some_and(|calls| !calls.is_empty()) {
            finish = FinishReason::ToolCalls;
        }

        LLMResponse {
            content,
            tool_calls,
            model,
            usage: Self::usage_from_counts(prompt_tokens, completion_tokens),
            finish_reason: finish,
            reasoning,
            reasoning_details,
            tool_references: Vec::new(),
            request_id: None,
            organization_id: None,
            compaction: None,
        }
    }

    /// Tagged private reasoning must never become public content when no final
    /// text remains. Apply the same boundary to both completed wire modes.
    pub(super) fn normalize_response_reasoning(response: &mut LLMResponse) {
        let Some(content) = response.content.take() else {
            return;
        };
        let (reasoning_parts, cleaned_content) = crate::utils::extract_reasoning_content(&content);
        if reasoning_parts.is_empty() {
            response.content = Some(content);
            return;
        }
        crate::providers::common::preserve_interleaved_content_in_reasoning_details(
            &mut response.reasoning_details,
            &content,
        );
        if response.reasoning.is_none() {
            response.reasoning = Some(reasoning_parts.join("\n\n"));
        }
        response.content = cleaned_content;
    }

    pub(super) fn response_from_chat_payload(
        model: String,
        parsed: OllamaChatResponse,
    ) -> Result<LLMResponse, LLMError> {
        if let Some(error) = parsed.error {
            return Err(LLMError::Provider { message: error, metadata: None });
        }

        let (content, reasoning, tool_calls, native_reasoning_details) = if let Some(message) = parsed.message {
            let content = message.content.and_then(|value| (!value.is_empty()).then_some(value));
            let reasoning = message.thinking.and_then(|value| (!value.is_empty()).then_some(value));
            let tool_calls = Self::convert_tool_calls(message.tool_calls)?;
            let native_reasoning_details = message.reasoning_details.filter(|d| !d.is_empty());
            (content, reasoning, tool_calls, native_reasoning_details)
        } else {
            (None, None, None, None)
        };

        let reasoning = reasoning.or_else(|| {
            native_reasoning_details
                .as_deref()
                .and_then(extract_reasoning_text_from_detail_values)
        });
        let reasoning_details = native_reasoning_details.as_deref().and_then(serialize_reasoning_detail_values);
        let mut response = Self::build_response(
            content,
            tool_calls,
            reasoning,
            reasoning_details,
            model,
            parsed.done_reason.as_deref(),
            parsed.prompt_eval_count,
            parsed.eval_count,
        );
        Self::normalize_response_reasoning(&mut response);
        Ok(response)
    }
}