Run LLMs Locally with Ollama: A Practical Guide

by Fahim Mahmud Chisti

Want to run an LLM (large language model) on your own machine instead of paying for a cloud API? Ollama downloads open models such as Llama 3 and runs them locally behind a simple command line and HTTP API. By the end of this guide you will have Ollama installed, a model answering prompts, a local API your apps can call, and a small RAG (chat-with-your-files) script.

Quick answer: Install Ollama, pull a small instruction-tuned model, and call it on http://localhost:11434. A 7–8B model in 4-bit quantization runs on a laptop with 8–16 GB of RAM, no GPU required.

  1. Install Ollama from ollama.com (or the Linux install script) and check ollama --version.
  2. Download a model, for example ollama pull llama3.
  3. Chat with it in the terminal: ollama run llama3.
  4. Call the local API from your code: POST http://localhost:11434/api/generate.
  5. Add an embedding model to answer questions from your own documents (RAG).
In this guide
  1. Why Run LLMs Locally with Ollama
  2. Before You Start: Hardware, Disk and Time
  3. Step 1: Install Ollama on macOS, Windows or Linux
  4. Step 2: Download a Model and Send Your First Prompt
  5. Step 3: Call the Local REST API from Your Apps
  6. Step 4: Control Output with System Prompts and Parameters
  7. Step 5: Chat with Your Own Files (Local RAG)
  8. Step 6: Test It End to End
  9. Speed It Up: Context, Quantization and Streaming
  10. Which Model Should You Use?
  11. Local Dev Patterns You Can Copy
  12. Troubleshooting: Common Ollama Problems
  13. Ollama Alternatives and How They Compare
  14. Guardrails for Real Projects
  15. Frequently Asked Questions
  16. Next Steps
  17. Official docs & trusted sources
Run LLMs locally with Ollama and Llama 3 today
Local-first AI: faster iteration, better privacy, fewer surprises.

Why Run LLMs Locally with Ollama

Ollama turns running an open model into one command, ollama run, and serves it on a local API. Compact instruction-tuned models such as Llama 3 8B follow instructions and help with code well enough for many everyday tasks on a normal laptop.

  • Privacy: prompts and documents stay on your machine.
  • Predictable cost: no per-token bill and no API rate limits; you pay in hardware and electricity.
  • Simple tooling: one command to pull, run and serve a model.
  • App building blocks: a REST API, an OpenAI-compatible endpoint, system prompts and embeddings for RAG.

The examples below use the llama3 model name. Any other model you pull works the same way: replace llama3 with its name (run ollama list to see what you have).

Before You Start: Hardware, Disk and Time

  • OS: macOS, Windows or Linux.
  • RAM: the model has to fit in memory. The default 8B Llama 3 build is a 4.7 GB file, so 8 GB of RAM is the practical minimum and 16 GB is comfortable; the 70B build is 40 GB and needs workstation-class memory.
  • Disk: about 5 GB for the default 8B download, 40 GB for 70B, plus the same again for every extra quantization you try.
  • GPU (optional): NVIDIA GPUs are used on Linux and Windows; Apple Silicon Macs use Metal automatically. Without a GPU, models run on the CPU, just more slowly.
  • Time: about 30 minutes, most of it waiting for the model download.
  • For the code examples: Node.js 18 or later (it has fetch built in) and, for the Bash helper, jq.

Start with a small, quantized model to confirm everything works, then try a larger one only if your task needs it.

Step 1: Install Ollama on macOS, Windows or Linux

Run the commands for your OS in a terminal (Terminal on macOS, PowerShell on Windows, your shell on Linux). Ollama also offers desktop installers on ollama.com.

# macOS: download the app from ollama.com, or use Homebrew
brew install ollama
ollama --version

# Windows: download the installer from ollama.com, then verify in PowerShell
ollama --version

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

If it worked, ollama --version prints the installed version number. If you are behind a corporate proxy, set the HTTPS_PROXY environment variable for the Ollama server so model downloads go through it.

Step 2: Download a Model and Send Your First Prompt

Ollama's model names point to sensible default builds. In the same terminal, pull a model and chat with it:

# Pull the model weights (first run may take a few minutes)
ollama pull llama3

# Chat interactively (type /bye to exit)
ollama run llama3

# Or pass a one-off prompt
ollama run llama3 "Write a 2-sentence summary of Ollama for a developer."

You should see a download progress bar, then a >>> prompt where you can type. The one-off form prints the answer and returns to your shell.

Want a specific size or quantization? Add a tag after the model name:

# Examples (tags change over time; see the model's Tags page on ollama.com)
ollama pull llama3:8b
ollama pull llama3:8b-instruct-q4_K_M
ollama run llama3:8b-instruct-q4_K_M

Quantization stores the model's weights with fewer bits, which cuts memory use for a small loss in quality. Q4 builds are a good starting point. The llama3 tag is the original 2024 release; newer family members such as llama3.1 and llama3.2 are pulled and run the same way.

Step 3: Call the Local REST API from Your Apps

Ollama runs an HTTP server on port 11434, so your apps call the model the way they would call a cloud provider. Run these commands in a terminal; if you start ollama serve yourself (for example after a Homebrew install), use a second terminal for the curl request.

# The desktop app and the Linux service already run the API server in the background.
# Start it yourself only if nothing is listening on port 11434:
ollama serve

# cURL example
curl http://localhost:11434/api/generate -d '{
  "model": "llama3",
  "prompt": "List 5 ways to optimize local LLMs",
  "stream": false
}'

The reply is a JSON object whose response field holds the model's answer, with "done": true at the end. To call the API from JavaScript, save this as ask.mjs and run node ask.mjs; it prints the answer:

const res = await fetch('http://localhost:11434/api/generate', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    model: 'llama3',
    prompt: 'Explain RAG in 2 lines',
    stream: false,
  }),
});
const json = await res.json();
console.log(json.response);

Step 4: Control Output with System Prompts and Parameters

Clear instructions and stable settings give more consistent answers:

  • System prompt: set tone, domain and limits once.
  • Temperature (how random the output is): 0.2–0.5 for factual tasks, higher for brainstorming.
  • Output length: cap it with the num_predict option for predictable latency.
  • Context window: num_ctx sets how many tokens of prompt and answer the model can see at once.

Send a body like this to POST /api/generate, either as the -d data in the curl command above or as the body in the fetch example:

{
  "model": "llama3",
  "system": "You are a concise technical writer. Avoid speculation.",
  "prompt": "Summarize Ollama in 60 words for a CTO.",
  "options": { "temperature": 0.3, "num_ctx": 4096, "num_predict": 200 },
  "stream": false
}

Step 5: Chat with Your Own Files (Local RAG)

Retrieval-Augmented Generation (RAG) finds the passages of your documents that match a question and passes them to the model, so answers come from your files rather than the model's memory.

  1. Embed documents (turn each text chunk into a vector of numbers) and store the vectors, for example in SQLite, FAISS or Chroma.
  2. When a question arrives, retrieve the top few chunks by similarity.
  3. Build a prompt with those chunks as context and call Ollama.

The minimal version below keeps the vectors in memory and uses Ollama for both embedding and answering. First pull an embedding model with ollama pull nomic-embed-text, then save the script as rag.mjs and run node rag.mjs:

// rag.mjs (run with: node rag.mjs)
const OLLAMA = 'http://localhost:11434';

async function embed(texts) {
  const res = await fetch(`${OLLAMA}/api/embed`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ model: 'nomic-embed-text', input: texts }),
  });
  return (await res.json()).embeddings;
}

function cosine(a, b) {
  let dot = 0, normA = 0, normB = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }
  return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}

// 1) Index: embed your text chunks (extract text from PDFs with a PDF library first)
const chunks = [
  'API keys are rotated every 90 days by the platform team.',
  'To rotate a key: create a new key, deploy it, then revoke the old one.',
  'On-call engineers are paged through the incident channel.',
];
const vectors = await embed(chunks);

// 2) Retrieve: rank chunks by similarity to the question
const question = 'How do we rotate API keys?';
const [questionVector] = await embed([question]);
const context = chunks
  .map((text, i) => ({ text, score: cosine(questionVector, vectors[i]) }))
  .sort((a, b) => b.score - a.score)
  .slice(0, 2)
  .map((chunk) => chunk.text);

// 3) Generate: answer from the retrieved context only
const prompt = `Answer from the context only.\n\nContext:\n${context.join('\n---\n')}\n\nQuestion: ${question}`;
const res = await fetch(`${OLLAMA}/api/generate`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ model: 'llama3', prompt, stream: false }),
});
const { response } = await res.json();
console.log(response);

It should print an answer based on the two key-rotation sentences, not the on-call one. Keep real chunks small (roughly 300–800 tokens) with a little overlap, and show which source each answer came from. Before you put RAG in front of users, work through the RAG architecture checklist for chunking, evaluation and access control.

Step 6: Test It End to End

  1. Run ollama list. Your chat model and nomic-embed-text should both be listed.
  2. Open http://localhost:11434 in a browser. It should say that Ollama is running.
  3. While a prompt is running, run ollama ps in another terminal. The Processor column shows where the model is loaded: 100% GPU means fully on the GPU, a CPU/GPU split means part of it is in system memory.
  4. Run node rag.mjs again and change the question to check that answers follow the context.

Speed It Up: Context, Quantization and Streaming

Local speed depends on model size, quantization, context length and your CPU or GPU.

  • Quantization: start with Q4 for speed; try Q5 or Q6 if quality matters more.
  • Context window: use the smallest num_ctx that fits your prompts. Ollama's default is 4096 tokens, and longer prompts are cut off unless you raise it.
  • Streaming and queueing: stream tokens ("stream": true) so users see output immediately, and queue API requests instead of firing them all at once.
  • Machine: close other memory-heavy apps and use a high-performance power mode on laptops.

Rule of thumb: prototype with a 7–8B model and step up only if your task clearly benefits.

Which Model Should You Use?

  • General assistant, coding help, docs Q&A: a small instruction-tuned model such as llama3 or a newer Llama 3.x release; 70B-class models only if you have the memory.
  • Light hardware: other small 7B-class models in the Ollama library, such as Mistral 7B.
  • Code work: code-tuned variants, where available, are better at refactors and generation.
  • Images: pick a vision-capable model from the library and check its model card.

Model line-ups change quickly. Check the Ollama model library for current options and their sizes before you download.

Local Dev Patterns You Can Copy

1) Ask about a file from the terminal

Paste this function into your shell (Bash or Zsh) or add it to your shell profile, then run it from your project folder. It prints the model's explanation of the file.

# Bash: ask a question about one file (requires jq)
# jq builds the JSON, so quotes and newlines in the file cannot break the request
ask() {
  local file="$1"; shift
  jq -n --arg prompt "$*" --rawfile code "$file" \
    '{model: "llama3", prompt: ($prompt + "\n\n" + $code), stream: false}' |
    curl -s http://localhost:11434/api/generate -d @- |
    jq -r .response
}

ask src/auth/session.js "Explain this file in two bullets for a new hire"

2) VS Code task: docstring helper

Add this to .vscode/tasks.json in your project, then run it from Terminal → Run Task.

// .vscode/tasks.json
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Docstring with Llama3",
      "type": "shell",
      "command": "node scripts/docstring.js ${file}"
    }
  ]
}

Here scripts/docstring.js is your own script: read the file passed as an argument and send it to /api/generate as in the fetch example above.

3) Browser console snippet for quick prompts

Paste this into the developer console of a page served from localhost, then call await localLLM("your prompt").

async function localLLM(prompt) {
  const r = await fetch('http://localhost:11434/api/generate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ model: 'llama3', prompt, stream: false }),
  });
  const j = await r.json();
  return j.response;
}

By default Ollama only accepts cross-origin browser requests from pages served on localhost or 127.0.0.1, so run this in the console of your local dev app. Other origins have to be added with the OLLAMA_ORIGINS environment variable; do not set it to *, which would let any website you visit call your local models.

Troubleshooting: Common Ollama Problems

  • curl says "connection refused" on port 11434: the server is not running. Open the desktop app, or run ollama serve in its own terminal.
  • ollama serve says the address is already in use: the app or the Linux service is already serving the API. Skip ollama serve and send your requests.
  • The API returns a "model not found" error: the name in your request does not match a pulled model. Run ollama list and use the exact name and tag, or pull the model first.
  • Download stalls: behind a corporate proxy, set HTTPS_PROXY for the server and retry the pull.
  • Out of memory or very slow tokens: switch to a smaller model or a more compressed quantization, lower num_ctx, and check ollama ps to see whether the model spilled onto the CPU.
  • Anything else: read the server log. On macOS run cat ~/.ollama/logs/server.log; on Linux run journalctl -u ollama --no-pager.

Ollama Alternatives and How They Compare

  • llama.cpp: the C/C++ engine behind many local tools; the most control, but more do-it-yourself.
  • LM Studio: a desktop app for downloading and chatting with models; good if you prefer a GUI to the terminal.
  • Text Generation WebUI: many features and plugins; heavier to set up, flexible for power users.

Ollama's strengths are simplicity and a clean local API. If you need more knobs or a GUI, use one of these alongside it.

Guardrails for Real Projects

  • Version your prompts: document system prompts and keep old versions so results are reproducible.
  • Ground answers: add retrieval and citations instead of relying on the model's memory for policy-sensitive answers.
  • Stream output: perceived speed matters more than raw throughput.
  • Re-test on upgrades: keep a set of reference prompts and compare outputs when you change model or quantization.

Frequently Asked Questions

Do I need a GPU to run Llama 3 locally?

No. A modern CPU can run 7–8B quantized models such as the default Llama 3 build; it is just slower. A GPU, or the Metal acceleration on Apple Silicon, speeds up responses a lot, but nothing in this guide requires one.

Which model size should I start with?

Start with a 7–8B instruction-tuned model in a Q4 quantization. It fits in 8–16 GB of RAM and is fast enough to iterate with. Move to a larger model only when you can show that your task needs better answers.

Can I call a local Ollama model like the OpenAI API?

Yes. Besides its native REST API, Ollama serves OpenAI‑compatible endpoints under http://localhost:11434/v1 (chat completions, embeddings, and more), so the OpenAI SDKs work when you point their base URL there and pass any placeholder API key.

Is running an LLM locally safe for sensitive data?

It keeps prompts off third-party servers, but you still need normal OS and app security. Ollama's API has no authentication and listens on 127.0.0.1 by default; do not expose port 11434 to a network without putting your own auth in front of it.

When should I still use a cloud model?

Use the cloud when you need models too large for your hardware, elastic scaling for many users, or a managed service level. Many teams run small local models for development and private data, and call a cloud model for the hardest tasks.

Next Steps

With a model answering on localhost:11434, you can build on it. Give it tools and a task loop in how to set up an AI agent locally, or put it behind a chat interface with the Telegram AI chatbot tutorial. For the bigger picture of tools, memory and guardrails, start from the AI agents developer guide.

Official docs & trusted sources

all_in_one_marketing_tool