ollama-rs
Library Featured
A Rust library for interacting with the Ollama API
- Downloads
- 45,579
- Dependents
- 68
- Stars
- 1,061
- Forks
- 167
- Contributors
- 59
- Commits
- 810
- Latest release
- 0.3.6 ·
About
A simple and easy-to-use library for interacting with the Ollama API.
This library was created following the Ollama API documentation.
Table of Contents
- Installation
- Initialization
- Using with llmman
- Usage
- Completion Generation
- Completion Generation (Streaming)
- Completion Generation (With Options)
- Chat Mode
- List Local Models
- Show Model Information
- Create a Model
- Create a Model (Streaming)
- Copy a Model
- Delete a Model
- Generate Embeddings
- Generate Embeddings (Batch)
- System One
- Make a Function Call
- Create a custom tool
- Completion Generation (With Thinking)
Installation
Add ollama-rs to your Cargo.toml
[dependencies]
ollama-rs = "0.3.6"
If you absolutely want the latest version, you can use the master branch by adding the following to your Cargo.toml file:
[dependencies]
ollama-rs = { git = "https://github.com/pepperoni21/ollama-rs.git", branch = "master" }
Note that the master branch may not be stable and may contain breaking changes.
Initialization
Initialize Ollama
use ollama_rs::Ollama;
// By default, it will connect to localhost:11434
let ollama = Ollama::default();
// For custom values:
let ollama = Ollama::new("http://localhost".to_string(), 11434);
Read the full README
Using with llmman
llmman is a local model runner that serves the Ollama API on port 17434, so ollama-rs works with it unchanged; just point the client at that port:
use ollama_rs::Ollama;
// llmman listens on 127.0.0.1:17434 by default
let ollama = Ollama::builder()
.host("http://localhost")
.port(17434)
.build();
Start the server with llmman serve and pull a model with llmman pull gemma4 (or llmman pull hf.co/unsloth/Qwen3.5-0.8B-GGUF to pull from Hugging Face).
Usage
Feel free to check the Chatbot example that shows how to use the library to create a simple chatbot in less than 50 lines of code. You can also check some other examples.
These examples use poor error handling for simplicity, but you should handle errors properly in your code.
Completion Generation
use ollama_rs::generation::completion::request::GenerationRequest;
let model = "llama2:latest".to_string();
let prompt = "Why is the sky blue?".to_string();
let res = ollama.generate(GenerationRequest::new(model, prompt)).await;
if let Ok(res) = res {
println!("{}", res.response);
}
OUTPUTS: The sky appears blue because of a phenomenon called Rayleigh scattering...
Completion Generation (Streaming)
Requires the stream feature.
use ollama_rs::generation::completion::request::GenerationRequest;
use tokio::io::{self, AsyncWriteExt};
use tokio_stream::StreamExt;
let model = "llama2:latest".to_string();
let prompt = "Why is the sky blue?".to_string();
let mut stream = ollama.generate_stream(GenerationRequest::new(model, prompt)).await.unwrap();
let mut stdout = io::stdout();
while let Some(res) = stream.next().await {
let responses = res.unwrap();
for resp in responses {
stdout.write_all(resp.response.as_bytes()).await.unwrap();
stdout.flush().await.unwrap();
}
}
Same output as above but streamed.
Completion Generation (With Options)
use ollama_rs::generation::completion::request::GenerationRequest;
use ollama_rs::models::ModelOptions;
let model = "llama2:latest".to_string();
let prompt = "Why is the sky blue?".to_string();
let options = ModelOptions::default()
.temperature(0.2)
.repeat_penalty(1.5)
.top_k(25)
.top_p(0.25);
let res = ollama.generate(GenerationRequest::new(model, prompt).options(options)).await;
if let Ok(res) = res {
println!("{}", res.response);
}
OUTPUTS: 1. Sun emits white sunlight: The sun consists primarily ...
Chat Mode
Every message sent and received will be stored in the library's history.
Example with history:
use ollama_rs::generation::chat::{request::ChatMessageRequest, ChatMessage};
use ollama_rs::history::ChatHistory;
let model = "llama2:latest".to_string();
let prompt = "Why is the sky blue?".to_string();
// `Vec<ChatMessage>` implements `ChatHistory`,
// but you could also implement it yourself on a custom type
let mut history = vec![];
let res = ollama
.send_chat_messages_with_history(
&mut history, // <- messages will be saved here
ChatMessageRequest::new(
model,
vec![ChatMessage::user(prompt)], // <- You should provide only one message
),
)
.await;
if let Ok(res) = res {
println!("{}", res.message.content);
}
Check chat with history examples for default and stream
List Local Models
let res = ollama.list_local_models().await.unwrap();
Returns a vector of LocalModel structs.
Show Model Information
let res = ollama.show_model_info("llama2:latest".to_string()).await.unwrap();
Returns a ModelInfo struct.
Create a Model
use ollama_rs::models::create::CreateModelRequest;
let res = ollama.create_model(CreateModelRequest::new("my_model".into())
.system("You're a chat bot.".into())
.from_model("llama2:latest".into())).await.unwrap();
Returns a CreateModelStatus struct representing the final status of the model creation.
Create a Model (Streaming)
Requires the stream feature.
use ollama_rs::models::create::CreateModelRequest;
use tokio_stream::StreamExt;
let res = ollama.create_model_stream(CreateModelRequest::new("my_model".into())
.system("You're a chat bot.".into())
.from_model("llama2:latest".into())).await.unwrap();
while let Some(res) = res.next().await {
let res = res.unwrap();
// Handle the status
}
Returns a CreateModelStatusStream that will stream every status update of the model creation.
Copy a Model
let _ = ollama.copy_model("mario".into(), "mario_copy".into()).await.unwrap();
Delete a Model
let _ = ollama.delete_model("mario_copy".into()).await.unwrap();
Generate Embeddings
use ollama_rs::generation::embeddings::request::GenerateEmbeddingsRequest;
let request = GenerateEmbeddingsRequest::new("llama2:latest".to_string(), "Why is the sky blue?".into());
let res = ollama.generate_embeddings(request).await.unwrap();
Generate Embeddings (Batch)
use ollama_rs::generation::embeddings::request::GenerateEmbeddingsRequest;
let request = GenerateEmbeddingsRequest::new("llama2:latest".to_string(), vec!["Why is the sky blue?", "Why is the sky red?"].into());
let res = ollama.generate_embeddings(request).await.unwrap();
Returns a GenerateEmbeddingsResponse struct containing the embeddings (a vector of floats).
System One
System One supports choice, yes/no (noul), and score questions with local decision models such as nimble. It requires Ollama 0.35.0 or later and a downloaded compatible model.
use ollama_rs::generation::systemone::{
request::{Question, SystemOneRequest},
SystemOneAnswer,
};
let request = SystemOneRequest::builder(
"nimble",
"Our checkout has returned 500 errors since 9am.",
)
.question(
"refund",
Question::noul("Is the customer requesting a refund?"),
)
.question(
"urgency",
Question::score(
"How urgently does this ticket need a response?",
[
"Routine: no time pressure",
"Soon: a customer is inconvenienced",
"Immediate: a critical service is unavailable",
],
),
)
.question(
"label",
Question::choice(
"Which label fits this ticket?",
[
("billing", "Payments and refunds"),
("bug", "Software errors"),
("account", "Login and account access"),
],
),
);
let response = ollama.system_one(request).await.unwrap();
for answer in response.answers.values() {
match answer {
SystemOneAnswer::Choice { choice, .. } => println!("Choice: {choice}"),
SystemOneAnswer::Noul { noul } => println!("True probability: {noul}"),
SystemOneAnswer::Score { score, .. } => println!("Score: {score}"),
}
}
The response contains typed choice, noul, and score answers, along with token usage. See the System One documentation for the available question types and model requirements.
Make a Function Call
use ollama_rs::coordinator::Coordinator;
use ollama_rs::generation::chat::ChatMessage;
use ollama_rs::generation::tools::implementations::{DDGSearcher, Scraper, Calculator};
use ollama_rs::models::ModelOptions;
let mut history = vec![];
let mut coordinator = Coordinator::new(ollama, "qwen2.5:32b".to_string(), history)
.options(ModelOptions::default().num_ctx(16384))
.add_tool(DDGSearcher::new())
.add_tool(Scraper {})
.add_tool(Calculator {});
let resp = coordinator
.chat(vec![ChatMessage::user("What is the current oil price?")])
.await.unwrap();
println!("{}", resp.message.content);
Uses the given tools (such as searching the web) to find an answer, feeds that answer back into the LLM, and returns a ChatMessageResponse with the answer to the question.
Create a custom tool
The function macro simplifies the creation of custom tools. Below is an example of a tool that retrieves the current weather for a specified city:
/// Retrieve the weather for a specified city.
///
/// * city - The city for which to get the weather.
#[ollama_rs::function]
async fn get_weather(city: String) -> Result<String, Box<dyn std::error::Error + Sync + Send>> {
let url = format!("https://wttr.in/{city}?format=%C+%t");
let response = reqwest::get(&url).await?.text().await?;
Ok(response)
}
To create a custom tool, define a function that returns a Result<String, Box<dyn std::error::Error + Sync + Send>> and annotate it with the function macro. This function will be automatically converted into a tool that can be used with the Coordinator, just like any other tool.
Ensure that the doc comment above the function clearly describes the tool's purpose and its parameters. This information will be provided to the LLM to help it understand how to use the tool.
When using streaming chat directly, you may also attach tool schemas to the request:
use ollama_rs::generation::chat::request::ChatMessageRequest;
let request = ChatMessageRequest::new("lfm2.5:8b".to_owned(), Vec::new()).add_tool(get_weather);
let mut stream = ollama.send_chat_messages_stream(request).await.unwrap();
send_chat_messages_stream yields streamed ChatMessageResponse chunks. If a chunk contains message.tool_calls, run the requested tools and include their results in a follow-up request.
For a more detailed example, see the function call example.
Completion Generation (With Thinking)
let model = "qwen3:latest".to_string();
let prompt = "Why is the sky blue?".to_string();
let res = ollama.generate(GenerationRequest::new(model, prompt).think(true)).await;
if let Ok(res) = res {
println!("{}", res.response);
}
Compatibility
- Runs on
- GPU support unknown
What shows it
- no dependency or feature matches a backend row
- Native code
- None found
- No native code found
- Python bindings
- No Python binding crate found
- License
- MIT
Compare with similar projects
Order: strongest tier first, then most downloads, then name, with unmeasured values last. A library counts downloads over 30 days. An app counts binary downloads per release. An app with none counts its crate downloads over 30 days. ML Rust runs this catalogue, so its closest project always gets a row.
| Project | Downloads | Dependents | Stars | Latest release | Runs on (GPU) | Native code | License |
|---|---|---|---|---|---|---|---|
|
A Rust library for interacting with the Ollama API |
45,579 downloads over 30 days | 68 | 1,061 | 0.3.6 | GPU support unknown | No native code found | MIT |
|
rust-genai Featured
Multi-AI Providers Library for Rust. (OpenAI, Gemini, Anthropic, DeepSeek, Ollama, OMLX, AWS Bedrock, Vertex, Xai, Groq, Kimi, GLM and many more) |
118,643 downloads over 30 days | 81 | 938 | 0.7.3 | GPU support unknown | No native code found | Apache-2.0 OR MIT |
|
openai-api-rs Listed
OpenAI API client library for Rust (unofficial) |
46,400 downloads over 30 days | 33 | 485 | 10.0.2 | GPU support unknown | No native code found | MIT |
|
aisdk Listed
An open-source Rust library for building AI-powered applications, inspired by the Vercel AI SDK. It provides a robust, type-safe, and easy-to-use interface for interacting with various Large Language Models (LLMs). |
36,877 downloads over 30 days | 4 | 263 | 0.6.1 | GPU support unknown | No native code found | MIT |
|
openai Listed
An unofficial Rust library for the OpenAI API. |
10,846 downloads over 30 days | 13 | 128 | 1.1.1 | GPU support unknown | No native code found | MIT |
|
gemini-client Listed
A Rust SDK for the Google Gemini API |
2,207 downloads over 30 days | 2 | 13 | 0.10.0 | GPU support unknown | No native code found | MIT |
|
Inference server for LLMs, speech and embeddings: OpenAI-compatible routes with streaming, plus speech synthesis (TTS) and transcription (ASR). Serves Llama, Mistral, Qwen, Mamba2, MLA+MoE and hybrid models from SafeTensors, AWQ, GPTQ and GGUF. |
8 binary downloads per release | Not applicable | 7 | 0.7.1 | CUDA, WebGPU | Binds native code: ring (feature distributed) | Apache-2.0 |
Why FeaturedIt passes every Featured gate.
What it meets
- It has 35 active dependents and 25 new dependents in 365 days. Featured needs 11 active dependents or 9 new dependents in 365 days.
- Active dependents are at 93% of their peak. Featured needs at least 50%.
- Docs are present. The release commit or a manifest ties the crate to the repository.
- No vulnerability advisory stays unpatched past the grace window. At least one version is neither a prerelease nor 0.0.x.
- The last activity is on 30 Oct 2026, 10 days ago. The rules expect an update within 900 days. Dormancy rule
Check notes
- the latest release was packaged from a dirty working tree
Exact rules: Featured library. The check on applied thresholds version 9.
Every rule outcome, as the check records it
expected-interval: version 0.3.6 base 450, doubled for 35 active users: E = 900 daysdormancy: last activity 2026-10-30, 10 days ago, E = 900: activefeatured: featured: active_users 35, new_adopters 25, former_glory 0.93
Crates2 crates
- ollama-rs Primary
- ollama-rs-macros
Measurements and sources
Each signal row shows the raw value, its source and the fetch date. The Sources list gathers every distinct source on this page. Movement needs more history.
Sources6 sources
- Description: the crates.io description
- crates.io database dump, fetched
- RustSec advisory database, fetched
- GitHub repository, fetched
- crates.io package, fetched
- GitHub contributors, fetched
Adoption35 active dependents, 25 new dependents in 365 days1 not measured
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| Active dependents | 35 | crates.io database dump | Yes | |
| New dependents (365 days) | 25 | crates.io database dump | Yes | |
| Peak active dependents | 39.5 | crates.io database dump | Yes | |
| Active dependents as a share of the peak | 0.9293 | crates.io database dump | Yes | |
| Binary downloads per release | Not measured | Yes |
MaintenanceLatest human commit: 10 days ago3 not measured
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| Latest human commit | 2026-10-30 | GitHub repository | Yes | |
| Latest release | 2026-07-24 | crates.io database dump | Yes | |
| First release | 2023-11-11 | crates.io database dump | Yes | |
| Latest version | 0.3.6 | crates.io database dump | Yes | |
| Days the oldest outside issue waits for a reply | 721 | GitHub repository | Yes | |
| Maintainer replies over 365 days | 12 | GitHub repository | Yes | |
| Repository archived | false | GitHub repository | Yes | |
| Repository gone | false | GitHub repository | Yes | |
| Release commit or manifest in the repo | true | crates.io package | Yes | |
| Published docs | true | crates.io database dump | Yes | |
| Latest release fails cargo check | Not measured | Yes | ||
| Build check date | Not measured | Yes | ||
| Build check toolchain | Not measured | Yes |
SecurityUnpatched vulnerabilities: none
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| Unpatched vulnerabilities past the grace window | none | RustSec advisory database | Yes | |
| RustSec unmaintained advisory | none | RustSec advisory database | Yes | |
| Deprecation notice | none | crates.io database dump | Yes | |
| Deprecated requirement | none | crates.io database dump | Yes |
Distribution24 releases, 45,579 downloads over 30 days5 not measured
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| Releases | 24 | crates.io database dump | Yes | |
| Downloads over 30 days | 45579 | crates.io database dump | Yes | |
| Binary downloads over the last 3 releases | Not measured | Yes | ||
| Homebrew installs on request over 365 days | Not measured | Yes | ||
| Repology repository families | Not measured | Yes | ||
| Docker pull growth over 90 days | Not measured | Yes | ||
| Docker pulls at the growth baseline | Not measured | Yes | ||
| Every version a prerelease | false | crates.io database dump | Yes | |
| Every version 0.0.x | false | crates.io database dump | Yes | |
| Every version yanked | false | crates.io database dump | Yes | |
| Crate deleted from crates.io | false | crates.io database dump | Yes |
Repository1,061 stars, 167 forks, 59 contributors, 810 commits. Stars alone never qualify a project.
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| GitHub stars | 1061 | GitHub repository | Yes — one part of the repository route | |
| GitHub forks | 167 | GitHub repository | Yes — one part of the repository route | |
| Contributors with a GitHub account | 59 | GitHub contributors | Yes — one part of the repository route | |
| Commits on the default branch | 810 | GitHub repository | No | |
| Repository's main crate left out of the entry | none | crates.io database dump | Yes |
Facts that never count
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| License | MIT | GitHub repository | No | |
| Runs on, from listed crates and their direct dependencies | GPU support unknown | crates.io database dump | No | |
| What shows each backend | no dependency or feature matches a backend row | crates.io database dump | No | |
| Native code, from listed crates and their dependencies | No native code found | crates.io database dump | No | |
| Python bindings, from direct dependencies of listed crates | No Python binding crate found | crates.io database dump | No | |
| Crates that depend on a listed crate directly | 68 | crates.io database dump | No |
Corrections and review history
No correction applies to this entry.
Judgments
A judgment enters only through an approved issue and a merged pull request.
No judgment applies to this entry.