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