Local AI Coding Setup: Ollama + OpenCode on macOS Terminal

Step-by-step guide to setting up a fully local AI coding agent with Ollama and OpenCode on macOS. Agentic tool use, multi-model support, zero cloud dependencies, all running on Apple Silicon.

📅

How to Connect OpenCode to Ollama: Local AI Coding Setup

Updated July 2026: added Docker setup, the exact error messages decoded, and the OLLAMA_CONTEXT_LENGTH alternative for num_ctx.

Want a fully local AI coding agent running in your terminal with zero cloud dependencies? This guide walks you through setting up Ollama (local LLM runner) and OpenCode (open-source AI coding agent) on macOS with Apple Silicon. The result: agentic coding capabilities, tool use, multi-model support, all running on your machine. You will find the complete working opencode.json below, ready to copy and paste.

Previously on CodeHelper: We covered MLX-CODE, a Python-based local AI coding assistant using Apple's MLX framework directly. This guide takes a different approach, using Ollama as the model server and OpenCode as the agentic coding interface. Both are 100% local and free, but they differ in architecture, model management, and capabilities.

What You Get:

  • ✅ Fully local AI: No data sent to external servers
  • ✅ Agentic coding: Tool use, file editing, plan/build modes
  • ✅ Multi-model support: Switch between models instantly
  • ✅ Terminal-only workflow: No GUI, no Electron, no bloat
  • ✅ Open source: Both Ollama and OpenCode are free and open

MLX-CODE vs Ollama + OpenCode

If you read our MLX-CODE article, you might wonder how this setup compares. Here's a quick breakdown:

FeatureMLX-CODEOllama + OpenCode
RuntimePython + MLX FrameworkOllama server + Node.js CLI
GPU AccelerationApple Metal (MLX native)Apple Metal (via llama.cpp)
Agentic FeaturesTemplates, file contextTool use, plan/build modes, undo/redo
Model ManagementManual HuggingFace downloadOne-command pull via Ollama
Context WindowModel-dependentConfigurable per model (up to 32K+)
IDE IntegrationTerminal onlyTerminal + IDE extensions
Best ForQuick local inference, MLX experimentationAgentic workflows, multi-model setups

Both approaches are valid. MLX-CODE is lighter and more self-contained; Ollama + OpenCode is more feature-rich for agentic coding workflows.

System Requirements

  • ✅ macOS (tested on Ventura+)
  • ✅ Apple Silicon (M1, M2, M3, M4)
  • ✅ Homebrew installed
  • ✅ Node.js / npm installed
  • ✅ 8GB RAM minimum (16GB+ recommended for 7B models)

On Linux the same setup works with curl -fsSL https://ollama.com/install.sh | sh instead of Homebrew: the OpenCode config in Step 7 is identical.

Step 1. Install Ollama

Ollama is a local LLM runner that manages model downloads, serves an OpenAI-compatible API, and handles GPU acceleration automatically.

# Install via Homebrew
brew install ollama

# Verify installation
ollama --version

# Start the server (keep running in a terminal tab)
ollama serve

Keep ollama serve running, OpenCode connects to it via the local API.

Step 2. Download Coding Models

Pull one or more models optimized for code generation:

# Recommended, best quality/speed balance
ollama pull qwen2.5-coder:7b

# Alternatives
ollama pull deepseek-coder:6.7b
ollama pull codellama:7b

# List installed models
ollama list

# Remove a model
ollama rm model-name

Step 3. Verify the Ollama API

Ollama exposes two endpoints. OpenCode uses the OpenAI-compatible one:

# Check Ollama native API
curl http://localhost:11434/api/tags

# Check OpenAI-compatible endpoint (used by OpenCode)
curl http://localhost:11434/v1/models

Important: OpenCode requires the /v1 endpoint (http://localhost:11434/v1), not the native Ollama API. It uses the @ai-sdk/openai-compatible package internally.

Step 4. Configure Model Context Window

Ollama defaults to a 4K context window, which is too small for agentic coding. You need at least 16K:

# Create a 16K context variant
ollama run qwen2.5-coder:7b
/set parameter num_ctx 16384
/save qwen2.5-coder:7b-16k
/bye

# For even better results (if you have 16GB+ RAM)
ollama run qwen2.5-coder:7b
/set parameter num_ctx 32768
/save qwen2.5-coder:7b-32k
/bye

This creates new model variants with the increased context. Use these names in your OpenCode config.

Alternative on newer Ollama versions: set the default context window globally with an environment variable, no model variant needed:

# Set the default context window for every model (Ollama 0.5.13+)
launchctl setenv OLLAMA_CONTEXT_LENGTH 16384   # macOS app
OLLAMA_CONTEXT_LENGTH=16384 ollama serve       # manual serve

With this set you can reference plain qwen2.5-coder:7b in the config instead of a -16k variant. The per-model variant remains the safer option if you run mixed workloads.

Step 5. Test the Model

# Interactive chat to verify it works
ollama run qwen2.5-coder:7b-16k

# Try a coding prompt
> write a debounce function in typescript

# Exit
/bye

Step 6. Install OpenCode

OpenCode is an open-source AI coding agent with a terminal TUI, plan/build modes, tool use, and undo/redo. Install globally via npm:

# Install globally
npm install -g opencode-ai

# Verify
opencode --help

Other install methods: Homebrew (brew install opencode), Bun, pnpm, Yarn, or Docker.

Step 7. Connect OpenCode to Ollama

Create the configuration file to connect OpenCode to your local Ollama instance:

# Create config directory
mkdir -p ~/.config/opencode

# Create config file
nano ~/.config/opencode/opencode.json

Paste this configuration:

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "ollama": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Ollama",
      "options": {
        "baseURL": "http://localhost:11434/v1"
      },
      "models": {
        "qwen2.5-coder:7b-16k": {
          "tools": true
        }
      }
    }
  },
  "model": "ollama/qwen2.5-coder:7b-16k"
}

Key configuration notes:

  • Config path: ~/.config/opencode/opencode.json (not ~/.opencode/)
  • npm package: Uses @ai-sdk/openai-compatible to talk to Ollama
  • baseURL: Must include /v1, this is required
  • "tools": true enables function calling for agentic features (file editing, commands)

Step 8. Use OpenCode

Navigate to any project and launch:

cd /path/to/your/project
opencode .

OpenCode Key Features

  • Plan Mode

    Press Tab to toggle. Generates implementation strategies without modifying code. Great for reasoning through complex tasks first.

  • Build Mode

    The default mode. OpenCode reads, writes, and modifies files in your project with tool use capabilities.

  • Undo / Redo

    Use /undo and /redo to revert or restore changes. Safe experimentation.

  • File References

    Press @ to fuzzy-search and attach project files to your prompt. Context-aware conversations.

  • AGENTS.md

    Run /init to generate an AGENTS.md file. OpenCode learns your project patterns and conventions.

  • Share Conversations

    Use /share to create a shareable link of your conversation for team collaboration.

Multi-Model Configuration

Add multiple models and switch between them with Ctrl+A:

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "ollama": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Ollama",
      "options": {
        "baseURL": "http://localhost:11434/v1"
      },
      "models": {
        "qwen2.5-coder:7b-16k": {
          "tools": true
        },
        "deepseek-coder:6.7b": {
          "tools": true
        },
        "codellama:7b": {
          "tools": true
        }
      }
    }
  },
  "model": "ollama/qwen2.5-coder:7b-16k",
  "small_model": "ollama/codellama:7b"
}

The small_model is used for lightweight tasks like generating titles or summaries.

Recommended Models by Task

TaskModelNotes
General codingqwen2.5-coder:7bBest quality/speed balance
WordPress / PHPdeepseek-coder:6.7bStrong PHP performance
Low RAM / Fastcodellama:7bLighter model, 8GB OK
Heavy qualityqwen2.5-coder:32bNeeds 32GB+ RAM

Remember to create 16K+ context variants for each model you use with agentic workflows.

Running Ollama in Docker

Prefer containers? Ollama ships an official image, and OpenCode connects to it with the exact same config, since the port mapping keeps the endpoint at localhost:11434:

# Start Ollama in Docker (CPU)
docker run -d -v ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama

# Pull a model inside the container
docker exec -it ollama ollama pull qwen2.5-coder:7b

# Linux with NVIDIA GPU: add --gpus=all (requires nvidia-container-toolkit)
docker run -d --gpus=all -v ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama

Honest caveat for Mac users: Docker containers on Apple Silicon cannot access the Metal GPU, so Ollama in Docker runs CPU-only and is several times slower than the native install. Use Docker on Linux servers (where --gpus=all works with NVIDIA cards); on macOS stick with brew install ollama.

Troubleshooting: the exact errors, decoded

Error: opencode is not installed, install from https://opencode.ai

Ollama is trying to hand off to the OpenCode binary and cannot find it on your PATH.

  • • Install it: npm install -g opencode-ai or brew install opencode
  • • Verify the shell can see it: which opencode
  • • If installed but not found, your PATH is missing the npm or Homebrew bin directory: restart the terminal or check npm config get prefix

connection refused on localhost:11434

  • • ollama serve is not running (or the menu bar app is closed)
  • • Test with curl http://localhost:11434/api/tags, you should get JSON back
  • • In Docker: check the container is up with docker ps and the port is published

OpenCode doesn't find models

  • • Check baseURL is http://localhost:11434/v1, the /v1 suffix is mandatory
  • • Verify the model name matches exactly what ollama list shows, including the tag

Tool calls not working or silently ignored

  • • Context window too small: increase num_ctx to 16K+ (Step 4), the 4K default overflows as soon as tool definitions plus a file land in context
  • • Missing "tools": true on the model entry in opencode.json
  • • Model doesn't support function calling well: qwen2.5-coder is the safest choice

Config errors

  • • Check JSON syntax (no trailing commas)
  • • Use the $schema for validation
  • • Confirm the file is at ~/.config/opencode/opencode.json, not ~/.opencode/

Quick Reference Commands

# Ollama
ollama serve                          # Start server
ollama list                           # List models
ollama pull qwen2.5-coder:7b          # Download model
ollama rm model-name                  # Remove model
curl http://localhost:11434/api/tags   # Check status
curl http://localhost:11434/v1/models  # OpenAI-compatible check

# OpenCode
opencode .                            # Launch in current project
/init                                 # Generate AGENTS.md
/undo                                 # Undo last change
/redo                                 # Redo last change
/share                                # Share conversation
/help                                 # List all commands
Tab                                   # Toggle plan/build mode
Ctrl+A                                # Switch models
@                                     # Fuzzy-search project files

Conclusion

With Ollama and OpenCode you get a fully local, privacy-first AI coding agent with agentic capabilities that rival cloud-based tools. No API keys, no subscriptions, no data leaving your machine. Curious what the same workload would cost on cloud APIs? Plug your token volume into our LLM Cost Calculator to compare Claude, GPT, Gemini and DeepSeek pricing, or estimate prompt sizes with the AI Token Counter.

If you're already using MLX-CODE for quick local inference, consider adding Ollama + OpenCode to your toolkit for more complex agentic workflows. Both tools complement each other: MLX-CODE for lightweight, GPU-native inference and OpenCode for full-featured coding agent capabilities.

Resources

Frequently Asked Questions

How do I connect OpenCode to Ollama?

Create a config file at ~/.config/opencode/opencode.json that points to Ollama's OpenAI-compatible endpoint at http://localhost:11434/v1. Set the provider to @ai-sdk/openai-compatible, list your models with "tools": true, and make sure ollama serve is running before launching OpenCode.

Which models work best with OpenCode and Ollama?

qwen2.5-coder:7b is the recommended model for general coding due to its quality/speed balance. For PHP/WordPress work deepseek-coder:6.7b performs well, codellama:7b works on 8GB RAM machines, and qwen2.5-coder:32b provides the best quality but requires 32GB or more RAM.

What are the system requirements to run Ollama with OpenCode?

You need macOS Ventura or later, an Apple Silicon chip (M1-M4), Homebrew, Node.js/npm, and at least 8GB RAM (16GB or more is recommended for 7B models). Both Ollama and OpenCode are free and open source.

Why is my OpenCode setup not finding Ollama models?

The most common causes are: ollama serve is not running, the baseURL in your config is missing the /v1 suffix (it must be http://localhost:11434/v1), or the model name in your config does not exactly match the name shown by ollama list. Also ensure the context window is set to at least 16K.

What does the error "opencode is not installed, install from https://opencode.ai" mean?

Ollama is trying to hand off to the OpenCode binary but cannot find it on your PATH. Install it with npm install -g opencode-ai or brew install opencode, then verify with which opencode. If it is installed but not found, your shell PATH does not include the npm or Homebrew bin directory: restart the terminal or add it to your shell profile.

What num_ctx value does OpenCode need with Ollama?

At least 16384 (16K). Ollama defaults to a 4K context window, which is too small for agentic coding: tool definitions plus file contents overflow it and tool calls silently fail. Create a 16K or 32K variant with /set parameter num_ctx followed by /save, or set the OLLAMA_CONTEXT_LENGTH environment variable on newer Ollama versions.

Can I run Ollama for OpenCode in Docker?

Yes: run the ollama/ollama image with port 11434 published and keep the same baseURL in opencode.json. One important caveat: on Apple Silicon Macs, Docker containers cannot access the Metal GPU, so Ollama in Docker runs CPU-only and is much slower than the native install. Use Docker on Linux hosts (with the NVIDIA toolkit for GPU) and the native app on macOS.