Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Run local models with Ollama

Install Ollama, run an open-weight model on your own machine, call it from scripts over the local API and choose a model size your hardware can handle, offline.

By Beginner30 min hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

Ollama downloads open-weight language models and runs them on your own machine behind a simple command line and a local HTTP API. Once a model is downloaded, prompts and documents never leave your computer, there is no per-token bill, and it works offline. The trade-off is capability: a model that fits on a laptop is noticeably weaker than the best hosted models, so local models suit private documents, drafts, classification, embeddings and experiments more than hard reasoning.

This tutorial installs Ollama, runs a model interactively, calls it from scripts and explains how to choose a model size your hardware can handle.

1. Install Ollama

On macOS and Windows, download the installer from ollama.com/download. On Linux:

curl -fsSL https://ollama.com/install.sh | sh

The installer sets up a background service that listens on http://localhost:11434. On Linux, if the service is not running, start it with ollama serve. Check the install:

ollama --version

2. Run your first model

Pull and chat with a small model. Gemma 4 from Google comes in several sizes; the e4b variant is a good first choice for a 16 GB machine:

ollama run gemma4:e4b

The first run downloads several gigabytes, then drops you into a chat prompt. Ask it something, then type /bye to leave. Everything you just did ran locally; you can check by turning off Wi-Fi and trying again.

A few commands you will use:

ollama pull gemma4:e4b     # download without starting a chat
ollama list                # models on disk and their sizes
ollama ps                  # models currently loaded in memory
ollama show gemma4:e4b     # details: parameters, context length, licence
ollama rm gemma4:e4b       # delete a model to free disk space

3. Pick a model that fits

The main constraint is memory. A model’s weights must fit in RAM (or GPU memory) with room to spare for the context. The download size on the Ollama library page is a good first estimate of the memory it needs. As a rough guide for Gemma 4, the library lists the e2b and e4b variants at around 5 to 10 GB depending on the build, and the 26b and 31b variants at 16 to 20 GB.

Your machine Start with
8 GB RAM The smallest variants (for example gemma4:e2b), short prompts
16 GB RAM or a laptop GPU gemma4:e4b or similar 4 to 8 billion parameter models
32 GB+ unified memory, or a 24 GB GPU Mid-size models in the 12 to 30 billion range

If responses crawl at a word or two per second, the model is too big for your hardware and is spilling out of GPU memory. Try a smaller variant.

Model choice also depends on the task. Ollama’s library has general chat models, coding models, embedding models (such as embeddinggemma, used in the RAG tutorials) and vision models. Check each model’s licence on its library page before using it in a product; open-weight does not always mean unrestricted.

4. Call it over HTTP

Anything that can make an HTTP request can use the local model:

curl http://localhost:11434/api/chat -d '{
  "model": "gemma4:e4b",
  "messages": [{"role": "user", "content": "Give me three names for a hiking club."}],
  "stream": false
}'

The answer is in message.content of the JSON response. Without "stream": false, Ollama streams the reply as a series of JSON lines, which is better for interactive use.

Ollama also exposes an OpenAI-compatible endpoint at http://localhost:11434/v1, so many tools and libraries that let you set a base URL for an OpenAI-style API can point at your local model with no other changes.

5. Use it from Python

Install the official Python library:

pip install ollama

A basic chat call:

from ollama import chat

response = chat(
    model="gemma4:e4b",
    messages=[{"role": "user", "content": "Explain what a context window is in two sentences."}],
)
print(response.message.content)

Streaming, so text appears as it is generated:

from ollama import chat

for part in chat(
    model="gemma4:e4b",
    messages=[{"role": "user", "content": "Write a haiku about version control."}],
    stream=True,
):
    print(part.message.content, end="", flush=True)
print()

To show streamed text in a browser rather than a terminal, stream LLM responses to a web page relays the tokens as server-sent events and adds a Stop button.

Structured output works too. Pass a JSON Schema in format, and validate the result with Pydantic:

from pydantic import BaseModel
from ollama import chat


class Sentiment(BaseModel):
    label: str
    confidence: float


review = "The battery life is great but the screen scratches far too easily."
response = chat(
    model="gemma4:e4b",
    messages=[{"role": "user", "content": f"Classify the sentiment of this review as positive, negative or mixed:\n{review}"}],
    format=Sentiment.model_json_schema(),
)
print(Sentiment.model_validate_json(response.message.content))

Small local models follow schemas less reliably than large hosted ones, so always validate, and keep the schema simple.

6. A useful first project: summarise private files

Here is a small script that summarises every text file in a folder without sending anything off your machine. It is the kind of job where local models shine: private input, simple task, many items.

# summarise_folder.py
import sys
from pathlib import Path

from ollama import chat

MODEL = "gemma4:e4b"
PROMPT = "Summarise the following document in three bullet points for a busy reader. Use only what the document says.\n\n"

for path in sorted(Path(sys.argv[1]).glob("*.txt")):
    text = path.read_text(encoding="utf-8")[:20_000]  # keep well inside the model's context window
    response = chat(model=MODEL, messages=[{"role": "user", "content": PROMPT + text}])
    print(f"## {path.name}\n{response.message.content}\n")
python summarise_folder.py ~/Documents/meeting-notes > summaries.md

The 20,000-character cut is a deliberate simplification. For longer documents, split them into parts, summarise each, then summarise the summaries.

7. Tune context length and memory

Two settings explain most “it was slow” or “it ignored half my document” reports.

The first is the context length the model is run with. Ollama loads models with a default context window that can be smaller than the model’s advertised maximum, and input beyond it is cut off. You can raise it per request with the num_ctx option. Larger windows use more memory, so raise it only as far as the task needs:

from ollama import chat

response = chat(
    model="gemma4:e4b",
    messages=[{"role": "user", "content": "Summarise this report:\n" + open("report.txt", encoding="utf-8").read()}],
    options={"num_ctx": 16384},  # tokens of context for this request
    keep_alive="10m",            # keep the model in memory for 10 minutes after this call
)
print(response.message.content)

The second is how long a model stays loaded. Loading a model from disk takes seconds; once loaded, responses start quickly. keep_alive controls how long Ollama keeps it in memory after a request, which matters when a script makes calls with pauses between them. ollama ps shows what is loaded and whether it is running on the GPU, the CPU or split between them. If you see a CPU/GPU split for a model you expected to fit on the GPU, a smaller variant or a smaller num_ctx will usually be much faster.

Pitfalls

Comparing a 4B local model with a frontier model. It will lose on hard reasoning. Judge local models on the tasks you want them for.

Silent truncation. Ollama runs models with a default context length that may be smaller than the model’s maximum. If long inputs seem to be ignored, check the num_ctx option (settable per request in options) and the model’s limits with ollama show.

Exposing the API. The server listens on localhost by default. If you change OLLAMA_HOST to make it reachable from other machines, anyone on that network can use it. Put it behind authentication if you do.

Treating the model’s knowledge as current. Local models have a training cutoff and no web access. For facts, give them the documents.

Ignoring licences. Check the licence of every model you ship in a product.

Next steps

Covers

Check your understanding

Run local models with Ollama quiz

Installing Ollama, pulling and running open-weight models, and calling them from your own code.

6 questions · pass mark 70%

Question 1 of 60 answered
  1. Which command downloads a model without starting a chat?
Back to top