New

🦙 Ollama Tutorial for Beginners: Run AI Models Locally

Install Ollama, chat with an open model on your own computer, then call it from Python and build a small offline study buddy. No API key, no bill.

Beginner ⏱️ ~40 minutes 🧰 Ollama, Python 3.10+, ollama 0.6
← Generative AI & RAG Track

What You'll Build in This Ollama Tutorial

This Ollama tutorial for beginners shows you how to run a large language model on your own laptop and use it from code. You will install Ollama, chat with Google's open Gemma 4 model in the terminal, call the local REST API, and then write a Python study buddy that streams answers, remembers the conversation and returns quiz questions as clean JSON. Everything runs offline once the model is downloaded.

Why learn this now? Open-weight models are everywhere this month, from small ones you can run on a laptop to giants like Amazon Ergo that need a data centre. Ollama is the easiest way to get hands-on with the small ones, and the skills (messages, streaming, structured output) carry over to every hosted API.

Prerequisites

Learn Ollama Step by Step

1 Install Ollama

On macOS or Windows, download the installer from ollama.com/download and run it. On Linux, use the official install script:

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

Ollama runs a small server in the background on http://localhost:11434. Check that it works:

ollama --version

If the command is not found on Windows, open a new terminal so the updated PATH is picked up. If the server is not running, start it with ollama serve.

2 Run your first local model

Run Gemma 4, the model the Ollama docs use in their own examples. The first run downloads the model, which can take a while:

ollama run gemma4

Type a question at the >>> prompt, for example "Explain Ohm's law in two sentences". Type /bye to leave. Low on memory? Open the model's page on ollama.com/library and pick a smaller tag, then use that name everywhere in this tutorial.

These are the commands you will use every day:

ollama pull gemma4    # download a model without chatting
ollama ls             # list the models on your computer
ollama ps             # show models loaded in memory right now
ollama show gemma4    # details: parameters, context length, license
ollama stop gemma4    # unload it from memory
ollama rm gemma4      # delete it from disk

3 Call the Ollama API with curl

Every Ollama feature is available through a local REST API. The chat endpoint takes a list of messages, just like hosted AI APIs:

curl http://localhost:11434/api/chat -d '{
  "model": "gemma4",
  "messages": [{"role": "user", "content": "Give me one tip for remembering the periodic table."}],
  "stream": false
}'

With "stream": false you get one JSON object back, and the answer is in message.content. Leave stream out and Ollama sends the answer piece by piece as separate JSON lines instead.

4 Use Ollama from Python

Create a project and install the official Python library:

mkdir study-buddy && cd study-buddy
python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -U ollama

Save this as hello_ollama.py:

# hello_ollama.py - one question, one answer
from ollama import chat

MODEL = "gemma4"

response = chat(
    model=MODEL,
    messages=[{"role": "user", "content": "What is photosynthesis? Answer for a class 10 student."}],
)
print(response.message.content)

Run python hello_ollama.py. chat() sends the request to your local server and returns a response object. The text is in response.message.content (the dictionary style response["message"]["content"] works too).

5 Stream answers and keep a conversation

Local models can feel slow if you wait for the whole answer. Pass stream=True and print each chunk as it arrives. To give the model memory, keep a messages list and add both your question and its answer after every turn. Save this as study_buddy.py:

# study_buddy.py - a streaming chat that remembers the conversation
from ollama import chat

MODEL = "gemma4"
messages = [
    {"role": "system", "content": "You are a patient study buddy for Indian school and exam students. "
                                  "Explain simply, use short examples and end with one check question."},
]

while True:
    question = input("\nYou: ").strip()
    if question.lower() in {"quit", "exit"}:
        break
    messages.append({"role": "user", "content": question})

    print("Buddy: ", end="", flush=True)
    answer = ""
    for chunk in chat(model=MODEL, messages=messages, stream=True):
        piece = chunk.message.content or ""
        print(piece, end="", flush=True)
        answer += piece
    print()

    messages.append({"role": "assistant", "content": answer})

Ask "What is velocity?" and then "How is it different from speed?". The second answer makes sense only because the first exchange is still in messages. The model itself remembers nothing between calls; your list is the memory.

6 Get structured JSON output

Apps need data, not paragraphs. Ollama can force the reply to match a JSON schema. Describe the shape with Pydantic, pass its schema as format, then validate the reply. Install Pydantic with pip install pydantic and save quiz_maker.py:

# quiz_maker.py - ask for a quiz question as validated JSON
from ollama import chat
from pydantic import BaseModel

MODEL = "gemma4"


class QuizQuestion(BaseModel):
    question: str
    options: list[str]
    correct_index: int
    explanation: str


response = chat(
    model=MODEL,
    messages=[{"role": "user", "content": "Write one multiple-choice question with 4 options about Newton's first law."}],
    format=QuizQuestion.model_json_schema(),
    options={"temperature": 0},
)

quiz = QuizQuestion.model_validate_json(response.message.content)
print(quiz.question)
for i, option in enumerate(quiz.options):
    marker = "*" if i == quiz.correct_index else " "
    print(f" {marker} {i + 1}. {option}")
print("Why:", quiz.explanation)

Setting temperature to 0 makes the output more predictable, which helps with structured data. The schema guarantees the shape, not the facts: always check the answer key a small model gives you.

7 Reuse OpenAI-style code with Ollama

Ollama also exposes an OpenAI-compatible endpoint at http://localhost:11434/v1/. Code written for the OpenAI Python SDK can talk to your local model by changing two lines. Run pip install openai, then:

# openai_compat.py - the OpenAI SDK pointed at your local Ollama
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1/", api_key="ollama")  # key is required but ignored

reply = client.chat.completions.create(
    model="gemma4",
    messages=[{"role": "user", "content": "Name three uses of a binary search tree."}],
)
print(reply.choices[0].message.content)

This is handy for testing an app offline before you switch it to a hosted model, or for trying tools that only speak the OpenAI format.

8 Know the limits

  • Small models make more mistakes. A model that fits on a laptop is far weaker than frontier models, so double-check facts, maths and code.
  • Memory sets the size. If answers are very slow or the model fails to load, use a smaller tag and close other heavy apps. ollama ps shows what is loaded.
  • Keep the server local. By default the API listens only on your own machine. Do not expose port 11434 to the internet without authentication in front of it.
  • Check each model's license with ollama show before you use it in a product.

Practice Task

Extend the study buddy on your own, then check yourself with the quiz below.

  1. In study_buddy.py, add a /reset command that clears the conversation but keeps the system message.
  2. Keep only the system message and the last 10 messages, so very long chats stay fast.
  3. In quiz_maker.py, add a difficulty field to the schema and ask for an "easy" and a "hard" question on the same topic.
  4. Pull a second, smaller model and compare its answers and speed with gemma4 on the same five questions.

Ollama Tutorial Quiz

Five quick questions on this tutorial.

Frequently Asked Questions

Is Ollama free to use?

Yes. Ollama is open-source software and running models on your own computer costs nothing beyond your electricity and disk space. Ollama also offers optional cloud models that run on its servers; those need an account and are not covered in this tutorial.

Do I need a GPU to run Ollama?

No. Ollama runs on a normal CPU, but answers are slower. A supported NVIDIA or AMD GPU, or an Apple Silicon Mac, makes a big difference. If your computer has little memory, choose a smaller tag of the model from its page on ollama.com.

Is my data private when I use Ollama?

When you run a local model, your prompts are processed on your own machine and the API listens on localhost by default. Cloud models and anything you expose to the network are different, so check which model you are calling.

What is the difference between Ollama and vLLM?

Ollama is built to make running models on one computer easy: one install, one command, a simple API. vLLM is a serving engine for GPU servers that handles many users at once with high throughput. Learn with Ollama, then look at vLLM or SGLang when you need to serve a large model to many people.

Can I run Amazon Ergo or other huge models with Ollama?

Not on a typical laptop. Amazon Ergo's smallest official download is 626 GB, and Amazon lists SGLang and vLLM for self-hosting. Stick to small and mid-sized models for local learning.

Sources

Code checked against the ollama Python library 0.6.4 on December 2, 2026, using a local test server that mimics Ollama's chat API. Model names change over time; if gemma4 is renamed, pick any chat model from the Ollama library.

What to Try Next

Keep learning generative AI

Head back to the Generative AI & RAG track for the full learning path and the hands-on retrieval lab.

Back to the Generative AI Track