ollama.rs

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