Setup guide · Models
Local models with Ollama
Ollama running open-weight chat and embedding models on your own machine, reachable through Anthropic- and OpenAI-compatible APIs and usable from Claude Code.
Ollama runs open-weight models on your own computer and serves them on http://localhost:11434. It speaks two APIs: a subset of the Anthropic Messages API, which Claude Agent SDK and Anthropic SDK code uses, and an OpenAI-compatible API, which OpenAI-SDK code uses for chat, structured output and embeddings. Exercise code reaches either by changing environment variables, not code. Everything stays on your machine and costs nothing per token.
Be realistic about quality. A model that fits on a laptop is far weaker than Claude at multi-step tool use, long documents and following a strict output format. Local models are good for learning how the plumbing works, for cheap iteration and for private data. Expect some agent exercises to work worse, and switch to a strong model through OpenRouter when you need the real result.
Before you start
- macOS 14 Sonoma or newer. Apple silicon runs models on the GPU; Intel Macs run them on the CPU only.
- Windows 10 22H2 or newer. NVIDIA (driver 551.61+) and AMD GPUs are supported.
- Linux with an NVIDIA or AMD GPU for usable speed. CPU-only works but is slow.
- Memory is the constraint. The model's download size plus its context has to fit in VRAM, or in unified memory on a Mac. A rough rule: download size plus a few GB of headroom.
- Disk: 1 to 20 GB per model.
1. Install Ollama
macOS and Linux
curl -fsSL https://ollama.com/install.sh | shOn macOS you can instead download the app from ollama.com/download and drag it to Applications.
Windows
irm https://ollama.com/install.ps1 | iexOr run OllamaSetup.exe from the download page. It installs in your user folder and doesn't need Administrator rights.
On macOS and Windows the app keeps a server running in the background. On Linux the install script sets up a service; if it isn't running, start it with ollama serve. Check with:
ollama -v2. Pick models that fit your machine
Sizes are the default download from the Ollama library. All the chat models listed support tool calling.
| Your RAM / VRAM | Chat and tool use | Notes |
|---|---|---|
| 8 GB | qwen3.5:4b (about 3.5 GB) | Fine for simple prompts; unreliable with tools |
| 16 GB | qwen3.5:9b (about 7 GB), gemma4:e4b (about 7–10 GB) | The practical minimum for tool-use exercises |
| 24–32 GB | gpt-oss:20b (14 GB), qwen3.5:27b (17–20 GB), qwen3-coder:30b (19 GB) | Noticeably better at agent loops and code |
| 64 GB+ | gpt-oss:120b (65 GB), qwen3.5:122b (81 GB) | Closest to hosted models, still behind Claude |
| Embedding model | Size | Max input |
|---|---|---|
embeddinggemma | 622 MB | 2K tokens |
nomic-embed-text | 274 MB | 2K tokens |
qwen3-embedding:0.6b | 639 MB | 32K tokens |
qwen3-embedding:8b | 4.7 GB | 40K tokens |
New models arrive every few weeks. The library's tools filter lists current models that can call tools, with their sizes. Answers default to qwen3.5 for chat and embeddinggemma for embeddings, and read both from environment variables so you can swap them.
3. Pull and run a model
ollama pull qwen3.5
ollama run qwen3.5 "Explain a context window in two sentences."
ollama pull embeddinggemmaollama run qwen3.5 with no prompt opens a chat; type /bye to leave. Other commands you'll use:
ollama list # downloaded models
ollama ps # loaded models, memory use, GPU/CPU split, context size
ollama stop qwen3.5 # unload from memory
ollama rm qwen3.5 # delete from disk4. Raise the context length for agents
Ollama sizes the context by VRAM: 4K tokens below 24 GB, 32K from 24 to 48 GB, and 256K from 48 GB up. A 4K window is too small for agents and long documents, and the model silently loses earlier text. Ollama recommends at least 64K for agents and coding tools:
- App (macOS, Windows): Settings, then drag the context length slider.
- CLI: quit the app first, then run
OLLAMA_CONTEXT_LENGTH=64000 ollama serveCheck the CONTEXT and PROCESSOR columns of ollama ps. If the processor shows part CPU, the model plus context doesn't fit in VRAM; use a smaller model or a shorter context.
5. Use the Anthropic-compatible API
Claude Agent SDK and Anthropic SDK code reaches Ollama through these variables in the project's .env. The token is required but ignored, and the empty ANTHROPIC_API_KEY stops a real key from taking over:
ANTHROPIC_BASE_URL=http://localhost:11434
ANTHROPIC_AUTH_TOKEN=ollama
ANTHROPIC_API_KEY=
MODEL=qwen3.5curl http://localhost:11434/v1/messages \
-H "content-type: application/json" \
-H "anthropic-version: 2023-06-01" \
-d '{"model":"qwen3.5","max_tokens":200,"messages":[{"role":"user","content":"Hello!"}]}'Messages, streaming, system prompts, tools and tool results, base64 images and thinking all work. These parts of the Anthropic API don't:
| Not supported | What it means for exercises |
|---|---|
tool_choice | You can't force or forbid a tool call; the model decides |
/v1/messages/count_tokens | No token counting before sending; usage in responses is an approximation |
Prompt caching (cache_control) | Ignored, so no caching savings to measure |
| Batches API | No /v1/messages/batches |
| Citations | No citations blocks |
PDF document blocks | Extract text yourself first |
metadata | Not accepted |
Streaming error events | Errors come back as HTTP status codes instead |
Partly supported: images must be base64 (no URLs), and the thinking budget_tokens value is accepted but not enforced. Structured-output (JSON schema) settings aren't in this endpoint's supported fields list either, so answers validate JSON themselves; see OpenRouter or a local model?.
6. Use the OpenAI-compatible API and embeddings
The same server exposes OpenAI-style endpoints under /v1. OpenAI-SDK code (plain model calls, structured output, embeddings) reaches them through the two variables the SDK reads itself, so the client is created with no arguments. The key is a placeholder that Ollama ignores:
OPENAI_BASE_URL=http://localhost:11434/v1
OPENAI_API_KEY=ollama
MODEL=qwen3.5
EMBEDDINGS_MODEL=embeddinggemmacurl http://localhost:11434/v1/embeddings \
-H "content-type: application/json" \
-d '{"model":"embeddinggemma","input":["first text","second text"]}'/v1/chat/completions supports tools, JSON mode and response_format, but not tool_choice, logprobs or image URLs (send images as base64).
7. Point Claude Code at a local model
Ollama can start Claude Code with the right settings:
ollama launch claudeOr set the variables yourself for one session. ANTHROPIC_API_KEY="" stops a key in your environment from taking over:
ANTHROPIC_AUTH_TOKEN=ollama ANTHROPIC_BASE_URL=http://localhost:11434 ANTHROPIC_API_KEY="" claude --model qwen3.5Run /status inside the session to confirm the base URL. Set the variables inline like this, not in your shell profile, or every claude -p call in your exercises will go to Ollama too. Claude Code's system prompt and tool definitions are large, so use a model with at least 64K context. Even then, small models often stall in multi-step edits.
LM Studio is an alternative desktop app that downloads and serves local models on OpenAI-compatible endpoints (by default at http://localhost:1234/v1).
Check it works
curl -s http://localhost:11434/v1/messages \
-H "content-type: application/json" -H "anthropic-version: 2023-06-01" \
-d '{"model":"qwen3.5","max_tokens":50,"messages":[{"role":"user","content":"Reply with the single word: ready"}]}' \
| jq -r '.content[] | select(.type=="text") | .text'Expected output (thinking models may add a thinking block first, which the filter skips):
readyTroubleshooting
connection refused on port 11434. The server isn't running. Open the Ollama app, or run ollama serve on Linux.
ollama serve fails with "address already in use". The app's server is already running. Quit the app before running ollama serve with your own settings.
A 404 or "model not found" error. Run ollama pull qwen3.5 first. Model names must match ollama list exactly, including the tag.
Very slow answers, or the model forgets the start of the conversation. Check ollama ps. Part-CPU means the model doesn't fit in memory; pick a smaller one. A 4096 context means you haven't raised it (step 4).
Going further
- OpenRouter or a local model?, the configuration pattern every answer uses
- Get an OpenRouter key, for any hosted model
- Install Claude Code
Sources
- Anthropic compatibilityDocs · OllamaThe environment variables, the supported request fields and the full list of unsupported Messages API features.
- OpenAI compatibilityDocs · OllamaThe `/v1` chat and embeddings endpoints, the supported request fields, and the placeholder API key.
- Claude Code with OllamaDocs · Ollama`ollama launch claude` and the manual environment-variable setup.
- Context lengthDocs · OllamaDefault context sizes by VRAM and how to raise them for agents.
- Ollama model libraryDocs · OllamaTags, download sizes, context windows and capabilities (tools, thinking, vision) for each model.
Exercises that use this
- Same report through the Agent SDKAgent Foundations · Structured outputs and grounding
- Build and test a session store adapterInfrastructure for Agents · State, sessions and checkpoints
- Build and attack a per-matter memory-tool handlerAgent Memory · Files, skills and memory tools
- Run the title-review agent on the SDKBuilding Agents with Claude and eve · The Claude Agent SDK
- Build and break a contract-pack reader in eveBuilding Agents with Claude and eve · Agents as files with eve
- Port the skill and subagent to eveBuilding Agents with Claude and eve · Skills and subagents
- A solicitor-approved send in eveBuilding Agents with Claude and eve · Human approval for high-stakes actions
- The same gate in the Agent SDKBuilding Agents with Claude and eve · Human approval for high-stakes actions
- Route auth and tenant isolation, checkedBuilding Agents with Claude and eve · Shipping agents
- Self-host an open parsing modelDocument Ingestion Pipelines · Parsing: text layers to vision models
- Write five eve evals for the enquiries agentEvaluating and Scoring Agents · Code-based graders
- Wire a judge into your eve evalsEvaluating and Scoring Agents · LLM-as-judge
- Measure flakiness and compare two prompt versionsEvaluating and Scoring Agents · Statistics, trials and CI gates
- Add an open-weight model to the bake-offLLMs for Engineers · Choosing and comparing models
- Fan out to eve subagents with structured resultsProduction Agent Systems · Multi-agent systems
- An eve workflow tool that waits for a search resultProduction Agent Systems · Durable, long-running agents
- Fixed recipients and a locked sandbox in eveProduction Agent Systems · Security and prompt injection
- Audit hook and retention policy in eveProduction Agent Systems · Compliance and auditability
- Session budgets and redacted exports in eveProduction Agent Systems · Observability and cost
- An eval-gated model swap in eve CIProduction Agent Systems · Continuous improvement
- DSPy: MIPROv2 versus GEPAPrompt and Context Optimisation · Automatic prompt optimisation
- Gate prompt changes in CIPrompt and Context Optimisation · Model migration and regression suites
- Measure truncation and quantisation on legal textRetrieval and Knowledge Systems · Embeddings in practice
- Add a commercial embedder (stretch)Retrieval and Knowledge Systems · Embeddings in practice
- Structure-aware and contextual chunking, measuredRetrieval and Knowledge Systems · Chunking structured documents
- Tune an ANN index against a recall targetRetrieval and Knowledge Systems · Vector indexes and databases
- Build and run a labelled query setRetrieval and Knowledge Systems · Measuring retrieval
- Verify citations end to end (stretch)Retrieval and Knowledge Systems · Measuring retrieval
- Build and measure a hybrid pipelineRetrieval and Knowledge Systems · Hybrid search and reranking
- Compare single-shot, grep-only and full agentic retrievalRetrieval and Knowledge Systems · Agentic retrieval
- Build scoped matter tools with the Agent SDK (stretch)Retrieval and Knowledge Systems · Agentic retrieval
- Compare long context, RAG and a router on your questionsRetrieval and Knowledge Systems · Long context versus RAG
- Log rate-limit headers and cache usageScaling AI Systems · Rate limits and quotas
- A deferrable-work batch pipeline against a mockScaling AI Systems · Backpressure, load shedding and batching
- Instrument and speed up a real agent turnScaling AI Systems · Latency engineering for agents