Running Local LLMs with Ollama

Install Ollama, download open models and call them from Python for private, offline RAG.

Last Updated:

Module 0 · Lesson 6 of 9 · Beginner

Running Local LLMs with Ollama

Install Ollama, download open models and call them from Python for private, offline RAG.

Ollama lets you download and run open-weight language models and embedding models on your own computer with one command. For RAG it is ideal when documents must not leave your machine, when you want to experiment without API costs, or when you need to work offline. This lesson installs Ollama, runs a model, and calls it from Python for chat, streaming and embeddings.

What you will learn

  • How to install Ollama and download models
  • How to chat with a local model from the command line and from Python
  • How to stream responses and create embeddings locally
  • How to choose a model size for your hardware

Prerequisites

  • Python 3.10+ with a virtual environment (Python Environment Setup)
  • A computer with at least 8 GB of RAM (16 GB or more recommended); a GPU is optional but makes generation much faster

Step 1: Install Ollama

  • Windows and macOS: download the installer from ollama.com and run it. Ollama runs in the background and serves an API on http://localhost:11434.
  • Linux: use the install script from the Ollama website, which also sets Ollama up as a service.

Check the installation:

ollama --version

Step 2: Download and run a model

ollama pull gemma4            # a general chat model (several GB)
ollama pull embeddinggemma    # an embedding model for RAG
ollama run gemma4             # chat in the terminal; type /bye to exit
ollama list                   # show downloaded models

The model library on ollama.com lists all available models and their sizes (Llama, Qwen, Mistral, Gemma, DeepSeek and many more). Names such as gemma4 are the examples used in Ollama's own documentation at the time of writing; pick any chat model from the library that fits your hardware.

Choosing a model size

A rough guide: models with about 1–4 billion parameters run on most laptops; 7–14 billion need 16 GB of RAM or a mid-range GPU; 30 billion and above need a strong GPU or a lot of memory. Smaller models answer simple RAG questions well because the facts come from the retrieved context, not the model's memory.

Step 3: Install the Python library

pip install ollama

Step 4: Chat from Python

ollama_chat.py
from ollama import chat

response = chat(
    model="gemma4",
    messages=[
        {"role": "system", "content": "You are a concise assistant."},
        {"role": "user", "content": "What is Retrieval-Augmented Generation? Two sentences."},
    ],
)
print(response.message.content)
Retrieval-Augmented Generation (RAG) is a technique where a language model first
retrieves relevant information from an external source and then uses it to generate
an answer. This grounds the response in real data and reduces made-up facts.

Step 5: Stream the answer

stream = chat(
    model="gemma4",
    messages=[{"role": "user", "content": "List three uses of RAG."}],
    stream=True,
)
for chunk in stream:
    print(chunk.message.content, end="", flush=True)
print()

Step 6: Create embeddings

ollama.embed() accepts one string or a list of strings and returns one vector per input in the embeddings field:

import numpy as np
import ollama

result = ollama.embed(
    model="embeddinggemma",
    input=["How do I reset my password?", "Steps to change your login credentials", "Pizza places in Pune"],
)
vectors = np.array(result.embeddings)
vectors /= np.linalg.norm(vectors, axis=1, keepdims=True)    # normalise for cosine similarity
print(vectors.shape)
print(np.round(vectors @ vectors[0], 3))       # similarity of each sentence to the first
(3, 768)
[1.    0.78  0.21]

The vector size depends on the embedding model. Your similarity values will differ slightly.

Step 7: Use a remote Ollama server

If Ollama runs on another machine (for example a GPU server in your office), use a Client with the server's address:

from ollama import Client

client = Client(host="http://gpu-server.local:11434")
response = client.chat(model="gemma4", messages=[{"role": "user", "content": "Hello"}])
print(response.message.content)

Do not expose an Ollama server directly to the internet; put it behind a VPN or an authenticating proxy.

Common errors and troubleshooting

ProblemCauseFix
Connection refused on port 11434Ollama is not runningStart the Ollama app, or run ollama serve
ResponseError: model not foundModel not downloaded or misspelledollama pull <name>; check with ollama list
Very slow answersModel too large for your hardware, running on CPUUse a smaller or more quantised model
Out of memoryModel plus context exceed RAM or VRAMSmaller model, shorter context, close other programs
Different embedding sizes after a changeNew embedding modelRe-embed the whole collection with the same model

Catch errors in Python with ollama.ResponseError, which has error and status_code attributes.

Best practices

  • Use a dedicated embedding model for retrieval, not a chat model.
  • Pin the model name (and tag) in configuration so results are reproducible.
  • Measure answer quality with your own questions; small local models vary a lot.

Key takeaways

  • Ollama runs open models locally and serves them on localhost:11434.
  • ollama.chat() generates text; stream=True streams it.
  • ollama.embed() returns vectors in result.embeddings.
  • Local models keep data on your machine, at the cost of speed and some quality.

Frequently asked questions

Is Ollama free?

The software is free to run locally. Each model has its own licence; check it before commercial use.

Can Ollama replace a hosted LLM API for RAG?

For many internal or private use cases, yes. For the hardest reasoning or very high traffic, hosted models or a dedicated inference server (vLLM, LM Studio and NVIDIA NIM) are usually better.

Does Ollama support the OpenAI API format?

Ollama provides an OpenAI-compatible endpoint, which lets tools built for OpenAI talk to local models. Check the Ollama documentation for the supported endpoints.

Practice exercises

  1. Pull two chat models of different sizes and compare their answers and speed on the same question.
  2. Embed ten sentences and find the most similar pair.
  3. Write a function ask_local(question, context) that answers only from the given context.

Related tutorials