The short answer: Ollama is a free tool that downloads open-weight language models and runs them on your own machine behind a local HTTP API on port 11434. Install it, run
ollama runwith a model name to chat, and point your code athttp://localhost:11434, either through Ollama's own API or its OpenAI-compatible endpoint at/v1/. Pick a model that fits your RAM or GPU memory, raise the context length for longer prompts, and keep the server bound to localhost unless you've deliberately secured it. Local models are great for privacy, offline work, prototyping and cheap bulk jobs; hosted frontier models still win on the hardest reasoning tasks.
A few years ago, running a capable language model on your own computer meant compiling inference code, hunting for weight files and fighting with GPU drivers. Today it's one install and one command. That change has quietly opened up a lot of useful work: summarising private documents that can't leave the building, building features on a plane, running thousands of classification jobs without an API bill, and simply learning how these models behave without watching a meter tick.
Ollama is one of the most popular ways to do it. It packages model download, quantised weights, a model runner and an HTTP server into a single tool that works on macOS, Windows and Linux. This guide covers how to get started, how to choose a model your hardware can actually run, how to call it from code (including from apps built for the OpenAI API), how to customise models, the settings that matter for performance, and the security mistakes to avoid.
The job Ollama does
Ollama sits between you and the model files. When you ask for a model, it downloads the weights from its library, stores them locally, loads them into memory when needed (on the GPU if you have a supported one, otherwise on the CPU), and serves them through a local API. Models stay loaded for a short while after use, so follow-up requests are fast, then unload to free memory.
The important point for developers is the API. Anything you can do from the command line, you can do from code over HTTP on localhost:11434. That makes a local model a drop-in component for scripts, internal tools and app prototypes.
Getting started in five minutes
Download the installer for your operating system from ollama.com (on Linux there's a one-line install script). Once installed, the server runs in the background. Then, in a terminal:
# Download a model (if needed) and start chatting with it
ollama run gemma4
# Other everyday commands
ollama pull gemma4 # download or update a model without chatting
ollama ls # list the models you have downloaded
ollama ps # show which models are loaded right now
ollama stop gemma4 # unload a model from memory
ollama rm gemma4 # delete a model from disk
The model library on Ollama's site lists what's available, with sizes and variants for each model family. Model names change often as new releases arrive, so check the library rather than relying on any particular name in a tutorial, including this one.
Choosing a model your hardware can run
The single biggest factor in a good local experience is matching the model to your memory. A model has to fit in GPU memory (VRAM) to run quickly; if it doesn't fit, part of it runs on the CPU and generation slows down dramatically.
Model sizes are usually given in billions of parameters, and the memory needed depends on both the parameter count and the quantisation: how many bits are used to store each weight. Most models in Ollama's library are offered in quantised form, typically around 4 bits per weight by default, which shrinks them to roughly a quarter of their full-precision size at a small cost in quality. As a rough rule of thumb, a 4-bit model needs a bit over half a gigabyte of memory per billion parameters for the weights, plus extra for the context.
| Model size (4-bit) | Rough weight memory | Typical hardware |
|---|---|---|
| 1 to 4 billion | About 1 to 3 GB | Most laptops, even CPU-only |
| 7 to 14 billion | About 5 to 9 GB | 8 to 16 GB GPU, or Apple silicon with 16 GB or more |
| 25 to 35 billion | About 15 to 22 GB | 24 GB GPU, or Apple silicon with 32 GB or more |
| 70 billion and above | 40 GB and up | Multiple GPUs or high-memory workstations |
These are approximations for planning, not guarantees; the exact figures depend on the model architecture and quantisation level, and Ollama's library shows each variant's download size. Apple silicon Macs are a special case worth knowing about: their unified memory is shared between CPU and GPU, so a Mac with plenty of RAM can run surprisingly large models.
Start smaller than you think you need. A small model that responds instantly is often more useful for development than a large one that takes a minute per answer, and you can move up once you know what quality your task requires.
Picking by task, not just size
- General chat and summarisation: a mid-sized general instruction-tuned model.
- Coding: a code-specialised model, or a general model known to be strong at code.
- Embeddings for search and RAG: a dedicated embedding model, which is small and fast. The guide to choosing an embedding model covers how to evaluate one.
- Images: a vision-capable model if you need to describe or extract information from pictures.
- Tool calling and agents: a model the library marks as supporting tools, with a long context.
Calling Ollama from code
Ollama's native API has endpoints such as /api/chat for conversations and /api/generate for single prompts. Responses stream by default as a sequence of JSON objects; set "stream": false for a single response.
const res = await fetch("http://localhost:11434/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "gemma4",
stream: false,
messages: [
{ role: "system", content: "You summarise support tickets in two sentences." },
{ role: "user", content: ticketText },
],
}),
});
const data = await res.json();
console.log(data.message.content);
Official client libraries for JavaScript and Python wrap the same API if you'd rather not write requests by hand.
Using the OpenAI-compatible endpoint
Ollama also exposes an OpenAI-compatible API under http://localhost:11434/v1/. That means many tools and libraries built for OpenAI's API can talk to a local model by changing two settings: the base URL and the model name. The client libraries require an API key value, but Ollama ignores it, so any placeholder works.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "http://localhost:11434/v1/",
apiKey: "ollama", // required by the client library, ignored by Ollama
});
const completion = await client.chat.completions.create({
model: "gemma4",
messages: [{ role: "user", content: "Write a haiku about local inference." }],
});
console.log(completion.choices[0].message.content);
Compatibility covers the common features, such as chat completions, streaming and, for capable models, tool calling and JSON output, but not every parameter of every endpoint. Test the specific features your app depends on before assuming a hosted-to-local swap will behave identically.
Context length: the setting most people miss
The context length (how many tokens of prompt and conversation the model can consider at once) has a big effect on what a local model can do. Ollama chooses a default based on available memory. According to its documentation, the default is 4,096 tokens on machines with under 24 GiB of VRAM, 32,000 tokens with 24 to 48 GiB, and 256,000 tokens with 48 GiB or more.
A 4,096-token default is fine for short chats but too small for summarising long documents, RAG with several retrieved chunks, or coding agents that read many files. When the input exceeds the context, older content is dropped, and the model quietly answers from a partial view. Ollama's documentation recommends at least 64,000 tokens for agents, web search and coding tools.
You can raise the limit globally with the OLLAMA_CONTEXT_LENGTH environment variable, per model in a Modelfile with PARAMETER num_ctx, or per request through the API's options. Larger contexts use more memory for the key-value cache, so a model that fits comfortably at 4,096 tokens may spill onto the CPU at 64,000. Check ollama ps after a request: it shows how much of the model is running on GPU versus CPU, which is the quickest way to spot this.
Customising models with a Modelfile
A Modelfile is a short text file that defines a custom model on top of an existing one: a base model, parameters and a system prompt. It's a convenient way to package a configuration your team can share.
FROM gemma4
PARAMETER temperature 0.2
PARAMETER num_ctx 32768
SYSTEM """
You are a release-notes assistant. Given a list of merged pull requests,
write concise, user-facing release notes grouped by Added, Changed and Fixed.
"""
ollama create release-notes -f Modelfile
ollama run release-notes
The new model shares the base model's weights on disk, so creating variants is cheap. Other instructions let you set a custom prompt template or apply adapter weights from fine-tuning, though most teams only need FROM, PARAMETER and SYSTEM.
Performance tuning that actually helps
- Fit the model in GPU memory. This matters more than any other setting. If
ollama psshows a CPU and GPU split, choose a smaller model, a smaller quantisation or a shorter context. - Keep models loaded when you need speed. By default a model stays in memory for five minutes after its last use. The
keep_aliverequest option (or theOLLAMA_KEEP_ALIVEvariable) extends that, which avoids reload delays for services that are called sporadically. - Consider KV cache quantisation for long contexts. The key-value cache defaults to 16-bit precision. The
OLLAMA_KV_CACHE_TYPEsetting can store it at lower precision to fit longer contexts in the same memory, at some cost in quality; measure on your task before relying on it. - Batch offline work sensibly. For bulk jobs, run a steady stream of requests rather than hundreds in parallel. Ollama can serve some requests concurrently, but a single machine saturates quickly, and queueing gives more predictable throughput.
- Use the right model for each step. A small, fast model for classification or routing, and a larger one only where quality demands it.
Security: keep it on localhost
By default the Ollama server binds to 127.0.0.1, so only programs on the same machine can reach it. That's the right default. You can change the bind address with OLLAMA_HOST, for example to share a GPU machine with your team, but the API has no built-in authentication. Exposing it on a network interface means anyone who can reach that port can run models on your hardware, pull new models and use your compute.
If you need remote access, put it behind something that adds authentication and encryption: a reverse proxy with auth, a VPN or a private network such as a tailnet. Never expose port 11434 directly to the internet. The OLLAMA_ORIGINS setting controls which browser origins may call the API; leave it restrictive unless a specific web app needs access.
Two more things are worth remembering. Model files are downloaded from a library, so stick to sources you trust, as you would with any dependency. And a local model is still a language model: if it processes untrusted text and has access to tools, the risks described in the guide to prompt injection apply just as much as they do to hosted models.
Local models: strengths and limits
Running models locally has real strengths, and real limits. Being honest about both saves frustration.
Local models shine when:
- Data can't leave your machine or network for privacy, contractual or regulatory reasons.
- You need to work offline or in restricted environments.
- You're running large volumes of simple tasks (classification, extraction, tagging, embeddings) where per-token API costs add up.
- You're prototyping and want fast, free iteration.
- You want to learn how models behave, including how sampling settings and prompts change outputs.
Hosted models are usually better when:
- The task needs the strongest available reasoning, coding or long-document understanding.
- You need to serve many concurrent users with consistent latency without buying and running hardware.
- You want managed features such as large-scale batch processing, prompt caching or very long context windows without tuning memory yourself.
Many teams use both. A common pattern is to develop and test against a local model, run high-volume simple tasks locally, and send the hardest requests to a hosted model. If you take this route, run the same evaluation set against both, as described in the guide to testing LLM features with evals, so you know exactly where the local model falls short.
A practical example: private document Q&A
To see how the pieces fit together, consider a small internal tool that answers questions about a folder of private documents, with nothing leaving the machine.
- Embed the documents locally. Pull a small embedding model, split the documents into chunks, and call Ollama's embeddings endpoint for each chunk. Store the vectors in a local database; Postgres with pgvector works well, as covered in the guide to vector search with pgvector, and so does SQLite with a vector extension for single-user tools.
- Retrieve for each question. Embed the question with the same model and fetch the most similar chunks.
- Answer with a local chat model. Send the question and retrieved chunks to a chat model, with a context length large enough to hold them, and instructions to answer only from the provided text and cite which chunk each claim comes from.
- Measure. Write a couple of dozen questions with known answers and check retrieval and answer quality. If retrieval misses, the debugging steps in the guide on why RAG chatbots give bad answers apply unchanged.
The whole system runs on one machine, costs nothing per query, and works with the network cable unplugged. For a team handling sensitive documents, that's a genuinely different set of trade-offs from a hosted service.
Running Ollama in Docker and CI
Ollama publishes an official Docker image, which is handy for reproducible setups, shared GPU servers and automated tests. Run it with a volume for the model directory so downloads persist between container restarts, and with GPU access enabled if your host supports it. Without a GPU, the container still works on the CPU, just more slowly.
In CI, a small local model can be useful for tests that exercise your LLM integration code (request formatting, streaming, parsing, tool-call handling) without calling a paid API or leaking test data. Keep those tests focused on your code's behaviour rather than on exact model outputs, which vary. Cache the model download between CI runs, since pulling several gigabytes on every build is slow.
Troubleshooting common problems
- Responses are very slow. The model probably doesn't fit in GPU memory. Check
ollama ps, then try a smaller model or a shorter context. - The model ignores the start of long inputs. The context length is too small for your prompt. Raise
num_ctxorOLLAMA_CONTEXT_LENGTH. - Connection refused from another machine or a container. The server is bound to localhost by default. Bind it deliberately (and securely), or, from Docker, use the host's address rather than
localhost. - The first request after a pause is slow. The model was unloaded after the keep-alive period. Increase
keep_alivefor services that need consistent latency. - Output quality is lower than expected. Check that you're using an instruction-tuned variant, try a larger model or a higher-precision quantisation, and lower the temperature for factual tasks.
- A browser app can't reach the API. Cross-origin requests are restricted; configure
OLLAMA_ORIGINSfor that app's origin.
Structured output and tool calling locally
Many real applications need more than free-form text: they need JSON that matches a schema, or a model that can call functions. Ollama supports both for models that are capable of them.
For structured output, the API's format parameter accepts either "json" or a JSON Schema, and the model's output is constrained to match. That's much more reliable than asking for JSON in the prompt and hoping. Smaller local models benefit from this even more than large hosted ones, because they're more likely to drift from a requested format on their own. Validate the parsed result in your code anyway, as described in the guide to getting reliable JSON from LLMs.
For tool calling, you pass tool definitions with the chat request, and a capable model responds with tool calls for your code to run. The quality of tool use varies a lot between local models, more than it does among top hosted models, so test your specific tools and expect to simplify them: fewer tools, clearer descriptions and smaller argument schemas all help smaller models choose correctly.
Keeping models up to date
Open-weight models improve quickly, and the same model name in Ollama's library can be updated with fixes or better quantisations. Running ollama pull on a model you already have fetches the latest version and only downloads the parts that changed. For anything you depend on, such as a team's shared Modelfile or a CI test, note which model and tag you validated against, and re-run your evaluation set after updating, because a newer version can change outputs even when it's better overall. Periodically run ollama ls and remove models you no longer use with ollama rm; model files are several gigabytes each, and disk space disappears quickly when you're trying out new releases.
Frequently asked questions
What is Ollama used for?
Ollama is used to download and run open-weight language models on your own computer. It provides a command-line interface for chatting with models and a local HTTP API on port 11434, so scripts and applications can use local models for chat, summarisation, coding help, embeddings and more without sending data to a hosted service.
How much RAM do I need to run an LLM locally?
It depends on the model size and quantisation. With common 4-bit quantisation, small models of 1 to 4 billion parameters need only a few gigabytes, 7 to 14 billion parameter models need roughly 5 to 9 GB for the weights, and larger models need much more. The model should fit in GPU memory for good speed, plus extra memory for the context.
Is Ollama compatible with the OpenAI API?
Yes, for common features. Ollama exposes an OpenAI-compatible API at localhost:11434/v1/, so many OpenAI client libraries and tools work by changing the base URL and model name. An API key value is required by the client libraries but ignored by Ollama. Not every parameter is supported, so test the features you rely on.
Can I use Ollama for RAG and embeddings?
Yes. Ollama can run dedicated embedding models through its API, which you can use to embed documents and queries for retrieval, and a chat model to answer questions from the retrieved text. Raise the context length so the retrieved chunks fit, and evaluate retrieval quality on real questions.
Is it safe to expose Ollama on my network?
Not directly. Ollama binds to localhost by default and its API has no built-in authentication, so exposing port 11434 lets anyone who can reach it use your models and hardware. For remote access, put it behind a reverse proxy with authentication, a VPN or a private network, and never expose it directly to the internet.
The takeaway
Running a language model locally used to be a project. With Ollama it's a command, and the local API makes those models easy to use from real code. Match the model to your memory, raise the context length for anything longer than a chat, keep the server on localhost, and measure quality against the hosted models you'd otherwise use. For private data, offline work and high-volume simple tasks, a model on your own machine is now a practical first choice rather than a curiosity.
Author at LuminaryEra
The LuminaryEra editorial desk publishes long-form, hands-on guides on AI-assisted development, large language models, developer tools and web engineering. Articles are researched and drafted with the help of AI tools, link to their sources, and are corrected when readers report errors.
View all articles




