123DevOps··13 min read

Ollama with Rust: ollama-rs, streaming, chat history, and a log summary CLI

A step-by-step guide to using Ollama from Rust with the ollama-rs 0.3.6 crate: Cargo.toml, generate, streaming, chat with history, a plain reqwest version, error handling, and a CLI that summarizes logs, from cargo build --release to a small Docker image.

AI

A Python script that summarizes logs works fine on your laptop. Moving it to a server, a minimal container, or a sidecar brings the interpreter and the dependencies along. In Rust, the result is a single binary, with no runtime to install, that talks to Ollama through the local HTTP API. In this guide you go from cargo new to a CLI that reads a log and streams back a summary.

If Ollama is new to you, start with what is Ollama. The overview lives in the guide to local AI with Ollama, Python, and Rust, and the Python version of this walkthrough is in Ollama with Python.

Why Rust for talking to Ollama

Running the model is the Ollama server’s job; your program only builds the HTTP request and uses the response. For that layer, Rust has clear advantages:

Situation Why Rust helps
A CLI for the team One binary, with no runtime or dependencies to install on the user’s machine
A sidecar or agent on a server Low memory and fast startup, with no garbage collector
A service that takes traffic Concurrency with tokio and errors handled at compile time
Log and text pipelines Strong types and explicit error handling avoid surprises with odd input

If you are still picking a language for automation, see programming languages for DevOps.

There is no official client: ollama-rs or reqwest

Ollama’s official libraries are for Python and JavaScript. For Rust, Ollama’s README lists ollama-rs among the community libraries, a crate maintained by pepperoni21. This guide uses version 0.3.6; since it is a community project, pin the version and read the changelog before upgrading.

The alternative is to call the HTTP API with JSON (see what is a REST API) using reqwest and serde_json.

Criterion ollama-rs reqwest + serde_json
Ready-made types (request, response, messages) Yes You build the JSON
Streaming Built in, with the stream feature You read the NDJSON line by line
Chat history send_chat_messages_with_history You keep the message vector
Dependencies More crates Minimal

Step 1: create the project and the Cargo.toml

Create the project, add the dependencies, and pick a model. In the library at ollama.com/library, choose a small model for testing on a laptop:

cargo new log-summary
cd log-summary
cargo add [email protected] --features stream
cargo add tokio --features macros,rt-multi-thread,io-std,io-util
cargo add tokio-stream

ollama pull <model>
export OLLAMA_MODEL=<model>

The Cargo.toml ends up looking like this:

[dependencies]
ollama-rs = { version = "0.3.6", features = ["stream"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "io-std", "io-util"] }
tokio-stream = "0.1"

The stream feature enables streaming. In tokio, macros and rt-multi-thread are enough for #[tokio::main]; io-std and io-util let you write to stdout asynchronously. tokio-stream brings StreamExt, which provides .next(). With stream, ollama-rs already turns on the full tokio through feature unification, but declaring what your own code uses keeps the Cargo.toml honest.

The model comes from the OLLAMA_MODEL environment variable, not from the code, following the 12-factor idea. Each example below becomes a file in src/bin/ and runs with cargo run --bin <name>.

Watch the GenerationRequest path

The crate’s README imports ollama_rs::generation::completion::GenerationRequest. In 0.3.6 that path does not compile (the compiler reports error[E0603]: the struct is private in that module). The correct path, used in the crate’s own examples, is:

use ollama_rs::generation::completion::request::GenerationRequest;

Step 2: connect to the server

Ollama::default() points to http://127.0.0.1:11434, the server’s default address. For another host, use the builder or Ollama::try_new. The old Ollama::new(host, port) has been deprecated since 0.3.5 and triggers a compiler warning.

// src/bin/connect.rs
use ollama_rs::Ollama;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Default: http://127.0.0.1:11434
    let local = Ollama::default();

    // 2. Builder: separate host and port (panics if the URL is invalid)
    let remote = Ollama::builder()
        .host("http://ollama.example.com")
        .port(11434)
        .build();

    // 3. Full URL from configuration: returns an error instead of panicking
    let url = std::env::var("OLLAMA_URL").unwrap_or_else(|_| "http://127.0.0.1:11434".to_string());
    let configured = Ollama::try_new(url)?;

    println!("{} | {} | {}", local.url(), remote.url(), configured.url());
    Ok(())
}

Step 3: generate text with generate

generate sends a single prompt and waits for the whole answer, which arrives in the response field:

// src/bin/generate.rs
use ollama_rs::{generation::completion::request::GenerationRequest, Ollama};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let model = std::env::var("OLLAMA_MODEL")?;
    let ollama = Ollama::default();

    let request = GenerationRequest::new(model, "Explain what a container is in one sentence.");
    let response = ollama.generate(request).await?;
    println!("{}", response.response);
    Ok(())
}

The first call takes longer because the server loads the model into memory. After that, it stays loaded for 5 minutes by default (keep_alive on the request or OLLAMA_KEEP_ALIVE on the server).

Step 4: streaming with generate_stream

Here each piece is printed as soon as it arrives. Each stream item is a Result<Vec<GenerationResponse>>: one item can carry several pieces, hence the inner for.

// src/bin/stream.rs
use ollama_rs::{generation::completion::request::GenerationRequest, Ollama};
use tokio::io::{self, AsyncWriteExt};
use tokio_stream::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let model = std::env::var("OLLAMA_MODEL")?;
    let ollama = Ollama::default(); // http://127.0.0.1:11434
    let request = GenerationRequest::new(model, "Summarize: checkout returned 500 after the deploy.");
    let mut stream = ollama.generate_stream(request).await?;
    let mut out = io::stdout();
    while let Some(parts) = stream.next().await {
        for p in parts? {
            out.write_all(p.response.as_bytes()).await?;
            out.flush().await?;
        }
    }
    println!();
    Ok(())
}

Animated illustration: Cargo.toml with ollama-rs, main.rs with generate_stream, and cargo run showing the streamed answer Animated illustration (not a real screenshot): the Cargo.toml with ollama-rs 0.3.6 and the stream feature, the code with Ollama::default(), GenerationRequest, and generate_stream, and cargo run compiling and printing the answer piece by piece. The real interface may use different names and positions.

Step 5: chat with ChatMessageRequest

Chat takes a list of messages with roles: system sets the behavior and user carries the question. The answer arrives in message.content.

// src/bin/chat.rs
use ollama_rs::{
    generation::chat::{request::ChatMessageRequest, ChatMessage},
    Ollama,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let model = std::env::var("OLLAMA_MODEL")?;
    let ollama = Ollama::default();

    let messages = vec![
        ChatMessage::system("You are an SRE assistant. Answer in at most 3 sentences.".to_string()),
        ChatMessage::user("What is an SLO?".to_string()),
    ];
    let request = ChatMessageRequest::new(model, messages);
    let response = ollama.send_chat_messages(request).await?;
    println!("{}", response.message.content);
    Ok(())
}

History with send_chat_messages_with_history

The model remembers nothing between calls: its “memory” is the message list you send again. send_chat_messages_with_history handles that, storing each round’s question and answer in the vector.

// src/bin/history.rs
use ollama_rs::{
    generation::chat::{request::ChatMessageRequest, ChatMessage},
    Ollama,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let model = std::env::var("OLLAMA_MODEL")?;
    let ollama = Ollama::default();
    let mut history = vec![ChatMessage::system(
        "You are a concise SRE assistant.".to_string(),
    )];

    for question in ["What is an SLO?", "Give an example for a payments API."] {
        let request = ChatMessageRequest::new(
            model.clone(),
            vec![ChatMessage::user(question.to_string())],
        );
        let response = ollama
            .send_chat_messages_with_history(&mut history, request)
            .await?;
        println!("> {question}\n{}\n", response.message.content);
    }
    println!("messages in history: {}", history.len());
    Ok(())
}

At the end, the history holds five messages: the system one and two rounds. In long conversations, trim old messages, because everything is sent again and has to fit in the model’s context.

Chat streaming

send_chat_messages_stream combines both ideas. Here each item is a Result<ChatMessageResponse, ()>; while let Some(Ok(...)) silently ends the loop on an error, and the CLI further down handles that case.

// src/bin/chat_stream.rs
use ollama_rs::{
    generation::chat::{request::ChatMessageRequest, ChatMessage},
    Ollama,
};
use tokio::io::{self, AsyncWriteExt};
use tokio_stream::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let model = std::env::var("OLLAMA_MODEL")?;
    let ollama = Ollama::default();

    let request = ChatMessageRequest::new(
        model,
        vec![ChatMessage::user("Name 3 Linux commands to investigate a full disk.".to_string())],
    );
    let mut stream = ollama.send_chat_messages_stream(request).await?;
    let mut out = io::stdout();
    while let Some(Ok(part)) = stream.next().await {
        out.write_all(part.message.content.as_bytes()).await?;
        out.flush().await?;
    }
    println!();
    Ok(())
}

Alternative: plain reqwest + serde_json

Without the crate, you call /api/chat directly. In a separate project, these are the dependencies:

[dependencies]
reqwest = { version = "0.12", features = ["json"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
// src/main.rs
use serde_json::{json, Value};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let model = std::env::var("OLLAMA_MODEL")?;
    let body = json!({
        "model": model,
        "messages": [{"role": "user", "content": "Explain DNS in one sentence."}],
        "stream": false
    });
    let v: Value = reqwest::Client::new()
        .post("http://localhost:11434/api/chat")
        .json(&body)
        .send()
        .await?
        .error_for_status()?
        .json()
        .await?;
    println!("{}", v["message"]["content"].as_str().unwrap_or_default());
    Ok(())
}

"stream": false matters: without it, the API answers in NDJSON, one JSON object per line, and you would have to read bytes_stream() (reqwest’s stream feature) until done: true; see the API documentation. The OpenAI-compatible endpoint, /v1/chat/completions, works too.

Error handling: ?, Box, and anyhow

The examples return Result<(), Box<dyn std::error::Error>>, and ? propagates any error: a missing variable, a network failure, invalid JSON. For better messages, handle the OllamaError cases: in 0.3.6, a connection failure arrives as ReqwestError, and an HTTP error from the server (a missing model, for example) arrives as Other, with the response body.

// src/bin/errors.rs
use ollama_rs::{error::OllamaError, generation::completion::request::GenerationRequest, Ollama};

async fn ask(
    ollama: &Ollama,
    model: &str,
    prompt: &str,
) -> Result<String, Box<dyn std::error::Error>> {
    let request = GenerationRequest::new(model.to_string(), prompt);
    let response = match ollama.generate(request).await {
        Ok(r) => r,
        Err(OllamaError::ReqwestError(e)) => {
            return Err(format!("cannot reach Ollama (is it running?): {e}").into())
        }
        Err(OllamaError::Other(body)) => {
            return Err(format!("the server rejected the request: {body}").into())
        }
        Err(e) => return Err(e.into()),
    };
    let text = response.response.trim().to_string();
    if text.is_empty() {
        return Err("the model returned an empty answer".into());
    }
    Ok(text)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let model = std::env::var("OLLAMA_MODEL")?;
    let ollama = Ollama::default();
    println!("{}", ask(&ollama, &model, "What is an SLO? One sentence.").await?);
    Ok(())
}

When main returns an error, Rust prints its debug form: a missing variable shows up only as Error: NotPresent. That is why the CLI below uses map_err to add context.

In larger applications, the anyhow crate is common: anyhow::Result replaces Box<dyn Error>, and .context("...") says what the program was doing when the error happened. In libraries, prefer your own error types, for example with thiserror.

Mini project: a CLI that summarizes logs

Putting it all together: a CLI that reads the file from the argument, or stdin, keeps only the end of the log, and streams the summary. Put this in src/main.rs:

// src/main.rs
use std::io::Read;

use ollama_rs::{
    generation::chat::{request::ChatMessageRequest, ChatMessage},
    models::ModelOptions,
    Ollama,
};
use tokio::io::{self, AsyncWriteExt};
use tokio_stream::StreamExt;

const MAX_BYTES: usize = 32 * 1024; // send only the last ~32 KB of the log

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let model = std::env::var("OLLAMA_MODEL").map_err(|_| "set the OLLAMA_MODEL variable")?;
    let url = std::env::var("OLLAMA_URL").unwrap_or_else(|_| "http://127.0.0.1:11434".to_string());
    let ollama = Ollama::try_new(url)?;

    // file from the first argument or, with no argument, stdin
    let log = match std::env::args().nth(1) {
        Some(path) => std::fs::read_to_string(path)?,
        None => {
            let mut text = String::new();
            std::io::stdin().read_to_string(&mut text)?;
            text
        }
    };
    if log.trim().is_empty() {
        return Err("empty log: pass a file or send the log through stdin".into());
    }

    // keep the end of the log, cutting on a UTF-8 character boundary
    let mut start = log.len().saturating_sub(MAX_BYTES);
    while !log.is_char_boundary(start) {
        start += 1;
    }
    let tail = &log[start..];

    let messages = vec![
        ChatMessage::system(
            "You are an SRE. Summarize the log in at most 5 bullets: main errors, affected service, \
             time, and one suggested next step. Do not invent anything that is not in the log."
                .to_string(),
        ),
        ChatMessage::user(format!("Log:\n{tail}")),
    ];
    let request = ChatMessageRequest::new(model, messages)
        .options(ModelOptions::default().temperature(0.2).num_predict(400)); // cap on answer tokens

    let mut stream = ollama.send_chat_messages_stream(request).await?;
    let mut out = io::stdout();
    while let Some(part) = stream.next().await {
        let part = part.map_err(|_| "failed to read the Ollama stream")?;
        out.write_all(part.message.content.as_bytes()).await?;
        out.flush().await?;
    }
    out.write_all(b"\n").await?;
    Ok(())
}

Design details: the byte limit keeps you from overflowing the context; the low temperature makes the summary more predictable; num_predict caps the answer length (in testing, a tiny model got stuck in a loop repeating the log and, without that cap, the CLI never finished); and OLLAMA_URL points to another server without recompiling. To try it:

cargo run --bin log-summary -- /var/log/app.log
journalctl -u nginx --since "1 hour ago" | cargo run --bin log-summary

Release build and a small Docker image

The release build produces an optimized binary in target/release/, which you can copy anywhere:

cargo build --release
ls -lh target/release/log-summary
tail -n 500 /var/log/syslog | ./target/release/log-summary

For a container, a multi-stage build compiles in an image with the full Rust toolchain and copies only the binary into a lean image (see what is Docker). On Linux, reqwest’s default TLS uses OpenSSL, so the final image installs libssl3 and ca-certificates. Add target/ to .dockerignore.

# stage 1: build with the full Rust toolchain
FROM rust:1-bookworm AS build
WORKDIR /app
COPY . .
RUN cargo build --release

# stage 2: only the binary and the libraries it needs
FROM debian:bookworm-slim
RUN apt-get update \
 && apt-get install -y --no-install-recommends ca-certificates libssl3 \
 && rm -rf /var/lib/apt/lists/*
COPY --from=build /app/target/release/log-summary /usr/local/bin/log-summary
USER nobody
ENTRYPOINT ["log-summary"]

Inside the container, 127.0.0.1 is the container itself, not your machine. On Docker Desktop (macOS and Windows), point to host.docker.internal; on Linux, the host network does the job:

docker build -t log-summary .

# Docker Desktop (macOS/Windows)
docker run --rm -i -e OLLAMA_MODEL=<model> -e OLLAMA_URL=http://host.docker.internal:11434 log-summary < app.log

# Linux: host network, and the default 127.0.0.1:11434 works
docker run --rm -i --network host -e OLLAMA_MODEL=<model> log-summary < app.log

For even smaller images, consider static musl binaries or distroless images.

Security: an API without auth and untrusted output

  • The Ollama API has no authentication. By default it listens on 127.0.0.1:11434. With OLLAMA_HOST=0.0.0.0, anyone who can reach the port can use the server: protect it with a firewall or a reverse proxy with authentication and TLS. The headers feature of ollama-rs sends headers, such as a token for that proxy; see the crate documentation.
  • Model output is untrusted. Never run suggested commands without review. If you need JSON, ask for a structured format and validate it with serde: a small model can return valid JSON with wrong content.
  • The log is untrusted input too. A log line can contain text written by an attacker trying to change the model’s instructions (prompt injection). See AI application security with the OWASP LLM list.
  • Personal data. Logs often hold IP addresses, emails, and user IDs. A local model keeps everything on the machine, which helps with privacy laws such as Brazil’s LGPD or the GDPR, but the machine’s own security still matters.
  • Cloud models. According to the documentation, models with the :cloud tag run on Ollama’s servers, so the data leaves the machine. If your policy requires everything to stay local, OLLAMA_NO_CLOUD=1 puts the server in local-only mode; check the current documentation.

Checklist

  • Pinned ollama-rs to 0.3.6 with the stream feature and declared the tokio features I use
  • Imported GenerationRequest from generation::completion::request
  • Replaced Ollama::new with Ollama::default(), the builder, or Ollama::try_new
  • Read the model from OLLAMA_MODEL and the address from OLLAMA_URL, with nothing hardcoded
  • Capped the input size and trimmed old chat history
  • Built the binary with cargo build --release and a multi-stage image
  • Kept the API on localhost or behind a proxy with authentication, and validated the model output

One binary, one local port, and no data leaving the machine: it is hard to ask more of an AI CLI.

Get updates on new posts and stay in the loop!