use crate::error::{MojenticError, Result};
use crate::llm::gateway::{
CompletionConfig, LlmGateway, ModelContextWindow, StreamChunk, StreamMetrics, StreamProgress,
};
use crate::llm::gateways::ollama_stream_events::OllamaEventParser;
use crate::llm::models::{
LlmGatewayResponse, LlmMessage, LlmToolCall, MessageRole, ResponseEvidence,
};
use crate::llm::stream_events::{drive_event_stream, StreamEventError, StreamEventStream};
use crate::llm::stream_timing::{system_clock, StreamClock, StreamTiming};
use crate::llm::tools::LlmTool;
use async_trait::async_trait;
use futures::stream::{Stream, StreamExt};
use reqwest::Client;
use serde_json::Value;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use tracing::{debug, info, warn};
#[derive(Debug, Clone)]
pub struct OllamaConfig {
pub host: String,
pub timeout: Option<std::time::Duration>,
pub headers: HashMap<String, String>,
}
impl Default for OllamaConfig {
fn default() -> Self {
Self {
host: std::env::var("OLLAMA_HOST")
.unwrap_or_else(|_| "http://localhost:11434".to_string()),
timeout: None,
headers: HashMap::new(),
}
}
}
pub struct OllamaGateway {
clock: Arc<dyn StreamClock>,
client: Client,
config: OllamaConfig,
}
impl OllamaGateway {
pub fn with_stream_clock(mut self, clock: Arc<dyn StreamClock>) -> Self {
self.clock = clock;
self
}
pub fn with_recovery(
self,
policy: crate::llm::recovery::RecoveryPolicy,
) -> Result<crate::llm::recovery::RecoveryGateway<Self>> {
crate::llm::recovery::RecoveryGateway::new(self, policy)
}
pub fn new() -> Self {
Self::with_config(OllamaConfig::default())
}
pub fn with_config(config: OllamaConfig) -> Self {
let mut client_builder = Client::builder();
if let Some(timeout) = config.timeout {
client_builder = client_builder.timeout(timeout);
}
let client = client_builder.build().unwrap();
Self {
client,
config,
clock: system_clock(),
}
}
pub fn with_host(host: impl Into<String>) -> Self {
Self::with_config(OllamaConfig {
host: host.into(),
..Default::default()
})
}
fn chat_request(&self, body: &Value) -> reqwest::RequestBuilder {
self.client.post(format!("{}/api/chat", self.config.host)).json(body)
}
pub fn effective_context_window(
window: Option<&ModelContextWindow>,
config: &CompletionConfig,
) -> Option<usize> {
window.map(|window| {
let maximum = window.max_context_tokens.get();
maximum.min(config.num_ctx.or(window.model_num_ctx).unwrap_or(maximum))
})
}
pub async fn pull_model(&self, model: &str) -> Result<()> {
info!("Pulling Ollama model: {}", model);
let response = self
.client
.post(format!("{}/api/pull", self.config.host))
.json(&serde_json::json!({
"name": model
}))
.send()
.await?;
if !response.status().is_success() {
return Err(MojenticError::GatewayError(format!(
"Failed to pull model {}: {}",
model,
response.status()
)));
}
Ok(())
}
}
impl Default for OllamaGateway {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl LlmGateway for OllamaGateway {
fn stream_clock(&self) -> Arc<dyn StreamClock> {
self.clock.clone()
}
async fn get_model_context_window(&self, model: &str) -> Result<Option<ModelContextWindow>> {
let mut request = self
.client
.post(format!("{}/api/show", self.config.host.trim_end_matches('/')))
.json(&serde_json::json!({"model": model}));
for (key, value) in &self.config.headers {
request = request.header(key, value);
}
let response = request.send().await?;
if !response.status().is_success() {
return Err(MojenticError::GatewayError(format!(
"Failed to show model {model}: {}",
response.status()
)));
}
let body: Value = response.json().await?;
if !body.is_object() {
return Err(MojenticError::GatewayError("Invalid response format".into()));
}
let Some(info) = body.get("model_info") else {
return Ok(None);
};
let info = info
.as_object()
.ok_or_else(|| MojenticError::GatewayError("Invalid model_info".into()))?;
let Some((key, value)) = info.iter().find(|(key, _)| key.ends_with(".context_length"))
else {
return Ok(None);
};
let mut window = ModelContextWindow::advertised(value, format!("model_info.{key}"))?;
if let Some(parameters) = body.get("parameters") {
let parameters = parameters
.as_str()
.ok_or_else(|| MojenticError::GatewayError("Invalid parameters".into()))?;
window.model_num_ctx = parameters.lines().find_map(|line| {
let mut parts = line.split_whitespace();
(parts.next() == Some("num_ctx"))
.then(|| parts.next().and_then(|n| n.parse().ok()))
.flatten()
});
}
Ok(Some(window))
}
async fn complete(
&self,
model: &str,
messages: &[LlmMessage],
tools: Option<&[Box<dyn LlmTool>]>,
config: &CompletionConfig,
) -> Result<LlmGatewayResponse> {
info!("Delegating to Ollama for completion");
debug!("Model: {}, Message count: {}", model, messages.len());
let mut body = chat_body(model, messages, config, false)?;
if let Some(tools) = tools {
let tool_defs: Vec<_> = tools.iter().map(|t| t.descriptor()).collect();
body["tools"] = serde_json::to_value(tool_defs)?;
}
let response = self.chat_request(&body).send().await?;
if !response.status().is_success() {
return Err(MojenticError::GatewayError(format!(
"Ollama API error: {}",
response.status()
)));
}
let response_body: Value = response.json().await?;
let content = response_body["message"]["content"].as_str().map(String::from);
let thinking = response_body["message"]["thinking"].as_str().map(String::from);
let tool_calls = if let Some(calls) = response_body["message"]["tool_calls"].as_array() {
calls
.iter()
.filter_map(|call| {
let name = call["function"]["name"].as_str()?.to_string();
let args = call["function"]["arguments"].as_object()?;
let arguments: HashMap<String, Value> =
args.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
Some(LlmToolCall {
id: call["id"].as_str().map(String::from),
name,
arguments,
})
})
.collect()
} else {
vec![]
};
Ok(LlmGatewayResponse {
content,
object: None,
tool_calls,
thinking,
evidence: ollama_evidence(&response_body),
})
}
async fn complete_json(
&self,
model: &str,
messages: &[LlmMessage],
schema: Value,
config: &CompletionConfig,
) -> Result<Value> {
self.complete_json_response(model, messages, schema, config)
.await?
.object
.ok_or_else(|| MojenticError::GatewayError("No content in response".to_string()))
}
async fn complete_json_response(
&self,
model: &str,
messages: &[LlmMessage],
schema: Value,
config: &CompletionConfig,
) -> Result<LlmGatewayResponse<Value>> {
info!("Requesting structured output from Ollama");
let mut body = chat_body(model, messages, config, false)?;
body["format"] = schema;
let response = self.chat_request(&body).send().await?;
if !response.status().is_success() {
return Err(MojenticError::GatewayError(format!(
"Ollama API error: {}",
response.status()
)));
}
let response_body: Value = response.json().await?;
let content = response_body["message"]["content"]
.as_str()
.ok_or_else(|| MojenticError::GatewayError("No content in response".to_string()))?;
let object: Value = serde_json::from_str(content)?;
Ok(LlmGatewayResponse {
content: Some(content.to_string()),
object: Some(object),
thinking: response_body["message"]["thinking"].as_str().map(String::from),
evidence: ollama_evidence(&response_body),
..Default::default()
})
}
async fn get_available_models(&self) -> Result<Vec<String>> {
debug!("Fetching available Ollama models");
let response = self.client.get(format!("{}/api/tags", self.config.host)).send().await?;
if !response.status().is_success() {
return Err(MojenticError::GatewayError(format!(
"Failed to get models: {}",
response.status()
)));
}
let body: Value = response.json().await?;
let models = body["models"]
.as_array()
.ok_or_else(|| MojenticError::GatewayError("Invalid response format".to_string()))?
.iter()
.filter_map(|m| m["name"].as_str().map(String::from))
.collect::<Vec<_>>();
Ok(models)
}
async fn calculate_embeddings(&self, text: &str, model: Option<&str>) -> Result<Vec<f32>> {
let model = model.unwrap_or("mxbai-embed-large");
debug!("Calculating embeddings with model: {}", model);
let body = serde_json::json!({
"model": model,
"prompt": text
});
let response = self
.client
.post(format!("{}/api/embeddings", self.config.host))
.json(&body)
.send()
.await?;
if !response.status().is_success() {
return Err(MojenticError::GatewayError(format!(
"Embeddings API error: {}",
response.status()
)));
}
let response_body: Value = response.json().await?;
let embeddings = response_body["embedding"]
.as_array()
.ok_or_else(|| MojenticError::GatewayError("Invalid embeddings response".to_string()))?
.iter()
.filter_map(|v| v.as_f64().map(|f| f as f32))
.collect();
Ok(embeddings)
}
fn complete_stream<'a>(
&'a self,
model: &'a str,
messages: &'a [LlmMessage],
tools: Option<&'a [Box<dyn LlmTool>]>,
config: &'a CompletionConfig,
) -> Pin<Box<dyn Stream<Item = Result<StreamChunk>> + Send + 'a>> {
let timing = StreamTiming::new(self.stream_clock());
let measure = timing.clone();
let source: Pin<Box<dyn Stream<Item = Result<StreamChunk>> + Send + 'a>> = Box::pin(
async_stream::stream! {
info!("Starting Ollama streaming completion");
debug!("Model: {}, Message count: {}", model, messages.len());
let mut body = match chat_body(model, messages, config, true) {
Ok(body) => body,
Err(e) => {
yield Err(e);
return;
}
};
if let Some(tools) = tools {
let tool_defs: Vec<_> = tools.iter().map(|t| t.descriptor()).collect();
if let Ok(tools_value) = serde_json::to_value(tool_defs) {
body["tools"] = tools_value;
}
}
measure.dispatch();
let response = match self.chat_request(&body).send().await {
Ok(r) => r,
Err(e) => {
yield Err(e.into());
return;
}
};
if !response.status().is_success() {
yield Err(MojenticError::GatewayError(format!(
"Ollama API error: {}",
response.status()
)));
return;
}
let mut stream = response.bytes_stream();
let mut buffer = String::new();
let mut accumulated_tool_calls: Vec<LlmToolCall> = Vec::new();
let mut frame_index = 0usize;
while let Some(chunk_result) = stream.next().await {
match chunk_result {
Ok(bytes) => {
if let Ok(text) = std::str::from_utf8(&bytes) {
buffer.push_str(text);
while let Some(newline_pos) = buffer.find('\n') {
let line = buffer[..newline_pos].trim().to_string();
buffer = buffer[newline_pos + 1..].to_string();
if line.is_empty() {
continue;
}
match serde_json::from_str::<Value>(&line) {
Ok(json) => {
measure.observe_line(&line);
frame_index += 1;
let done = json["done"].as_bool().unwrap_or(false);
let (content_chars, thinking_chars, tool_call_count) =
frame_progress_counts(&json);
yield Ok(StreamChunk::Progress(StreamProgress {
provider: "ollama".to_string(),
frame_index,
done,
content_chars,
thinking_chars,
tool_call_count,
accumulated_tool_call_count: accumulated_tool_calls.len(),
}));
if done {
yield Ok(StreamChunk::Metrics(ollama_stream_metrics(&json)));
if !accumulated_tool_calls.is_empty() {
yield Ok(StreamChunk::ToolCalls(accumulated_tool_calls.clone()));
}
continue;
}
if let Some(message) = json["message"].as_object() {
if let Some(thinking) =
message.get("thinking").and_then(|v| v.as_str())
{
if !thinking.is_empty() {
yield Ok(StreamChunk::Thinking(thinking.to_string()));
}
}
if let Some(content) =
message.get("content").and_then(|v| v.as_str())
{
if !content.is_empty() {
yield Ok(StreamChunk::Content(content.to_string()));
}
}
if let Some(calls) = message.get("tool_calls").and_then(|v| v.as_array()) {
for call in calls {
if let Some(function) = call.get("function").and_then(|v| v.as_object()) {
if let (Some(name), Some(args)) = (
function.get("name").and_then(|v| v.as_str()),
function.get("arguments").and_then(|v| v.as_object()),
) {
let arguments: HashMap<String, Value> = args
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let tool_call = LlmToolCall {
id: call.get("id").and_then(|v| v.as_str()).map(String::from),
name: name.to_string(),
arguments,
};
accumulated_tool_calls.push(tool_call);
}
}
}
}
}
}
Err(e) => {
warn!("Failed to parse streaming chunk: {}", e);
}
}
}
}
}
Err(e) => {
yield Err(e.into());
return;
}
}
}
},
);
timing.legacy(source, "ollama")
}
fn complete_stream_events<'a>(
&'a self,
model: &'a str,
messages: &'a [LlmMessage],
config: &'a CompletionConfig,
) -> std::result::Result<StreamEventStream<'a>, StreamEventError> {
info!("Starting Ollama stream events");
let body =
chat_body(model, messages, config, true).map_err(StreamEventError::RequestFailed)?;
Ok(drive_event_stream(
self.chat_request(&body),
OllamaEventParser::default(),
self.stream_clock(),
"ollama",
))
}
}
const OLLAMA_USAGE_FIELDS: [&str; 2] = ["prompt_eval_count", "eval_count"];
const OLLAMA_METADATA_FIELDS: [&str; 5] = [
"created_at",
"total_duration",
"load_duration",
"prompt_eval_duration",
"eval_duration",
];
pub(crate) fn ollama_evidence(frame: &Value) -> ResponseEvidence {
let usage = reported_fields(frame, &OLLAMA_USAGE_FIELDS);
ResponseEvidence {
usage: (!usage.is_empty()).then(|| Value::Object(usage.into_iter().collect())),
provider_model: frame["model"].as_str().map(String::from),
finish_reason: frame["done_reason"].as_str().map(String::from),
metadata: reported_fields(frame, &OLLAMA_METADATA_FIELDS),
}
}
fn reported_fields(frame: &Value, fields: &[&str]) -> HashMap<String, Value> {
fields
.iter()
.filter_map(|field| {
let value = &frame[*field];
(!value.is_null()).then(|| (field.to_string(), value.clone()))
})
.collect()
}
pub(crate) fn frame_progress_counts(json: &Value) -> (usize, usize, usize) {
let Some(message) = json["message"].as_object() else {
return (0, 0, 0);
};
let content_chars = message
.get("content")
.and_then(|value| value.as_str())
.map(str::len)
.unwrap_or_default();
let thinking_chars = message
.get("thinking")
.and_then(|value| value.as_str())
.map(str::len)
.unwrap_or_default();
let tool_call_count = message
.get("tool_calls")
.and_then(|value| value.as_array())
.map(Vec::len)
.unwrap_or_default();
(content_chars, thinking_chars, tool_call_count)
}
pub(crate) fn ollama_stream_metrics(json: &Value) -> StreamMetrics {
let eval_count = json["eval_count"].as_u64();
let eval_duration_ns = json["eval_duration"].as_u64();
StreamMetrics {
provider: "ollama".to_string(),
total_duration_ns: json["total_duration"].as_u64(),
load_duration_ns: json["load_duration"].as_u64(),
prompt_eval_count: json["prompt_eval_count"].as_u64(),
prompt_eval_duration_ns: json["prompt_eval_duration"].as_u64(),
eval_count,
eval_duration_ns,
tokens_per_second: tokens_per_second(eval_count, eval_duration_ns),
..Default::default()
}
}
fn tokens_per_second(eval_count: Option<u64>, eval_duration_ns: Option<u64>) -> Option<f64> {
let tokens = eval_count?;
let duration = eval_duration_ns?;
if duration == 0 {
return None;
}
Some(tokens as f64 / (duration as f64 / 1_000_000_000.0))
}
fn adapt_messages_to_ollama(messages: &[LlmMessage]) -> Result<Vec<Value>> {
messages
.iter()
.map(|msg| {
let mut ollama_msg = serde_json::json!({
"role": match msg.role {
MessageRole::System => "system",
MessageRole::User => "user",
MessageRole::Assistant => "assistant",
MessageRole::Tool => "tool",
},
"content": msg.content.as_deref().unwrap_or("")
});
if msg.role == MessageRole::Assistant {
if let Some(reasoning) = &msg.reasoning_content {
ollama_msg["thinking"] = serde_json::json!(reasoning);
}
}
if let Some(image_paths) = &msg.image_paths {
let encoded_images: Result<Vec<String>> = image_paths
.iter()
.map(|path| {
std::fs::read(path)
.map_err(|e| {
MojenticError::GatewayError(format!(
"Failed to read image file {}: {}",
path, e
))
})
.map(|bytes| {
base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
bytes,
)
})
})
.collect();
ollama_msg["images"] = serde_json::to_value(encoded_images?)?;
}
if let Some(tool_calls) = &msg.tool_calls {
let calls: Vec<_> = tool_calls
.iter()
.map(|tc| {
serde_json::json!({
"type": "function",
"function": {
"name": tc.name,
"arguments": tc.arguments
}
})
})
.collect();
ollama_msg["tool_calls"] = serde_json::to_value(calls)?;
}
Ok(ollama_msg)
})
.collect()
}
fn chat_body(
model: &str,
messages: &[LlmMessage],
config: &CompletionConfig,
stream: bool,
) -> Result<Value> {
config.validate_reasoning()?;
let mut body = serde_json::json!({
"model": model,
"messages": adapt_messages_to_ollama(messages)?,
"options": extract_ollama_options(config),
"stream": stream
});
if let Some(effort) = config.reasoning_effort {
use crate::llm::gateway::ReasoningEffort;
body["think"] = match effort {
ReasoningEffort::Disabled => Value::Bool(false),
ReasoningEffort::Enabled => Value::Bool(true),
named => serde_json::to_value(named)?,
};
}
add_response_format(&mut body, config);
Ok(body)
}
fn extract_ollama_options(config: &CompletionConfig) -> Value {
let mut options = serde_json::json!({});
if let Some(temperature) = config.temperature {
options["temperature"] = serde_json::json!(temperature);
}
if let Some(num_ctx) = config.num_ctx {
options["num_ctx"] = serde_json::json!(num_ctx);
}
if let Some(max_tokens) = config.max_tokens {
options["num_predict"] = serde_json::json!(max_tokens);
}
if let Some(top_p) = config.top_p {
options["top_p"] = serde_json::json!(top_p);
}
if let Some(top_k) = config.top_k {
options["top_k"] = serde_json::json!(top_k);
}
options
}
fn add_response_format(body: &mut Value, config: &CompletionConfig) {
use crate::llm::gateway::ResponseFormat;
if let Some(response_format) = &config.response_format {
match response_format {
ResponseFormat::JsonObject { schema: Some(s) } => {
body["format"] = s.clone();
}
ResponseFormat::JsonObject { schema: None } => {
body["format"] = serde_json::json!("json");
}
ResponseFormat::Text => {
}
}
}
}
impl crate::llm::recovery::RecoveryProvider for OllamaGateway {
fn recovery_provider(&self) -> crate::llm::recovery::Provider {
crate::llm::recovery::Provider::Ollama
}
fn prepare_recovery(
&self,
model: &str,
messages: &[LlmMessage],
tools: Option<&[Box<dyn LlmTool>]>,
config: &CompletionConfig,
schema: Option<Value>,
stream: bool,
) -> Result<reqwest::Request> {
let mut body = chat_body(model, messages, config, stream)?;
if let Some(schema) = schema {
body["format"] = schema;
}
if let Some(tools) = tools {
body["tools"] =
serde_json::to_value(tools.iter().map(|t| t.descriptor()).collect::<Vec<_>>())?;
}
let mut request = self.chat_request(&body).build()?;
*request.timeout_mut() = None;
Ok(request)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
static ENV_MUTEX: Mutex<()> = Mutex::new(());
#[test]
fn test_ollama_config_default() {
let _guard = ENV_MUTEX.lock().unwrap();
std::env::remove_var("OLLAMA_HOST");
let config = OllamaConfig::default();
assert_eq!(config.host, "http://localhost:11434");
assert!(config.timeout.is_none());
assert!(config.headers.is_empty());
}
#[test]
fn test_ollama_config_from_env() {
let _guard = ENV_MUTEX.lock().unwrap();
std::env::set_var("OLLAMA_HOST", "http://custom:8080");
let config = OllamaConfig::default();
assert_eq!(config.host, "http://custom:8080");
std::env::remove_var("OLLAMA_HOST");
}
#[test]
fn test_ollama_config_custom() {
let mut headers = HashMap::new();
headers.insert("X-Custom".to_string(), "value".to_string());
let config = OllamaConfig {
host: "http://test:9999".to_string(),
timeout: Some(std::time::Duration::from_secs(30)),
headers,
};
assert_eq!(config.host, "http://test:9999");
assert_eq!(config.timeout, Some(std::time::Duration::from_secs(30)));
assert_eq!(config.headers.get("X-Custom"), Some(&"value".to_string()));
}
#[test]
fn test_gateway_new() {
let gateway = OllamaGateway::new();
assert_eq!(gateway.config.host, "http://localhost:11434");
}
#[test]
fn test_gateway_with_host() {
let gateway = OllamaGateway::with_host("http://example.com:8080");
assert_eq!(gateway.config.host, "http://example.com:8080");
}
#[test]
fn test_gateway_with_config() {
let config = OllamaConfig {
host: "http://custom:5000".to_string(),
timeout: Some(std::time::Duration::from_secs(60)),
headers: HashMap::new(),
};
let gateway = OllamaGateway::with_config(config);
assert_eq!(gateway.config.host, "http://custom:5000");
}
#[test]
fn test_gateway_default() {
let gateway = OllamaGateway::default();
assert_eq!(gateway.config.host, "http://localhost:11434");
}
#[test]
fn test_adapt_messages_to_ollama_simple() {
let messages = vec![
LlmMessage::system("You are helpful"),
LlmMessage::user("Hello"),
LlmMessage::assistant("Hi there"),
];
let result = adapt_messages_to_ollama(&messages).unwrap();
assert_eq!(result.len(), 3);
assert_eq!(result[0]["role"], "system");
assert_eq!(result[0]["content"], "You are helpful");
assert_eq!(result[1]["role"], "user");
assert_eq!(result[1]["content"], "Hello");
assert_eq!(result[2]["role"], "assistant");
assert_eq!(result[2]["content"], "Hi there");
}
#[test]
fn test_adapt_messages_with_images() {
use std::io::Write;
use tempfile::NamedTempFile;
let mut temp_file1 = NamedTempFile::new().unwrap();
let mut temp_file2 = NamedTempFile::new().unwrap();
temp_file1.write_all(b"fake_image_data_1").unwrap();
temp_file2.write_all(b"fake_image_data_2").unwrap();
let path1 = temp_file1.path().to_string_lossy().to_string();
let path2 = temp_file2.path().to_string_lossy().to_string();
let expected_base64_1 = base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
b"fake_image_data_1",
);
let expected_base64_2 = base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
b"fake_image_data_2",
);
let messages = vec![LlmMessage::user("Describe this").with_images(vec![path1, path2])];
let result = adapt_messages_to_ollama(&messages).unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0]["role"], "user");
assert_eq!(result[0]["images"][0], expected_base64_1);
assert_eq!(result[0]["images"][1], expected_base64_2);
}
#[test]
fn test_adapt_messages_with_tool_calls() {
let tool_call = LlmToolCall {
id: Some("call_123".to_string()),
name: "test_function".to_string(),
arguments: {
let mut map = HashMap::new();
map.insert("arg1".to_string(), serde_json::json!("value1"));
map
},
};
let messages = vec![LlmMessage {
role: MessageRole::Assistant,
content: None,
tool_calls: Some(vec![tool_call]),
image_paths: None,
reasoning_content: None,
}];
let result = adapt_messages_to_ollama(&messages).unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0]["role"], "assistant");
assert_eq!(result[0]["tool_calls"][0]["type"], "function");
assert_eq!(result[0]["tool_calls"][0]["function"]["name"], "test_function");
}
#[test]
fn test_adapt_messages_empty_content() {
let messages = vec![LlmMessage {
role: MessageRole::User,
content: None,
tool_calls: None,
image_paths: None,
reasoning_content: None,
}];
let result = adapt_messages_to_ollama(&messages).unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0]["content"], "");
}
#[test]
fn test_adapt_messages_tool_role() {
let messages = vec![LlmMessage {
role: MessageRole::Tool,
content: Some("Tool result".to_string()),
tool_calls: None,
image_paths: None,
reasoning_content: None,
}];
let result = adapt_messages_to_ollama(&messages).unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0]["role"], "tool");
assert_eq!(result[0]["content"], "Tool result");
}
#[test]
fn test_extract_ollama_options_basic() {
let config = CompletionConfig {
temperature: Some(0.7),
num_ctx: Some(4096),
max_tokens: Some(2048),
top_p: None,
top_k: None,
response_format: None,
reasoning_effort: None,
reasoning_profile: None,
preserve_reasoning: false,
max_tool_iterations: 10,
};
let options = extract_ollama_options(&config);
assert!((options["temperature"].as_f64().unwrap() - 0.7).abs() < 0.01);
assert_eq!(options["num_ctx"], 4096);
assert_eq!(options["num_predict"], 2048);
}
#[test]
fn test_extract_ollama_options_output_limit() {
let config = CompletionConfig {
temperature: Some(0.5),
num_ctx: Some(2048),
max_tokens: Some(1000),
top_p: None,
top_k: None,
response_format: None,
reasoning_effort: None,
reasoning_profile: None,
preserve_reasoning: false,
max_tool_iterations: 10,
};
let options = extract_ollama_options(&config);
assert!((options["temperature"].as_f64().unwrap() - 0.5).abs() < 0.01);
assert_eq!(options["num_ctx"], 2048);
assert_eq!(options["num_predict"], 1000);
}
#[test]
fn test_extract_ollama_options_unset_output_limit() {
let config = CompletionConfig {
temperature: Some(1.0),
num_ctx: Some(8192),
max_tokens: None,
top_p: None,
top_k: None,
response_format: None,
reasoning_effort: None,
reasoning_profile: None,
preserve_reasoning: false,
max_tool_iterations: 10,
};
let options = extract_ollama_options(&config);
assert!((options["temperature"].as_f64().unwrap() - 1.0).abs() < 0.01);
assert_eq!(options["num_ctx"], 8192);
assert!(options.get("num_predict").is_none());
}
#[test]
fn test_extract_ollama_options_zero_max_tokens() {
let config = CompletionConfig {
temperature: Some(0.8),
num_ctx: Some(1024),
max_tokens: Some(0),
top_p: None,
top_k: None,
response_format: None,
reasoning_effort: None,
reasoning_profile: None,
preserve_reasoning: false,
max_tool_iterations: 10,
};
let options = extract_ollama_options(&config);
assert!((options["temperature"].as_f64().unwrap() - 0.8).abs() < 0.01);
assert_eq!(options["num_ctx"], 1024);
assert_eq!(options["num_predict"], 0);
}
#[test]
fn test_extract_ollama_options_with_top_p() {
let config = CompletionConfig {
temperature: Some(0.7),
num_ctx: Some(4096),
max_tokens: Some(2048),
top_p: Some(0.9),
top_k: None,
response_format: None,
reasoning_effort: None,
reasoning_profile: None,
preserve_reasoning: false,
max_tool_iterations: 10,
};
let options = extract_ollama_options(&config);
assert!((options["temperature"].as_f64().unwrap() - 0.7).abs() < 0.01);
assert_eq!(options["num_ctx"], 4096);
assert!((options["top_p"].as_f64().unwrap() - 0.9).abs() < 0.01);
assert!(options.get("top_k").is_none());
}
#[test]
fn test_extract_ollama_options_with_top_k() {
let config = CompletionConfig {
temperature: Some(0.8),
num_ctx: Some(2048),
max_tokens: Some(1024),
top_p: None,
top_k: Some(40),
response_format: None,
reasoning_effort: None,
reasoning_profile: None,
preserve_reasoning: false,
max_tool_iterations: 10,
};
let options = extract_ollama_options(&config);
assert!((options["temperature"].as_f64().unwrap() - 0.8).abs() < 0.01);
assert_eq!(options["top_k"], 40);
assert!(options.get("top_p").is_none());
}
#[test]
fn test_extract_ollama_options_with_all_sampling_params() {
let config = CompletionConfig {
temperature: Some(0.6),
num_ctx: Some(8192),
max_tokens: Some(4096),
top_p: Some(0.95),
top_k: Some(50),
response_format: None,
reasoning_effort: None,
reasoning_profile: None,
preserve_reasoning: false,
max_tool_iterations: 10,
};
let options = extract_ollama_options(&config);
assert!((options["temperature"].as_f64().unwrap() - 0.6).abs() < 0.01);
assert_eq!(options["num_ctx"], 8192);
assert_eq!(options["num_predict"], 4096);
assert!((options["top_p"].as_f64().unwrap() - 0.95).abs() < 0.01);
assert_eq!(options["top_k"], 50);
}
#[test]
fn test_add_response_format_text() {
use crate::llm::gateway::ResponseFormat;
let config = CompletionConfig {
temperature: Some(0.7),
num_ctx: Some(4096),
max_tokens: Some(2048),
top_p: None,
top_k: None,
response_format: Some(ResponseFormat::Text),
reasoning_effort: None,
reasoning_profile: None,
preserve_reasoning: false,
max_tool_iterations: 10,
};
let mut body = serde_json::json!({
"model": "test",
"messages": []
});
add_response_format(&mut body, &config);
assert!(body.get("format").is_none());
}
#[test]
fn test_add_response_format_json_no_schema() {
use crate::llm::gateway::ResponseFormat;
let config = CompletionConfig {
temperature: Some(0.7),
num_ctx: Some(4096),
max_tokens: Some(2048),
top_p: None,
top_k: None,
response_format: Some(ResponseFormat::JsonObject { schema: None }),
reasoning_effort: None,
reasoning_profile: None,
preserve_reasoning: false,
max_tool_iterations: 10,
};
let mut body = serde_json::json!({
"model": "test",
"messages": []
});
add_response_format(&mut body, &config);
assert_eq!(body["format"], "json");
}
#[test]
fn test_add_response_format_json_with_schema() {
use crate::llm::gateway::ResponseFormat;
let schema = serde_json::json!({
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"}
}
});
let config = CompletionConfig {
temperature: Some(0.7),
num_ctx: Some(4096),
max_tokens: Some(2048),
top_p: None,
top_k: None,
response_format: Some(ResponseFormat::JsonObject {
schema: Some(schema.clone()),
}),
reasoning_effort: None,
reasoning_profile: None,
preserve_reasoning: false,
max_tool_iterations: 10,
};
let mut body = serde_json::json!({
"model": "test",
"messages": []
});
add_response_format(&mut body, &config);
assert_eq!(body["format"], schema);
}
#[test]
fn test_add_response_format_none() {
let config = CompletionConfig {
temperature: Some(0.7),
num_ctx: Some(4096),
max_tokens: Some(2048),
top_p: None,
top_k: None,
response_format: None,
reasoning_effort: None,
reasoning_profile: None,
preserve_reasoning: false,
max_tool_iterations: 10,
};
let mut body = serde_json::json!({
"model": "test",
"messages": []
});
add_response_format(&mut body, &config);
assert!(body.get("format").is_none());
}
async fn streamed_request_body(config: CompletionConfig) -> Value {
let captured = std::sync::Arc::new(Mutex::new(None::<Value>));
let sink = captured.clone();
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/chat")
.match_request(move |request| {
let body = serde_json::from_slice(request.body().expect("request body"))
.expect("JSON request body");
*sink.lock().unwrap() = Some(body);
true
})
.with_status(200)
.with_body("{\"done\":true,\"done_reason\":\"stop\"}\n")
.create_async()
.await;
let gateway = OllamaGateway::with_host(server.url());
let messages = vec![LlmMessage::user("Hi")];
let mut stream = gateway.complete_stream("qwen3:32b", &messages, None, &config);
while stream.next().await.is_some() {}
mock.assert_async().await;
let body = captured.lock().unwrap().take();
body.expect("streaming request body was captured")
}
fn config_with_format(format: Option<crate::llm::gateway::ResponseFormat>) -> CompletionConfig {
CompletionConfig {
response_format: format,
..Default::default()
}
}
#[tokio::test]
async fn streaming_request_without_format_leaves_body_unchanged() {
let body = streamed_request_body(config_with_format(None)).await;
assert_eq!(body["stream"], true);
assert!(body.get("format").is_none());
}
#[tokio::test]
async fn streaming_request_omits_format_for_text() {
use crate::llm::gateway::ResponseFormat;
let body = streamed_request_body(config_with_format(Some(ResponseFormat::Text))).await;
assert!(body.get("format").is_none());
}
#[tokio::test]
async fn streaming_request_forwards_json_object_format() {
use crate::llm::gateway::ResponseFormat;
let body = streamed_request_body(config_with_format(Some(ResponseFormat::JsonObject {
schema: None,
})))
.await;
assert_eq!(body["format"], "json");
}
#[tokio::test]
async fn streaming_request_forwards_json_schema_format() {
use crate::llm::gateway::ResponseFormat;
let schema =
serde_json::json!({"type": "object", "properties": {"n": {"type": "integer"}}});
let body = streamed_request_body(config_with_format(Some(ResponseFormat::JsonObject {
schema: Some(schema.clone()),
})))
.await;
assert_eq!(body["format"], schema);
}
#[tokio::test]
async fn complete_carries_reported_evidence_unchanged() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/chat")
.with_status(200)
.with_body(
r#"{"model":"qwen3:32b","created_at":"2026-09-24T10:00:00Z",
"message":{"role":"assistant","content":"Hi"},
"done":true,"done_reason":"length",
"total_duration":900,"load_duration":100,
"prompt_eval_count":12,"prompt_eval_duration":200,
"eval_count":34,"eval_duration":600}"#,
)
.create_async()
.await;
let gateway = OllamaGateway::with_host(server.url());
let messages = vec![LlmMessage::user("Hi")];
let response = gateway
.complete("qwen3", &messages, None, &CompletionConfig::default())
.await
.unwrap();
mock.assert_async().await;
let evidence = response.evidence;
assert_eq!(evidence.provider_model.as_deref(), Some("qwen3:32b"));
assert_eq!(evidence.finish_reason.as_deref(), Some("length"));
assert_eq!(
evidence.usage,
Some(serde_json::json!({"prompt_eval_count": 12, "eval_count": 34}))
);
assert_eq!(evidence.metadata["total_duration"], 900);
assert_eq!(evidence.metadata["load_duration"], 100);
assert_eq!(evidence.metadata["prompt_eval_duration"], 200);
assert_eq!(evidence.metadata["eval_duration"], 600);
assert_eq!(evidence.metadata["created_at"], "2026-09-24T10:00:00Z");
}
#[tokio::test]
async fn complete_leaves_unreported_usage_unknown() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/chat")
.with_status(200)
.with_body(r#"{"message":{"role":"assistant","content":"Hi"},"done":true}"#)
.create_async()
.await;
let gateway = OllamaGateway::with_host(server.url());
let messages = vec![LlmMessage::user("Hi")];
let response = gateway
.complete("qwen3", &messages, None, &CompletionConfig::default())
.await
.unwrap();
mock.assert_async().await;
assert_eq!(response.evidence, crate::llm::models::ResponseEvidence::default());
}
#[tokio::test]
async fn complete_json_response_carries_object_and_evidence() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/chat")
.with_status(200)
.with_body(
r#"{"model":"qwen3:32b","message":{"role":"assistant","content":"{\"n\":1}"},
"done":true,"done_reason":"stop","prompt_eval_count":3,"eval_count":4}"#,
)
.create_async()
.await;
let gateway = OllamaGateway::with_host(server.url());
let messages = vec![LlmMessage::user("JSON")];
let response = gateway
.complete_json_response(
"qwen3",
&messages,
serde_json::json!({"type": "object"}),
&CompletionConfig::default(),
)
.await
.unwrap();
mock.assert_async().await;
assert_eq!(response.object, Some(serde_json::json!({"n": 1})));
assert_eq!(response.evidence.finish_reason.as_deref(), Some("stop"));
assert_eq!(
response.evidence.usage,
Some(serde_json::json!({"prompt_eval_count": 3, "eval_count": 4}))
);
}
mod stream_events {
use super::*;
use crate::llm::stream_events::testing::endless_stream_server;
use crate::llm::{StreamEvent, StreamEventError};
async fn collect_events(
server: &mockito::Server,
config: &CompletionConfig,
) -> Vec<StreamEvent> {
let gateway = OllamaGateway::with_host(server.url());
let messages = vec![LlmMessage::user("Hi")];
let stream = gateway
.complete_stream_events("qwen3:32b", &messages, config)
.expect("Ollama supports stream events");
let events: Vec<_> = stream.collect().await;
let metrics: Vec<_> = events
.iter()
.filter_map(|e| {
if let StreamEvent::Metrics(m) = e {
Some(m)
} else {
None
}
})
.collect();
assert_eq!(metrics.len(), 1);
assert!(metrics[0].request_duration_ms.is_some());
events
.into_iter()
.filter(|event| !matches!(event, StreamEvent::Metrics(_)))
.collect()
}
#[tokio::test]
async fn request_streams_without_tools_and_honours_config() {
use crate::llm::gateway::{ReasoningEffort, ResponseFormat};
let captured = std::sync::Arc::new(Mutex::new(None::<Value>));
let sink = captured.clone();
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/chat")
.match_request(move |request| {
*sink.lock().unwrap() =
serde_json::from_slice(request.body().expect("request body")).ok();
true
})
.with_status(200)
.with_body("{\"done\":true,\"done_reason\":\"stop\"}\n")
.create_async()
.await;
let config = CompletionConfig {
reasoning_effort: Some(ReasoningEffort::Disabled),
response_format: Some(ResponseFormat::JsonObject { schema: None }),
..Default::default()
};
collect_events(&server, &config).await;
mock.assert_async().await;
let body = captured.lock().unwrap().take().expect("captured body");
assert_eq!(body["model"], "qwen3:32b");
assert_eq!(body["stream"], true);
assert_eq!(body["think"], false);
assert_eq!(body["format"], "json");
assert!(body.get("tools").is_none());
}
#[tokio::test]
async fn completes_over_http_with_durations() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/chat")
.with_status(200)
.with_body(concat!(
"{\"message\":{\"content\":\"Hi\"},\"done\":false}\n",
"{\"model\":\"qwen3:32b\",\"done\":true,\"done_reason\":\"stop\",",
"\"total_duration\":900,\"eval_count\":2}\n",
))
.create_async()
.await;
let events = collect_events(&server, &CompletionConfig::default()).await;
mock.assert_async().await;
assert!(matches!(
events.as_slice(),
[StreamEvent::Content(text), StreamEvent::Completed(evidence)]
if text == "Hi"
&& evidence.metadata["total_duration"] == 900
&& evidence.usage == Some(serde_json::json!({"eval_count": 2}))
));
}
#[tokio::test]
async fn end_of_stream_without_done_is_incomplete_stream() {
let mut server = mockito::Server::new_async().await;
let _mock = server
.mock("POST", "/api/chat")
.with_status(200)
.with_body("{\"message\":{\"content\":\"Hi\"},\"done\":false}\n")
.create_async()
.await;
let events = collect_events(&server, &CompletionConfig::default()).await;
assert!(matches!(
events.as_slice(),
[
StreamEvent::Content(_),
StreamEvent::Error(StreamEventError::IncompleteStream(_))
]
));
}
#[tokio::test]
async fn http_error_status_is_reported_with_body() {
let mut server = mockito::Server::new_async().await;
let _mock = server
.mock("POST", "/api/chat")
.with_status(404)
.with_body(r#"{"error":"model 'qwen3:32b' not found"}"#)
.create_async()
.await;
let events = collect_events(&server, &CompletionConfig::default()).await;
assert!(matches!(
events.as_slice(),
[StreamEvent::Error(StreamEventError::ProviderError { status: Some(404), error })]
if error == "model 'qwen3:32b' not found"
));
}
#[tokio::test]
async fn dropping_the_stream_cancels_the_request() {
let (url, closed) =
endless_stream_server("{\"message\":{\"content\":\"Hi\"},\"done\":false}\n").await;
let gateway = OllamaGateway::with_host(url);
let messages = vec![LlmMessage::user("Hi")];
let config = CompletionConfig::default();
let mut stream = gateway
.complete_stream_events("qwen3:32b", &messages, &config)
.expect("supported");
assert!(matches!(stream.next().await, Some(StreamEvent::Content(_))));
drop(stream);
tokio::time::timeout(std::time::Duration::from_secs(5), closed)
.await
.expect("the request was not cancelled")
.expect("server reported the disconnect");
}
}
#[tokio::test]
async fn test_pull_model_success() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/pull")
.with_status(200)
.with_body(r#"{"status":"success"}"#)
.create();
let gateway = OllamaGateway::with_host(server.url());
let result = gateway.pull_model("llama2").await;
mock.assert();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_pull_model_failure() {
let mut server = mockito::Server::new_async().await;
let mock = server.mock("POST", "/api/pull").with_status(404).create();
let gateway = OllamaGateway::with_host(server.url());
let result = gateway.pull_model("nonexistent").await;
mock.assert();
assert!(result.is_err());
}
#[tokio::test]
async fn test_complete_simple() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/chat")
.with_status(200)
.with_body(r#"{"message":{"role":"assistant","content":"Hello!"}}"#)
.create();
let gateway = OllamaGateway::with_host(server.url());
let messages = vec![LlmMessage::user("Hi")];
let config = CompletionConfig::default();
let result = gateway.complete("llama2", &messages, None, &config).await;
mock.assert();
assert!(result.is_ok());
let response = result.unwrap();
assert_eq!(response.content, Some("Hello!".to_string()));
assert_eq!(response.thinking, None);
}
#[tokio::test]
async fn test_complete_with_tools() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/chat")
.match_body(mockito::Matcher::JsonString(
r#"{"model":"llama2","messages":[{"role":"user","content":"Hi"}],"options":{},"stream":false,"tools":[{"type":"function","function":{"name":"test_tool","description":"A test","parameters":{}}}]}"#.to_string()
))
.with_status(200)
.with_body(r#"{"message":{"role":"assistant","content":"Result"}}"#)
.create();
let gateway = OllamaGateway::with_host(server.url());
let messages = vec![LlmMessage::user("Hi")];
let config = CompletionConfig::default();
use crate::llm::tools::{FunctionDescriptor, LlmTool, ToolDescriptor};
#[derive(Clone)]
struct MockTool;
#[async_trait]
impl LlmTool for MockTool {
async fn run(
&self,
_args: &HashMap<String, Value>,
_ctx: &crate::llm::tools::ToolRunCtx,
) -> Result<Value> {
Ok(serde_json::json!({}))
}
fn descriptor(&self) -> ToolDescriptor {
ToolDescriptor {
r#type: "function".to_string(),
function: FunctionDescriptor {
name: "test_tool".to_string(),
description: "A test".to_string(),
parameters: serde_json::json!({}),
},
}
}
fn clone_box(&self) -> Box<dyn LlmTool> {
Box::new(self.clone())
}
}
let tools: Vec<Box<dyn LlmTool>> = vec![Box::new(MockTool)];
let result = gateway.complete("llama2", &messages, Some(&tools), &config).await;
mock.assert();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_complete_error() {
let mut server = mockito::Server::new_async().await;
let mock = server.mock("POST", "/api/chat").with_status(500).create();
let gateway = OllamaGateway::with_host(server.url());
let messages = vec![LlmMessage::user("Hi")];
let config = CompletionConfig::default();
let result = gateway.complete("llama2", &messages, None, &config).await;
mock.assert();
assert!(result.is_err());
}
#[tokio::test]
async fn test_complete_json() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/chat")
.with_status(200)
.with_body(r#"{"message":{"content":"{\"name\":\"test\",\"value\":42}"}}"#)
.create();
let gateway = OllamaGateway::with_host(server.url());
let messages = vec![LlmMessage::user("Generate JSON")];
let schema = serde_json::json!({"type": "object"});
let config = CompletionConfig::default();
let result = gateway.complete_json("llama2", &messages, schema, &config).await;
mock.assert();
assert!(result.is_ok());
let json = result.unwrap();
assert_eq!(json["name"], "test");
assert_eq!(json["value"], 42);
}
#[tokio::test]
async fn test_get_available_models() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("GET", "/api/tags")
.with_status(200)
.with_body(r#"{"models":[{"name":"llama2"},{"name":"mistral"}]}"#)
.create();
let gateway = OllamaGateway::with_host(server.url());
let result = gateway.get_available_models().await;
mock.assert();
assert!(result.is_ok());
let models = result.unwrap();
assert_eq!(models.len(), 2);
assert!(models.contains(&"llama2".to_string()));
assert!(models.contains(&"mistral".to_string()));
}
#[tokio::test]
async fn test_calculate_embeddings() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/embeddings")
.with_status(200)
.with_body(r#"{"embedding":[0.1,0.2,0.3,0.4]}"#)
.create();
let gateway = OllamaGateway::with_host(server.url());
let result = gateway.calculate_embeddings("test text", None).await;
mock.assert();
assert!(result.is_ok());
let embeddings = result.unwrap();
assert_eq!(embeddings.len(), 4);
assert_eq!(embeddings[0], 0.1);
assert_eq!(embeddings[3], 0.4);
}
#[tokio::test]
async fn test_calculate_embeddings_custom_model() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/embeddings")
.match_body(mockito::Matcher::JsonString(
r#"{"model":"custom-embed","prompt":"test"}"#.to_string(),
))
.with_status(200)
.with_body(r#"{"embedding":[0.5,0.6]}"#)
.create();
let gateway = OllamaGateway::with_host(server.url());
let result = gateway.calculate_embeddings("test", Some("custom-embed")).await;
mock.assert();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_complete_with_reasoning_effort() {
use crate::llm::gateway::ReasoningEffort;
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/chat")
.match_body(mockito::Matcher::PartialJson(
serde_json::json!({"think": "high"}),
))
.with_status(200)
.with_body(r#"{"message":{"role":"assistant","content":"Response","thinking":"Internal reasoning..."}}"#)
.create();
let gateway = OllamaGateway::with_host(server.url());
let messages = vec![LlmMessage::user("Test")];
let config = CompletionConfig {
reasoning_effort: Some(ReasoningEffort::High),
..Default::default()
};
let result = gateway.complete("qwen3:32b", &messages, None, &config).await;
mock.assert();
assert!(result.is_ok());
let response = result.unwrap();
assert_eq!(response.content, Some("Response".to_string()));
assert_eq!(response.thinking, Some("Internal reasoning...".to_string()));
}
#[tokio::test]
async fn test_complete_stream_disables_thinking() {
use crate::llm::gateway::ReasoningEffort;
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/chat")
.match_body(mockito::Matcher::PartialJson(
serde_json::json!({"stream": true, "think": false}),
))
.with_status(200)
.with_body(
r#"{"message":{"role":"assistant","content":"Final"},"done":false}
{"done":true,"eval_count":1,"eval_duration":1000000000}
"#,
)
.create();
let gateway = OllamaGateway::with_host(server.url());
let messages = vec![LlmMessage::user("Act")];
let config = CompletionConfig {
reasoning_effort: Some(ReasoningEffort::Disabled),
..Default::default()
};
let mut stream = gateway.complete_stream("qwen3:32b", &messages, None, &config);
let mut chunks = Vec::new();
while let Some(chunk) = stream.next().await {
chunks.push(chunk.unwrap());
}
mock.assert();
assert!(chunks
.iter()
.any(|chunk| matches!(chunk, StreamChunk::Content(content) if content == "Final")));
assert!(!chunks.iter().any(|chunk| matches!(chunk, StreamChunk::Thinking(_))));
}
#[tokio::test]
async fn test_complete_stream_surfaces_thinking_chunks() {
use crate::llm::gateway::ReasoningEffort;
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/api/chat")
.match_body(mockito::Matcher::PartialJson(
serde_json::json!({"stream": true, "think": "high"}),
))
.with_status(200)
.with_body(
r#"{"message":{"role":"assistant","thinking":"Internal reasoning...","content":""},"done":false}
{"message":{"role":"assistant","content":"Final"},"done":false}
{"done":true,"eval_count":2,"eval_duration":1000000000}
"#,
)
.create();
let gateway = OllamaGateway::with_host(server.url());
let messages = vec![LlmMessage::user("Test")];
let config = CompletionConfig {
reasoning_effort: Some(ReasoningEffort::High),
..Default::default()
};
let mut stream = gateway.complete_stream("qwen3:32b", &messages, None, &config);
let mut chunks = Vec::new();
while let Some(chunk) = stream.next().await {
chunks.push(chunk.unwrap());
}
mock.assert();
assert!(chunks.iter().any(|chunk| matches!(
chunk,
StreamChunk::Progress(StreamProgress {
thinking_chars,
..
}) if *thinking_chars == "Internal reasoning...".len()
)));
assert!(chunks.iter().any(|chunk| matches!(
chunk,
StreamChunk::Thinking(thinking) if thinking == "Internal reasoning..."
)));
assert!(chunks
.iter()
.any(|chunk| matches!(chunk, StreamChunk::Content(content) if content == "Final")));
assert!(chunks.iter().any(
|chunk| matches!(chunk, StreamChunk::Metrics(metrics) if metrics.eval_count == Some(2))
));
}
}