ollama-rs

Library Featured

A Rust library for interacting with the Ollama API

Checked · Sources

Downloads
45,579
Dependents
68
Stars
1,061
Forks
167
Contributors
59
Commits
810
Latest release
0.3.6 ·

About

From the project README ·

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);
}
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.

ollama-rs beside the projects that share a topic with it
ProjectDownloadsDependentsStarsLatest releaseRuns on (GPU)Native codeLicense
ollama-rs This page Featured

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 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

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
blazr App Listed

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 days
  • dormancy: last activity 2026-10-30, 10 days ago, E = 900: active
  • featured: featured: active_users 35, new_adopters 25, former_glory 0.93
Crates2 crates

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
Adoption35 active dependents, 25 new dependents in 365 days1 not measured
Adoption measurements
SignalValueSourceFetchedCounts
Active dependents35crates.io database dumpYes
New dependents (365 days)25crates.io database dumpYes
Peak active dependents39.5crates.io database dumpYes
Active dependents as a share of the peak0.9293crates.io database dumpYes
Binary downloads per releaseNot measuredYes
MaintenanceLatest human commit: 10 days ago3 not measured
Maintenance measurements
SignalValueSourceFetchedCounts
Latest human commit2026-10-30GitHub repositoryYes
Latest release2026-07-24crates.io database dumpYes
First release2023-11-11crates.io database dumpYes
Latest version0.3.6crates.io database dumpYes
Days the oldest outside issue waits for a reply721GitHub repositoryYes
Maintainer replies over 365 days12GitHub repositoryYes
Repository archivedfalseGitHub repositoryYes
Repository gonefalseGitHub repositoryYes
Release commit or manifest in the repotruecrates.io packageYes
Published docstruecrates.io database dumpYes
Latest release fails cargo checkNot measuredYes
Build check dateNot measuredYes
Build check toolchainNot measuredYes
SecurityUnpatched vulnerabilities: none
Security measurements
SignalValueSourceFetchedCounts
Unpatched vulnerabilities past the grace windownoneRustSec advisory databaseYes
RustSec unmaintained advisorynoneRustSec advisory databaseYes
Deprecation noticenonecrates.io database dumpYes
Deprecated requirementnonecrates.io database dumpYes
Distribution24 releases, 45,579 downloads over 30 days5 not measured
Distribution measurements
SignalValueSourceFetchedCounts
Releases24crates.io database dumpYes
Downloads over 30 days45579crates.io database dumpYes
Binary downloads over the last 3 releasesNot measuredYes
Homebrew installs on request over 365 daysNot measuredYes
Repology repository familiesNot measuredYes
Docker pull growth over 90 daysNot measuredYes
Docker pulls at the growth baselineNot measuredYes
Every version a prereleasefalsecrates.io database dumpYes
Every version 0.0.xfalsecrates.io database dumpYes
Every version yankedfalsecrates.io database dumpYes
Crate deleted from crates.iofalsecrates.io database dumpYes
Repository1,061 stars, 167 forks, 59 contributors, 810 commits. Stars alone never qualify a project.
Repository measurements
SignalValueSourceFetchedCounts
GitHub stars1061GitHub repositoryYes — one part of the repository route
GitHub forks167GitHub repositoryYes — one part of the repository route
Contributors with a GitHub account59GitHub contributorsYes — one part of the repository route
Commits on the default branch810GitHub repositoryNo
Repository's main crate left out of the entrynonecrates.io database dumpYes
Facts that never count
Facts that never count measurements
SignalValueSourceFetchedCounts
LicenseMITGitHub repositoryNo
Runs on, from listed crates and their direct dependenciesGPU support unknowncrates.io database dumpNo
What shows each backendno dependency or feature matches a backend rowcrates.io database dumpNo
Native code, from listed crates and their dependenciesNo native code foundcrates.io database dumpNo
Python bindings, from direct dependencies of listed cratesNo Python binding crate foundcrates.io database dumpNo
Crates that depend on a listed crate directly68crates.io database dumpNo

Corrections and review history

Report a correction

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.