Generative AI Part 6: How to Run LLMs Locally with Ollama

Generative AI Part 6 banner: run LLMs locally with Ollama on localhost:11434 from the terminal, Python and Node.js
PART 6 Generative AI Series · DevDojo Run LLMs Locally with Ollama Free, private, offline AI on your own laptop $ ollama run Python app Node.js app Ollamalocalhost:11434 Llama Gemma Qwen Your PCCPU / GPUno cloud devdojo.co.in · Beginner friendly · Terminal + Python + Node.js examples
Series: Generative AI Part 6 of 30

What you should know first: read Part 5: Temperature, Top-p and Controlling Model Output and Part 3: Your First LLM API Calls. You only need a terminal and a laptop with at least 8 GB of RAM.

So far in this series every model we used lived in someone else’s data centre: you sent a prompt over the internet, paid per token and trusted the provider with your data. In this part you will learn how to run LLMs locally with Ollama, a free open-source tool that downloads open models such as Llama, Gemma and Qwen and runs them on your own computer. You will install Ollama, pull your first model, chat with it in the terminal, call it from Python and Node.js, stream answers, reuse your OpenAI code from Part 3 and even build your own custom model with a Modelfile. No API key, no bill, and it works offline.

Quick Summary
  • Ollama is a free tool that downloads and runs open models (Llama, Gemma, Qwen, Mistral, gpt-oss and more) on your own computer.
  • Install it, then use ollama pull llama3.2 to download a model and ollama run llama3.2 to chat with it in the terminal.
  • Ollama runs a local server at http://localhost:11434. Your apps talk to it with the ollama package (Python and JavaScript) or plain HTTP.
  • It also offers an OpenAI-compatible API at /v1, so your Part 3 code works locally by changing only the base URL.
  • Pick a model that fits your RAM: about 1–4B parameters for 8 GB, 7–8B for 16 GB, and bigger models need 32 GB or a good GPU.
  • Local models give you privacy, zero per-token cost and full control (temperature, top-k, seed, context size), but they are smaller and slower than top cloud models.
Full Generative AI roadmap (30 parts)

Beginner

  1. What Is Generative AI and How Do LLMs Work?
  2. Tokens, Context Windows and Model Parameters
  3. Your First LLM API Calls in Python and Node.js (OpenAI, Anthropic, Gemini)
  4. Prompt Engineering Basics: Roles, Instructions and Examples
  5. Temperature, Top-p and Controlling Model Output
  6. Run LLMs Locally with Ollama You are here
  7. Streaming Responses and Building a Simple Chat UI Coming soon
  8. Structured Outputs: Getting Reliable JSON from LLMs Coming soon

Intermediate

  1. Embeddings Explained: Turning Text into Vectors Coming soon
  2. Vector Databases: pgvector, Chroma and Pinecone Coming soon
  3. RAG Fundamentals: Retrieval-Augmented Generation Coming soon
  4. Document Loading and Chunking Strategies Coming soon
  5. Better RAG: Hybrid Search, Re-ranking and Query Rewriting Coming soon
  6. Function Calling and Tool Use Coming soon
  7. Conversation Memory and Long Context Management Coming soon
  8. Multimodal AI: Vision, Images and Audio Inputs Coming soon
  9. How Image Generation Works: Diffusion Models Basics Coming soon
  10. LangChain vs LlamaIndex: When to Use a Framework Coming soon
  11. Testing LLM Apps: Evals, Metrics and Test Sets Coming soon
  12. Cutting Cost and Latency: Caching, Batching and Model Choice Coming soon

Advanced

  1. Fine-Tuning vs Prompting vs RAG: Choosing the Right Tool Coming soon
  2. Fine-Tuning an Open Model with LoRA Coming soon
  3. Transformers Deep Dive: Attention Explained Simply Coming soon
  4. Reasoning Models and Thinking Time Coming soon
  5. Guardrails, Safety and Prompt Injection Defence Coming soon
  6. Monitoring and Tracing LLM Apps in Production Coming soon
  7. Serving Open Models: vLLM, Quantization and GPUs Coming soon
  8. Building a Production GenAI App End to End Coming soon
  9. Responsible AI: Privacy, Licensing and Bias Coming soon
  10. Final Project: Build Your Own AI Knowledge Assistant Coming soon

Why run LLMs locally?

In Part 3 you called OpenAI, Claude and Gemini over the internet. Those models are the smartest available, but every request costs money, needs an API key and sends your text to another company. A local LLM flips all of that. The model file sits on your disk and runs on your own CPU or GPU.

PrivacyCompany code, customer data or personal notes never leave your computer. Great for regulated work.
Zero per-token costExperiment as much as you like. Perfect for learning, testing prompts and batch jobs.
Works offlineCode on a train or flight. No network, no rate limits, no outages.
Full controlAll the sampling dials from Part 5 (temperature, top-k, seed) still work, plus context size.
Cloud API (Parts 3–5) Local model (this part) Your app Providerdata centre internet ✗ pay per token ✗ data leaves your machine ✗ needs internet + API key ✓ biggest, smartest models ✓ no hardware needed your laptop Your app Ollama ✓ free after download ✓ data never leaves your PC ✓ works offline, no API key ✗ smaller models, less smart ✗ speed depends on your RAM/GPU
Cloud APIs vs local models: local wins on privacy and cost, cloud wins on raw quality.

The trade-off is quality and speed. A 3-billion-parameter model on a laptop will not match the biggest cloud models at hard reasoning, but it is surprisingly good at summaries, simple Q&A, rewriting text and code help. Many real apps use both: a local model for cheap, private tasks and a cloud model for the hardest ones.

What is Ollama and how it works

Ollama is a free, open-source app for macOS, Windows and Linux that makes local models as easy as Docker made containers. It does three jobs for you:

  1. Downloads models from its library (ollama.com/library) in a compressed (quantized) format called GGUF, so an 8B model needs about 5 GB instead of 16 GB.
  2. Runs a local server on http://localhost:11434 that loads the model into RAM or GPU memory and answers requests.
  3. Gives you simple tools: a command-line chat, a REST API, official Python and JavaScript packages and an OpenAI-compatible endpoint.
ollama run (CLI) Python / Node.js Chat apps, IDEs HTTP requests Ollama serverlocalhost:11434loads & unloads models Model files~/.ollama/models (GGUF) Model in memorykept warm ~5 min GPUor CPU +RAM Answers stream back the same way, token by token
How Ollama works: one local server, many apps, models loaded from disk into RAM or GPU memory.
Open model vs open source: “open model” (or “open weights”) means you can download and run the model file. Each model still has its own licence, so check it on the model page before using it in a commercial product.

Install Ollama and run your first model

On macOS and Windows, download the installer from the official site and open it; Ollama then runs in the background (you will see its icon in the menu bar or system tray). On Linux, use the install script. Then pull a model and start chatting:

Terminal — install Ollama
# macOS / Windows: download the installer from https://ollama.com/download
# Linux: one-line install script
$ curl -fsSL https://ollama.com/install.sh | sh
$ ollama --version
# download a small model (about 2 GB) and chat with it
$ ollama pull llama3.2
$ ollama run llama3.2
# type a message, press Enter; type /bye to quit

The first ollama run takes a few seconds while the model loads into memory; after that, answers start almost instantly. If you skip ollama pull, ollama run downloads the model for you automatically. Here are the everyday commands you will use:

Terminal — manage models
$ ollama list            # models on your disk
$ ollama ps              # models loaded in memory right now
$ ollama run llama3.2 "Explain an API in one sentence"   # one-shot prompt
$ ollama show llama3.2   # size, context length, parameters
$ ollama stop llama3.2   # unload it from memory
$ ollama rm llama3.2     # delete it from disk
Tip: model names have tags after a colon. llama3.2 means the default tag (3B parameters); llama3.2:1b is the smaller 1B version. The tag tells you the size, and size tells you how much memory you need.

Choosing a model for your computer

The most common beginner mistake is downloading a model that is too big. A simple rule: a model compressed to 4 bits needs roughly 0.6–0.7 GB of memory per billion parameters, plus extra for the context window. So a 3B model needs about 2–3 GB, an 8B model about 5–6 GB and a 32B model about 20 GB. Click your setup below for safe picks:

Most student laptops. Stay with 1–4B parameter models and close heavy apps (Chrome tabs eat RAM too).

Start herellama3.2 (3B)
Tiny + fastllama3.2:1b, gemma3:1b
Good all-roundergemma3:4b, qwen3:4b

Expect a few words per second on CPU. Fine for learning and small tasks.

Typical developer laptop, including Apple Silicon Macs. 7–8B models are the sweet spot for quality and speed.

Chat + writingllama3.1:8b
Code + reasoningqwen3:8b
Vision toogemma3:4b (reads images)

Apple Silicon shares memory with its GPU, so Macs run these models smoothly.

Workstations and high-end Macs. You can try 12–32B models that feel much closer to cloud quality.

Strong all-roundergemma3:12b, qwen3:14b
Open reasoning modelgpt-oss:20b
Heaviergemma3:27b, qwen3:32b

Bigger models load slower; keep only one large model running at a time.

NVIDIA or AMD GPU. Ollama uses the GPU automatically when the model fits in its video memory (VRAM).

8 GB VRAM7–8B models
12–16 GB VRAM12–14B models, gpt-oss:20b
24 GB VRAMup to ~32B models

Run ollama ps: the PROCESSOR column shows how much of the model sits on the GPU vs the CPU.

Model names change quickly as new versions arrive, so treat these as starting points and browse the Ollama model library for the newest options. Look at the size tag and the “tools”, “vision” or “thinking” labels on each model page.

The local REST API

Everything Ollama does goes through its HTTP server, so any language that can send a request can use a local model. The two main endpoints are /api/generate (single prompt) and /api/chat (a list of messages with roles, exactly like Part 4). Set "stream": false to get one JSON reply instead of many small chunks:

api_chat.sh — devdojo-ollama — Visual Studio Code
devdojo-ollama › api_chat.sh
# Ollama runs a local REST API on port 11434
curl http://localhost:11434/api/chat -d '{
  "model": "llama3.2",
  "messages": [{ "role": "user", "content": "Say hello to DevDojo readers" }],
  "stream": false,
  "options": { "temperature": 0.2 }
}'
TERMINALOUTPUTPROBLEMSExample output – wording and numbers will differ on your machine
$ bash api_chat.sh
{"model":"llama3.2","created_at":"…","message":{"role":"assistant","content":"Hello, DevDojo readers! Happy coding and keep learning!"},"done":true,"done_reason":"stop","total_duration":…,"prompt_eval_count":…,"eval_count":…}
⎇ mainLn 7, Col 1Spaces: 4UTF-8LFShell Script

Click ▶ Run to see the shape of the JSON reply. The … parts are timing and token numbers that differ on every machine.

Notice that the reply has the same role and content shape you saw with cloud APIs, plus useful stats: prompt_eval_count (input tokens), eval_count (output tokens) and total_duration in nanoseconds.

Run LLMs locally with Ollama from Python and Node.js

For real apps, use the official ollama packages. They wrap the REST API with nice types, and the code looks almost the same in both languages. Install them first (and keep Ollama running in the background):

Terminal — devdojo-ollama
# Python
$ pip install -U ollama openai
# Node.js (ES modules, Node 18+)
$ npm install ollama openai

Now send a chat request with a system message, a user message and the sampling options you learned in Part 5. num_ctx sets the context window size in tokens and num_predict is the local version of “max tokens”:

2 files — devdojo-ollama — Visual Studio Code
devdojo-ollama › chat_local.py
# chat_local.py - talk to a local model with the official ollama package
from ollama import chat

response = chat(
    model="llama3.2",
    messages=[
        {"role": "system", "content": "You are a friendly coding tutor. Answer in 2 short sentences."},
        {"role": "user", "content": "What is a REST API?"},
    ],
    options={"temperature": 0.2, "top_p": 0.9, "seed": 42, "num_ctx": 4096, "num_predict": 120},
)

print(response.message.content)
print("tokens in:", response.prompt_eval_count, "| tokens out:", response.eval_count)
print(f"time: {response.total_duration / 1e9:.1f}s")
TERMINALOUTPUTPROBLEMSExample output – wording and numbers will differ on your machine
$ python chat_local.py
A REST API is a way for programs to talk to each other over HTTP using URLs and methods like GET and POST. For example, an app can send GET /users to a server and receive the list of users as JSON.
tokens in: <n> | tokens out: <n>
time: <seconds>s
⎇ mainLn 15, Col 1Spaces: 4UTF-8LFPython
devdojo-ollama › chat-local.mjs
// chat-local.mjs - talk to a local model with the official ollama package
import ollama from "ollama";

const response = await ollama.chat({
  model: "llama3.2",
  messages: [
    { role: "system", content: "You are a friendly coding tutor. Answer in 2 short sentences." },
    { role: "user", content: "What is a REST API?" },
  ],
  options: { temperature: 0.2, top_p: 0.9, seed: 42, num_ctx: 4096, num_predict: 120 },
});

console.log(response.message.content);
console.log("tokens in:", response.prompt_eval_count, "| tokens out:", response.eval_count);
console.log(`time: ${(response.total_duration / 1e9).toFixed(1)}s`);
TERMINALOUTPUTPROBLEMSExample output – wording and numbers will differ on your machine
$ node chat-local.mjs
A REST API is a way for programs to talk to each other over HTTP using URLs and methods like GET and POST. For example, an app can send GET /users to a server and receive the list of users as JSON.
tokens in: <n> | tokens out: <n>
time: <seconds>s
⎇ mainLn 15, Col 1Spaces: 2UTF-8LFJavaScript

Switch between the Python and Node.js tabs, then click ▶ Run to see the output.

OptionWhat it controlsTypical value
temperatureRandomness (Part 5)0.2 for facts, 0.8 for ideas
top_p / top_kCut unlikely tokens0.9 / 40
seedSame input + same seed = same outputany number, e.g. 42
num_ctxContext window in tokens (more = more memory)4096–8192
num_predictMaximum tokens to generate128–1024
stopStop sequences["\n\n"]
Watch the context size: Ollama uses a fairly small default context window to save memory. If the model seems to “forget” the start of a long document, raise num_ctx, but remember that a bigger context uses more RAM.

Streaming answers

Local models write a few words at a time. Instead of waiting for the full answer, stream it so users see text appear instantly (we will build a full chat UI with streaming in Part 7). Pass stream=True and loop over the chunks:

2 files — devdojo-ollama — Visual Studio Code
devdojo-ollama › stream_local.py
# stream_local.py - print the answer word by word as the model writes it
from ollama import chat

stream = chat(
    model="llama3.2",
    messages=[{"role": "user", "content": "Give me 3 short tips to learn Python."}],
    stream=True,
)

for chunk in stream:
    print(chunk.message.content, end="", flush=True)
print()
TERMINALOUTPUTPROBLEMSExample output – wording and numbers will differ on your machine
$ python stream_local.py
1. Practise a little every day, even 20 minutes.
2. Build small projects like a to-do app or a quiz.
3. Read other people's code and run it yourself.
⎇ mainLn 12, Col 1Spaces: 4UTF-8LFPython
devdojo-ollama › stream-local.mjs
// stream-local.mjs - print the answer word by word as the model writes it
import ollama from "ollama";

const stream = await ollama.chat({
  model: "llama3.2",
  messages: [{ role: "user", content: "Give me 3 short tips to learn Python." }],
  stream: true,
});

for await (const part of stream) {
  process.stdout.write(part.message.content);
}
process.stdout.write("\n");
TERMINALOUTPUTPROBLEMSExample output – wording and numbers will differ on your machine
$ node stream-local.mjs
1. Practise a little every day, even 20 minutes.
2. Build small projects like a to-do app or a quiz.
3. Read other people's code and run it yourself.
⎇ mainLn 13, Col 1Spaces: 2UTF-8LFJavaScript

Click ▶ Run; in a real terminal the text appears word by word.

Reuse OpenAI code with a local model

Already have code written with the OpenAI SDK from Part 3? Ollama speaks the same language at /v1. Change the base_url, pass any API key and use a local model name. This is a great way to develop and test for free, then switch to a cloud model in production by changing two lines:

2 files — devdojo-ollama — Visual Studio Code
devdojo-ollama › openai_local.py
# openai_local.py - reuse your OpenAI code from Part 3 with a local model
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:11434/v1",  # Ollama's OpenAI-compatible API
    api_key="ollama",                      # required by the SDK, ignored by Ollama
)

response = client.chat.completions.create(
    model="llama3.2",
    messages=[{"role": "user", "content": "Explain JSON to a beginner in one sentence."}],
    temperature=0.2,
)

print(response.choices[0].message.content)
TERMINALOUTPUTPROBLEMSExample output – wording and numbers will differ on your machine
$ python openai_local.py
JSON is a simple text format for storing data as key-value pairs, like {"name": "Asha", "age": 21}, that almost every programming language can read.
⎇ mainLn 15, Col 1Spaces: 4UTF-8LFPython
devdojo-ollama › openai-local.mjs
// openai-local.mjs - reuse your OpenAI code from Part 3 with a local model
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "http://localhost:11434/v1", // Ollama's OpenAI-compatible API
  apiKey: "ollama",                     // required by the SDK, ignored by Ollama
});

const response = await client.chat.completions.create({
  model: "llama3.2",
  messages: [{ role: "user", content: "Explain JSON to a beginner in one sentence." }],
  temperature: 0.2,
});

console.log(response.choices[0].message.content);
TERMINALOUTPUTPROBLEMSExample output – wording and numbers will differ on your machine
$ node openai-local.mjs
JSON is a simple text format for storing data as key-value pairs, like {"name": "Asha", "age": 21}, that almost every programming language can read.
⎇ mainLn 15, Col 1Spaces: 2UTF-8LFJavaScript

Same OpenAI SDK, local model. Compare the two tabs with your Part 3 code.

Good pattern: read base_url, api_key and the model name from environment variables. Then your app runs on Ollama in development and on a cloud model in production without code changes.

Build a custom model with a Modelfile

Typing the same system prompt and settings every time gets boring. A Modelfile is like a Dockerfile for models: it starts FROM a base model and saves your own defaults and personality under a new name. This does not train the model; it packages a prompt and settings so every app gets the same behaviour.

Modelfile — devdojo-ollama — Visual Studio Code
devdojo-ollama › Modelfile
# Modelfile - build your own "DevDojo Tutor" on top of llama3.2
FROM llama3.2

PARAMETER temperature 0.3
PARAMETER num_ctx 8192

SYSTEM """
You are DevDojo Tutor. Explain coding ideas to beginners
in simple English, with one short code example.
"""
TERMINALOUTPUTPROBLEMSExample output – layer hashes differ
$ ollama create devdojo-tutor -f Modelfile
gathering model components
using existing layer sha256:…
creating new layer sha256:…
writing manifest
success
⎇ mainLn 10, Col 1Spaces: 4UTF-8LFModelfile

Click ▶ Run to see what ollama create prints.

Terminal — use your custom model
$ ollama run devdojo-tutor "What is a variable?"
# it also works from code: model="devdojo-tutor"
$ ollama list

Common errors and fixes

Problem or errorLikely causeFix
ConnectionError / ECONNREFUSED 127.0.0.1:11434The Ollama server is not runningOpen the Ollama app, or run ollama serve in a separate terminal.
model "llama3.2" not found, try pulling it firstThe model is not downloaded or the name/tag is wrongRun ollama pull llama3.2 and check names with ollama list.
model requires more system memory than is availableModel too big for your RAMUse a smaller tag (e.g. llama3.2:1b), close other apps or lower num_ctx.
Answers are very slow (one word per second)Model running on CPU or partly swappedCheck ollama ps; pick a smaller model so it fits in GPU/unified memory.
Model forgets the start of a long textContext window too smallRaise num_ctx in options or in a Modelfile.
Another device on your network cannot connectOllama listens only on localhost by defaultSet OLLAMA_HOST=0.0.0.0 only on a trusted network and protect the port.
OpenAI SDK error: missing API keyThe SDK requires a key even for local usePass any string, e.g. api_key="ollama".

Best practices

  • Start small, scale up. Begin with a 1–4B model, check that answers are good enough, and only then try a bigger one.
  • Pin model tags in your code (for example llama3.2:3b), so an update to the default tag does not silently change your app.
  • Set a seed and low temperature for tests, so the same prompt gives the same answer on your machine.
  • Keep the server private. Port 11434 has no login, so never expose it to the internet without a proxy and authentication.
  • Use the OpenAI-compatible API plus environment variables, so you can switch between local and cloud models easily.
  • Check the licence of each open model before using it in a paid product.
  • Watch disk space. Models are big; remove old ones with ollama rm.

Practice task

Build a tiny “local model showdown”:

  1. Pull two models that fit your RAM (for example llama3.2:1b and llama3.2).
  2. Extend chat_local.py to loop over both models and ask the same three questions with seed=42 and temperature=0.2.
  3. Print each answer with eval_count and speed in tokens per second (eval_count / (eval_duration / 1e9)).
  4. Create a Modelfile for a “Git helper” that only answers Git questions, then test it with ollama run.
  5. Point your OpenAI code from Part 3 at Ollama using environment variables and run it without an API key.
Bonus: share your tokens-per-second results and laptop model in the comments, so other readers know what to expect.

FAQ: running LLMs locally with Ollama

Is Ollama free?

Yes. Ollama itself is free and open source, and the models in its library are free to download. Each model has its own licence, so check it for commercial use.

Can I run Ollama without a GPU?

Yes. Ollama runs on the CPU too. Small models (1–4B) work fine on most laptops with 8 GB of RAM; a GPU or Apple Silicon simply makes everything faster.

Does Ollama send my data to the internet?

No. When you run a local model, prompts and answers stay on your computer. Internet is needed only to download Ollama and the models.

Which is the best model for a beginner?

Start with llama3.2 (3B) on an 8 GB machine or an 8B model such as qwen3:8b or llama3.1:8b on 16 GB. Then try others from the library and compare.

Can I use Ollama with LangChain or other tools?

Yes. Most AI frameworks, editors and chat apps support Ollama directly or through its OpenAI-compatible API, which we will use in later parts of this series.

Where are the model files stored?

By default in ~/.ollama/models on macOS and Linux and in your user folder on Windows. You can change the location with the OLLAMA_MODELS environment variable.

Conclusion

You can now run LLMs locally with Ollama: install it, pull an open model that fits your computer, chat in the terminal, call it from Python and Node.js, stream answers, reuse your OpenAI code by changing the base URL and package your own assistant with a Modelfile. Local models will not replace the biggest cloud models for every task, but they are perfect for learning, privacy-sensitive work and free experiments. For every command and option, keep the official Ollama documentation handy.

Missed the previous part? Read Part 5: Temperature, Top-p and Controlling Model Output. Want to build something bigger with LLMs? Try our RAG tutorial with Python and pgvector.

Next part – Generative AI Part 7: Streaming Responses and Building a Simple Chat UI. Turn the streaming code from today into a real chat app with a web interface that shows answers word by word, works with both local and cloud models and remembers the conversation.

New posts every day on DevDojo

Follow the full Generative AI series – 30 parts from “what is an LLM” to building a production AI assistant. Bookmark devdojo.co.in and tell us in the comments which local model you liked most.

Share