You’re on a train with no Wi-Fi, a half-finished script, and a question you’d normally paste into a chatbot. With Ollama installed, that question goes to a model living on your own laptop instead.

No API key. No bill. No prompt leaving your machine.

This guide shows you how to run a local AI model with Ollama and call it from Python, from a clean install to a working script that streams answers. Plan on about 15 minutes, plus download time for the model.

Key Takeaways

  • Ollama installs in one step, pulls models with one command, and serves them on a local API at port 11434.
  • A 3B to 8B parameter model is the realistic ceiling for most laptops with 8 to 16 GB of RAM.
  • The official ollama Python package lets you chat, stream, and request structured output in a few lines.

What You Need Before You Start

You need a laptop running macOS, Windows, or Linux, Python 3.8 or newer, and free disk space for the model. Small models are around 2 GB; 8B models run roughly 4 to 5 GB when quantized. Check the model page in the Ollama library for exact sizes.

RAM matters more than your CPU. Ollama’s own documentation suggests at least 8 GB for 7B class models and 16 GB for 13B class models. A dedicated GPU speeds things up, but Apple Silicon Macs and plain CPUs work fine for learning.

Step 1: Install Ollama

Download the installer for your operating system from ollama.com and run it. On Linux, the site gives you a one-line install script. Afterward, open a terminal and run ollama --version to confirm it works.

Ollama starts a background service that listens on localhost:11434. That service is the whole trick: every model you pull is served through one local HTTP API, and the Python library simply talks to it.

The common screw-up here is a terminal that was open before installation. It won’t see the new command, so close it and open a fresh one.

Step 2: Pull and Run Your First Model

Run ollama pull llama3.2 to download Meta’s Llama 3.2, which ships in a 3B size that suits modest laptops. Then run ollama run llama3.2 and type a question. You’ll get an answer in the terminal, and /bye exits.

Pulling is separate from running, and that’s useful. You can download several models, then switch between them by name. Run ollama list to see what’s on disk and ollama rm modelname to reclaim space.

Which model should a beginner pick?

Start with Llama 3.2 3B if you have 8 GB of RAM, or an 8B model such as Llama 3.1 8B if you have 16 GB. Both are available in the Ollama library. For code questions, try a coding model like Qwen2.5 Coder, also listed there.

My advice: stay small until your script works. A fast 3B model teaches you the API in seconds per call, while a sluggish 13B model teaches you patience. Scale up once the plumbing is solid.

Step 3: Install the Ollama Python Library

Create a virtual environment, then run pip install ollama. The package is Ollama’s official Python client, maintained in the project’s GitHub repository. It wraps the local REST API so you don’t write raw HTTP requests.

Keep the Ollama app running while you code. If the service is stopped, your script raises a connection error, which is the most frequent first-day failure. Start it by launching the app, or run ollama serve on Linux.

Step 4: Write Your First Python Script

Create a file called chat.py and call ollama.chat() with a model name and a list of messages. The response holds the reply under response["message"]["content"]. That’s a complete local chatbot call.

import ollama

response = ollama.chat(
    model="llama3.2",
    messages=[{"role": "user", "content": "Explain list comprehensions in two sentences."}],
)
print(response["message"]["content"])

Run it with python chat.py. The first call is slower because Ollama loads the model into memory. By default it keeps the model loaded for about five minutes, so later calls feel much quicker.

If you’ve built a ChatGPT-powered app before, this will look familiar. Our post on coding a Python application that uses ChatGPT follows the same message structure, so swapping a hosted model for a local one is mostly a one-line change.

Step 5: Stream Responses So the App Feels Fast

Pass stream=True to get tokens as they’re generated instead of waiting for the full answer. Streaming doesn’t make the model faster, but it makes the wait feel short, which matters on a laptop generating perhaps a handful to a few dozen tokens per second.

stream = ollama.chat(
    model="llama3.2",
    messages=[{"role": "user", "content": "Write a haiku about debugging."}],
    stream=True,
)
for chunk in stream:
    print(chunk["message"]["content"], end="", flush=True)

Each chunk is a small piece of the reply. Forgetting flush=True is the classic mistake; your output appears all at once at the end and you assume streaming is broken.

Step 6: Keep Conversation Memory

Ollama’s chat endpoint is stateless, so you must resend the whole conversation each time. Store messages in a list, append the user turn, call the model, then append the assistant reply. Without this, the model forgets everything between calls.

history = []
while True:
    user = input("You: ")
    history.append({"role": "user", "content": user})
    reply = ollama.chat(model="llama3.2", messages=history)
    text = reply["message"]["content"]
    history.append({"role": "assistant", "content": text})
    print("Bot:", text)

There’s a cost. Every turn makes the prompt longer, and each model has a context window, a cap on how many tokens it can consider at once. Trim old turns when the list grows. For a deeper build, see our walkthrough on building an intelligent chatbot with Python.

Step 7: Use the REST API and Structured Output

You can skip the Python package entirely and POST JSON to http://localhost:11434/api/chat with the requests library. That’s handy when you work in a framework like FastAPI and want one fewer dependency.

Newer Ollama releases also support structured outputs, where you pass a JSON schema through the format parameter and the model’s reply is constrained to match it. Ollama announced this feature in its blog in late 2024, and it pairs well with Pydantic for validating the result. For anything that parses model output into code, this beats begging the model to “reply only in JSON.”

If you’re wrapping a model in a web service, our piece on FastAPI as a web framework covers the server side.

How Much RAM Do You Need to Run an LLM Locally?

For a 7B or 8B model in the default 4-bit quantization, plan on 8 GB of free memory at the very least, and 16 GB of total system RAM for comfort. Smaller 1B to 3B models run in far less. Bigger models need proportionally more, so a 13B model wants about 16 GB free.

Quantization is the reason this works at all. It stores model weights in fewer bits, shrinking the file and memory footprint at a small cost in answer quality. If a model doesn’t fit in memory, your system swaps to disk and generation crawls, so pick a smaller one rather than fighting it.

Is a Local Model Better Than ChatGPT or Claude?

No, not for hard reasoning or long, complicated tasks. A 3B or 8B model on a laptop is noticeably weaker than the frontier hosted models, and I’d say so plainly. If you need the best answer, use a hosted one; we compare them in ChatGPT vs Claude.

Local wins on other axes. Your data stays on your machine, there’s no per-token cost, it works offline, and you can run a thousand test prompts without watching a bill. For summarizing private notes, drafting commit messages, classifying text, or prototyping, a small local model is often enough. Choose local for privacy and experimentation, and hosted for peak quality.

Where Local Models Fit in Real Projects

The strongest beginner project is retrieval over your own documents. You embed files, store the vectors, and feed the best matches to the model. Ollama can serve embedding models such as nomic-embed-text, and you can store the vectors in Chroma, which is a good first choice as covered in our vector databases guide.

Other solid uses include a private code explainer, a log summarizer, and automation glue. If that last one appeals, read how to start with AI automation, then point the workflow at your local endpoint. As of 2026, tools like n8n let you call a custom HTTP endpoint, which includes Ollama.

Common Mistakes and Troubleshooting

Most failures come from five causes, and each has a quick fix.

  • Connection refused: the Ollama service isn’t running. Launch the app or run ollama serve.
  • Model not found: you used a name you never pulled. Check ollama list and spell the tag exactly.
  • Painfully slow output: the model is too large for your RAM. Drop to a smaller size or a lower quantization.
  • Answers cut off or forgetful: you’ve hit the context window. Trim history or raise num_ctx in the options, knowing it uses more memory.
  • Port conflict: something else uses 11434. Set the OLLAMA_HOST environment variable to a different address.

One more habit: pin the model tag in your code, such as llama3.2:3b, rather than relying on the default. Defaults can change, and your results will change with them.

Your Next Step

Pull one small model tonight, run the three scripts above, and break them on purpose. Shrink the model, lengthen the history, kill the service. You’ll learn more from those failures than from any tutorial, this one included. Once you’re comfortable, add a document folder and build the retrieval project; for wider context on where this is heading, browse our roundup of trending AI tools for programming.

FAQ

Is Ollama free?

Yes, Ollama is free and open source, and the models in its library are free to download. Each model carries its own license, so check the terms on its library page before using it commercially.

Can I run Ollama without a GPU?

Yes. Ollama falls back to your CPU, and small models of 1B to 3B parameters are usable that way. Expect slower generation than on a GPU or Apple Silicon.

Does Ollama work offline?

It does, once a model is downloaded. You need internet only to pull models or install updates, so your Python scripts can run on a plane.

How do I choose a model size?

Match it to your RAM. Use roughly 3B parameters for 8 GB machines and up to 8B for 16 GB machines, then move up only if speed stays acceptable.

Is my data private with Ollama?

Prompts are processed on your own machine and sent to no hosted API. Privacy still depends on your setup, so avoid exposing the port to a network without protection.

Facebook Comments