1use anyhow::{Context as _, Result};
2use futures::{AsyncBufReadExt, AsyncReadExt, StreamExt, io::BufReader, stream::BoxStream};
3use http_client::{AsyncBody, HttpClient, HttpRequestExt, Method, Request as HttpRequest};
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6pub use settings::KeepAlive;
7
8pub const OLLAMA_API_URL: &str = "http://localhost:11434";
9
10#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
11#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
12pub struct Model {
13 pub name: String,
14 pub display_name: Option<String>,
15 pub max_tokens: u64,
16 pub keep_alive: Option<KeepAlive>,
17 pub supports_tools: Option<bool>,
18 pub supports_vision: Option<bool>,
19 pub supports_thinking: Option<bool>,
20}
21
22fn get_max_tokens(name: &str) -> u64 {
23 /// Default context length for unknown models.
24 const DEFAULT_TOKENS: u64 = 4096;
25 /// Magic number. Lets many Ollama models work with ~16GB of ram.
26 /// Models that support context beyond 16k such as codestral (32k) or devstral (128k) will be clamped down to 16k
27 const MAXIMUM_TOKENS: u64 = 16384;
28
29 match name.split(':').next().unwrap() {
30 "granite-code" | "phi" | "tinyllama" => 2048,
31 "llama2" | "stablelm2" | "vicuna" | "yi" => 4096,
32 "aya" | "codegemma" | "gemma" | "gemma2" | "llama3" | "starcoder" => 8192,
33 "codellama" | "starcoder2" => 16384,
34 "codestral" | "dolphin-mixtral" | "llava" | "magistral" | "mistral" | "mixstral"
35 | "qwen2" | "qwen2.5-coder" => 32768,
36 "cogito" | "command-r" | "deepseek-coder-v2" | "deepseek-r1" | "deepseek-v3"
37 | "devstral" | "gemma3" | "gpt-oss" | "granite3.3" | "llama3.1" | "llama3.2"
38 | "llama3.3" | "mistral-nemo" | "phi3" | "phi3.5" | "phi4" | "qwen3" | "yi-coder" => 128000,
39 "qwen3-coder" => 256000,
40 _ => DEFAULT_TOKENS,
41 }
42 .clamp(1, MAXIMUM_TOKENS)
43}
44
45impl Model {
46 pub fn new(
47 name: &str,
48 display_name: Option<&str>,
49 max_tokens: Option<u64>,
50 supports_tools: Option<bool>,
51 supports_vision: Option<bool>,
52 supports_thinking: Option<bool>,
53 ) -> Self {
54 Self {
55 name: name.to_owned(),
56 display_name: display_name
57 .map(ToString::to_string)
58 .or_else(|| name.strip_suffix(":latest").map(ToString::to_string)),
59 max_tokens: max_tokens.unwrap_or_else(|| get_max_tokens(name)),
60 keep_alive: Some(KeepAlive::indefinite()),
61 supports_tools,
62 supports_vision,
63 supports_thinking,
64 }
65 }
66
67 pub fn id(&self) -> &str {
68 &self.name
69 }
70
71 pub fn display_name(&self) -> &str {
72 self.display_name.as_ref().unwrap_or(&self.name)
73 }
74
75 pub fn max_token_count(&self) -> u64 {
76 self.max_tokens
77 }
78}
79
80#[derive(Serialize, Deserialize, Debug)]
81#[serde(tag = "role", rename_all = "lowercase")]
82pub enum ChatMessage {
83 Assistant {
84 content: String,
85 tool_calls: Option<Vec<OllamaToolCall>>,
86 #[serde(skip_serializing_if = "Option::is_none")]
87 images: Option<Vec<String>>,
88 thinking: Option<String>,
89 },
90 User {
91 content: String,
92 #[serde(skip_serializing_if = "Option::is_none")]
93 images: Option<Vec<String>>,
94 },
95 System {
96 content: String,
97 },
98 Tool {
99 tool_name: String,
100 content: String,
101 },
102}
103
104#[derive(Serialize, Deserialize, Debug)]
105#[serde(rename_all = "lowercase")]
106pub enum OllamaToolCall {
107 Function(OllamaFunctionCall),
108}
109
110#[derive(Serialize, Deserialize, Debug)]
111pub struct OllamaFunctionCall {
112 pub name: String,
113 pub arguments: Value,
114}
115
116#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
117pub struct OllamaFunctionTool {
118 pub name: String,
119 pub description: Option<String>,
120 pub parameters: Option<Value>,
121}
122
123#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
124#[serde(tag = "type", rename_all = "lowercase")]
125pub enum OllamaTool {
126 Function { function: OllamaFunctionTool },
127}
128
129#[derive(Serialize, Debug)]
130pub struct ChatRequest {
131 pub model: String,
132 pub messages: Vec<ChatMessage>,
133 pub stream: bool,
134 pub keep_alive: KeepAlive,
135 pub options: Option<ChatOptions>,
136 pub tools: Vec<OllamaTool>,
137 pub think: Option<bool>,
138}
139
140// https://github.com/ollama/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values
141#[derive(Serialize, Default, Debug)]
142pub struct ChatOptions {
143 pub num_ctx: Option<u64>,
144 pub num_predict: Option<isize>,
145 pub stop: Option<Vec<String>>,
146 pub temperature: Option<f32>,
147 pub top_p: Option<f32>,
148}
149
150#[derive(Deserialize, Debug)]
151pub struct ChatResponseDelta {
152 pub model: String,
153 pub created_at: String,
154 pub message: ChatMessage,
155 pub done_reason: Option<String>,
156 pub done: bool,
157 pub prompt_eval_count: Option<u64>,
158 pub eval_count: Option<u64>,
159}
160
161#[derive(Serialize, Deserialize)]
162pub struct LocalModelsResponse {
163 pub models: Vec<LocalModelListing>,
164}
165
166#[derive(Serialize, Deserialize)]
167pub struct LocalModelListing {
168 pub name: String,
169 pub modified_at: String,
170 pub size: u64,
171 pub digest: String,
172 pub details: ModelDetails,
173}
174
175#[derive(Serialize, Deserialize)]
176pub struct LocalModel {
177 pub modelfile: String,
178 pub parameters: String,
179 pub template: String,
180 pub details: ModelDetails,
181}
182
183#[derive(Serialize, Deserialize)]
184pub struct ModelDetails {
185 pub format: String,
186 pub family: String,
187 pub families: Option<Vec<String>>,
188 pub parameter_size: String,
189 pub quantization_level: String,
190}
191
192#[derive(Deserialize, Debug)]
193pub struct ModelShow {
194 #[serde(default)]
195 pub capabilities: Vec<String>,
196}
197
198impl ModelShow {
199 pub fn supports_tools(&self) -> bool {
200 // .contains expects &String, which would require an additional allocation
201 self.capabilities.iter().any(|v| v == "tools")
202 }
203
204 pub fn supports_vision(&self) -> bool {
205 self.capabilities.iter().any(|v| v == "vision")
206 }
207
208 pub fn supports_thinking(&self) -> bool {
209 self.capabilities.iter().any(|v| v == "thinking")
210 }
211}
212
213pub async fn stream_chat_completion(
214 client: &dyn HttpClient,
215 api_url: &str,
216 api_key: Option<&str>,
217 request: ChatRequest,
218) -> Result<BoxStream<'static, Result<ChatResponseDelta>>> {
219 let uri = format!("{api_url}/api/chat");
220 let request = HttpRequest::builder()
221 .method(Method::POST)
222 .uri(uri)
223 .header("Content-Type", "application/json")
224 .when_some(api_key, |builder, api_key| {
225 builder.header("Authorization", format!("Bearer {api_key}"))
226 })
227 .body(AsyncBody::from(serde_json::to_string(&request)?))?;
228
229 let mut response = client.send(request).await?;
230 if response.status().is_success() {
231 let reader = BufReader::new(response.into_body());
232
233 Ok(reader
234 .lines()
235 .map(|line| match line {
236 Ok(line) => serde_json::from_str(&line).context("Unable to parse chat response"),
237 Err(e) => Err(e.into()),
238 })
239 .boxed())
240 } else {
241 let mut body = String::new();
242 response.body_mut().read_to_string(&mut body).await?;
243 anyhow::bail!(
244 "Failed to connect to Ollama API: {} {}",
245 response.status(),
246 body,
247 );
248 }
249}
250
251pub async fn get_models(
252 client: &dyn HttpClient,
253 api_url: &str,
254 api_key: Option<&str>,
255) -> Result<Vec<LocalModelListing>> {
256 let uri = format!("{api_url}/api/tags");
257 let request = HttpRequest::builder()
258 .method(Method::GET)
259 .uri(uri)
260 .header("Accept", "application/json")
261 .when_some(api_key, |builder, api_key| {
262 builder.header("Authorization", format!("Bearer {api_key}"))
263 })
264 .body(AsyncBody::default())?;
265
266 let mut response = client.send(request).await?;
267
268 let mut body = String::new();
269 response.body_mut().read_to_string(&mut body).await?;
270
271 anyhow::ensure!(
272 response.status().is_success(),
273 "Failed to connect to Ollama API: {} {}",
274 response.status(),
275 body,
276 );
277 let response: LocalModelsResponse =
278 serde_json::from_str(&body).context("Unable to parse Ollama tag listing")?;
279 Ok(response.models)
280}
281
282/// Fetch details of a model, used to determine model capabilities
283pub async fn show_model(
284 client: &dyn HttpClient,
285 api_url: &str,
286 api_key: Option<&str>,
287 model: &str,
288) -> Result<ModelShow> {
289 let uri = format!("{api_url}/api/show");
290 let request = HttpRequest::builder()
291 .method(Method::POST)
292 .uri(uri)
293 .header("Content-Type", "application/json")
294 .when_some(api_key, |builder, api_key| {
295 builder.header("Authorization", format!("Bearer {api_key}"))
296 })
297 .body(AsyncBody::from(
298 serde_json::json!({ "model": model }).to_string(),
299 ))?;
300
301 let mut response = client.send(request).await?;
302 let mut body = String::new();
303 response.body_mut().read_to_string(&mut body).await?;
304
305 anyhow::ensure!(
306 response.status().is_success(),
307 "Failed to connect to Ollama API: {} {}",
308 response.status(),
309 body,
310 );
311 let details: ModelShow = serde_json::from_str(body.as_str())?;
312 Ok(details)
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318
319 #[test]
320 fn parse_completion() {
321 let response = serde_json::json!({
322 "model": "llama3.2",
323 "created_at": "2023-12-12T14:13:43.416799Z",
324 "message": {
325 "role": "assistant",
326 "content": "Hello! How are you today?"
327 },
328 "done": true,
329 "total_duration": 5191566416u64,
330 "load_duration": 2154458,
331 "prompt_eval_count": 26,
332 "prompt_eval_duration": 383809000,
333 "eval_count": 298,
334 "eval_duration": 4799921000u64
335 });
336 let _: ChatResponseDelta = serde_json::from_value(response).unwrap();
337 }
338
339 #[test]
340 fn parse_streaming_completion() {
341 let partial = serde_json::json!({
342 "model": "llama3.2",
343 "created_at": "2023-08-04T08:52:19.385406455-07:00",
344 "message": {
345 "role": "assistant",
346 "content": "The",
347 "images": null
348 },
349 "done": false
350 });
351
352 let _: ChatResponseDelta = serde_json::from_value(partial).unwrap();
353
354 let last = serde_json::json!({
355 "model": "llama3.2",
356 "created_at": "2023-08-04T19:22:45.499127Z",
357 "message": {
358 "role": "assistant",
359 "content": ""
360 },
361 "done": true,
362 "total_duration": 4883583458u64,
363 "load_duration": 1334875,
364 "prompt_eval_count": 26,
365 "prompt_eval_duration": 342546000,
366 "eval_count": 282,
367 "eval_duration": 4535599000u64
368 });
369
370 let _: ChatResponseDelta = serde_json::from_value(last).unwrap();
371 }
372
373 #[test]
374 fn parse_tool_call() {
375 let response = serde_json::json!({
376 "model": "llama3.2:3b",
377 "created_at": "2025-04-28T20:02:02.140489Z",
378 "message": {
379 "role": "assistant",
380 "content": "",
381 "tool_calls": [
382 {
383 "function": {
384 "name": "weather",
385 "arguments": {
386 "city": "london",
387 }
388 }
389 }
390 ]
391 },
392 "done_reason": "stop",
393 "done": true,
394 "total_duration": 2758629166u64,
395 "load_duration": 1770059875,
396 "prompt_eval_count": 147,
397 "prompt_eval_duration": 684637583,
398 "eval_count": 16,
399 "eval_duration": 302561917,
400 });
401
402 let result: ChatResponseDelta = serde_json::from_value(response).unwrap();
403 match result.message {
404 ChatMessage::Assistant {
405 content,
406 tool_calls,
407 images: _,
408 thinking,
409 } => {
410 assert!(content.is_empty());
411 assert!(tool_calls.is_some_and(|v| !v.is_empty()));
412 assert!(thinking.is_none());
413 }
414 _ => panic!("Deserialized wrong role"),
415 }
416 }
417
418 #[test]
419 fn parse_show_model() {
420 let response = serde_json::json!({
421 "license": "LLAMA 3.2 COMMUNITY LICENSE AGREEMENT...",
422 "details": {
423 "parent_model": "",
424 "format": "gguf",
425 "family": "llama",
426 "families": ["llama"],
427 "parameter_size": "3.2B",
428 "quantization_level": "Q4_K_M"
429 },
430 "model_info": {
431 "general.architecture": "llama",
432 "general.basename": "Llama-3.2",
433 "general.file_type": 15,
434 "general.finetune": "Instruct",
435 "general.languages": ["en", "de", "fr", "it", "pt", "hi", "es", "th"],
436 "general.parameter_count": 3212749888u64,
437 "general.quantization_version": 2,
438 "general.size_label": "3B",
439 "general.tags": ["facebook", "meta", "pytorch", "llama", "llama-3", "text-generation"],
440 "general.type": "model",
441 "llama.attention.head_count": 24,
442 "llama.attention.head_count_kv": 8,
443 "llama.attention.key_length": 128,
444 "llama.attention.layer_norm_rms_epsilon": 0.00001,
445 "llama.attention.value_length": 128,
446 "llama.block_count": 28,
447 "llama.context_length": 131072,
448 "llama.embedding_length": 3072,
449 "llama.feed_forward_length": 8192,
450 "llama.rope.dimension_count": 128,
451 "llama.rope.freq_base": 500000,
452 "llama.vocab_size": 128256,
453 "tokenizer.ggml.bos_token_id": 128000,
454 "tokenizer.ggml.eos_token_id": 128009,
455 "tokenizer.ggml.merges": null,
456 "tokenizer.ggml.model": "gpt2",
457 "tokenizer.ggml.pre": "llama-bpe",
458 "tokenizer.ggml.token_type": null,
459 "tokenizer.ggml.tokens": null
460 },
461 "tensors": [
462 { "name": "rope_freqs.weight", "type": "F32", "shape": [64] },
463 { "name": "token_embd.weight", "type": "Q4_K_S", "shape": [3072, 128256] }
464 ],
465 "capabilities": ["completion", "tools"],
466 "modified_at": "2025-04-29T21:24:41.445877632+03:00"
467 });
468
469 let result: ModelShow = serde_json::from_value(response).unwrap();
470 assert!(result.supports_tools());
471 assert!(result.capabilities.contains(&"tools".to_string()));
472 assert!(result.capabilities.contains(&"completion".to_string()));
473 }
474
475 #[test]
476 fn serialize_chat_request_with_images() {
477 let base64_image = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
478
479 let request = ChatRequest {
480 model: "llava".to_string(),
481 messages: vec![ChatMessage::User {
482 content: "What do you see in this image?".to_string(),
483 images: Some(vec![base64_image.to_string()]),
484 }],
485 stream: false,
486 keep_alive: KeepAlive::default(),
487 options: None,
488 think: None,
489 tools: vec![],
490 };
491
492 let serialized = serde_json::to_string(&request).unwrap();
493 assert!(serialized.contains("images"));
494 assert!(serialized.contains(base64_image));
495 }
496
497 #[test]
498 fn serialize_chat_request_without_images() {
499 let request = ChatRequest {
500 model: "llama3.2".to_string(),
501 messages: vec![ChatMessage::User {
502 content: "Hello, world!".to_string(),
503 images: None,
504 }],
505 stream: false,
506 keep_alive: KeepAlive::default(),
507 options: None,
508 think: None,
509 tools: vec![],
510 };
511
512 let serialized = serde_json::to_string(&request).unwrap();
513 assert!(!serialized.contains("images"));
514 }
515
516 #[test]
517 fn test_json_format_with_images() {
518 let base64_image = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
519
520 let request = ChatRequest {
521 model: "llava".to_string(),
522 messages: vec![ChatMessage::User {
523 content: "What do you see?".to_string(),
524 images: Some(vec![base64_image.to_string()]),
525 }],
526 stream: false,
527 keep_alive: KeepAlive::default(),
528 options: None,
529 think: None,
530 tools: vec![],
531 };
532
533 let serialized = serde_json::to_string(&request).unwrap();
534
535 let parsed: serde_json::Value = serde_json::from_str(&serialized).unwrap();
536 let message_images = parsed["messages"][0]["images"].as_array().unwrap();
537 assert_eq!(message_images.len(), 1);
538 assert_eq!(message_images[0].as_str().unwrap(), base64_image);
539 }
540}