How to use OpenCode with a local model in LM Studio

By

Tagged: AI

Connect OpenCode to LM Studio, test local tool calling, fix model discovery problems, and check what you need for a coding workflow that works offline.

You can run OpenCode against a local model served by LM Studio. Instead of sending prompts to a cloud API, OpenCode talks to a local HTTP server running a model you’ve already downloaded. (LM Studio also ships Bionic, its own agent app built on the same local models.)

Your prompts stay on your machine, and in return your computer has to run the model alongside OpenCode, your editor, and your dev tools. If you want to compare this with API billing or Ollama, I covered those options in how to use a coding agent without another subscription.

In this guide we’ll connect OpenCode to LM Studio, run a small coding task, and look at what offline really means in practice. Pointing OpenCode at a local model keeps inference on your machine, while tools like web search, Git, or shell commands can still hit the network.

To follow along, you’ll need OpenCode, LM Studio, and enough RAM for the model you pick. All commands below use OpenCode v2. If you still have v1 installed alongside it, run opencode2 wherever you see opencode.

Choose a model that can use tools

A coding agent needs more than a model that can answer JavaScript questions in a chat box.

It has to ask OpenCode to read a file, read what comes back, and request the next step in the exact format the server expects. After that, it needs to apply a clean edit and make sense of your test output.

In LM Studio, download an instruction-tuned coding model that supports tool use. Check the model card and LM Studio’s metadata before downloading. For your first connection test, pick a smaller model that fits comfortably in RAM instead of pushing your machine with the largest download you can barely load.

Memory usage depends on model size, quantization, and context length. Keep in mind that the context holds the full conversation plus tool outputs, not just your latest message. Leave headroom for your editor, the LM Studio server, and your project’s build process.

Don’t throw a large migration at a new local model right away. Start by asking it to read a single file through a tool call. Getting a decent answer in the LM Studio chat panel is easy, while reliable tool calling is where local models usually stumble first.

If you want to understand what these model files are and why their licenses still matter when you run them yourself, read my open weights post.

Start the LM Studio server

Load your downloaded model in LM Studio, open the Developer tab, and start the local server.

By default, it listens at this address:

http://127.0.0.1:1234

Leave it bound to your local machine for now. You don’t need to open access to other computers on your network.

If you already have LM Studio’s lms command installed, you can start the server from your terminal instead (see the LM Studio server documentation):

lms server start

Next, check the OpenAI-compatible models endpoint from a terminal:

curl http://127.0.0.1:1234/v1/models

You should get back a response containing model IDs. Use the exact IDs your server returns, because a model’s display name in the UI doesn’t always match its API identifier.

If you turned on server authentication in LM Studio, an unauthenticated request will fail even when the model is loaded. Keep authentication enabled if your setup needs it, pass the same credentials into OpenCode, and don’t try to fix connection errors by exposing the server to a wider network.

Let OpenCode discover it

OpenCode v2 automatically discovers LM Studio models at the default local address. Start the LM Studio server before you open the model picker.

From a small project directory, launch OpenCode:

opencode

Then open the model picker:

/models

Pick your model under the lmstudio provider. Double-check the provider label so you don’t accidentally choose a hosted provider offering a similarly named model.

That selection only applies to the current session. To make it the default for this project, create opencode.jsonc and set model to the exact selector from the picker.

Here’s an example LM Studio config using a sample model selector:

{
  "$schema": "https://opencode.ai/config.json",
  "model": "lmstudio/google/gemma-4-26b-a4b"
}

Use that value only if your server has that exact model loaded. Otherwise swap it for the exact selector shown in your picker. Putting it in opencode.jsonc only tells OpenCode which model to pick, so the model still needs to be downloaded and loaded in LM Studio.

Both the lmstudio provider prefix and the model ID matter. Changing the default in opencode.jsonc also won’t always override an existing session that already selected a model, so run /models to confirm what the active session is using.

Use another port or authentication

If LM Studio listens on another port or host, configure the endpoint under providers. OpenCode’s built-in integration will still discover its loaded models.

For a local server listening on port 5678, save this in opencode.jsonc:

{
  "$schema": "https://opencode.ai/config.json",
  "providers": {
    "lmstudio": {
      "settings": {
        "baseURL": "http://127.0.0.1:5678/v1"
      }
    }
  }
}

Pay attention to the /v1 suffix on the API URL. The server address shown in LM Studio’s interface and the OpenAI-compatible API base URL aren’t always the same string.

If you enabled server authentication, add "apiKey": "{env:LMSTUDIO_API_KEY}" inside settings and pass the variable through your shell environment or secret manager. Keep the key out of opencode.jsonc and out of Git.

OpenCode routes model requests through a shared background service, so an already-running service won’t see an environment variable you just set in a new terminal. For a single command, opencode run --standalone starts a private server that inherits that command’s environment (see the CLI documentation).

Make a small test project

Let’s test the setup on a tiny project that needs no package downloads. We’ll ask the agent to fix a function that drops 0 values, which is easy to check right away.

Create a new directory:

mkdir local-agent-practice
cd local-agent-practice
git init

Save this code as prices.mjs:

export function listedPrices(prices) {
  return prices.filter(Boolean)
}

Save this test file as prices.test.mjs:

import test from 'node:test'
import assert from 'node:assert/strict'
import { listedPrices } from './prices.mjs'

test('keeps zero prices and removes missing entries', () => {
  assert.deepEqual(listedPrices([12, 0, null, 5, undefined]), [12, 0, 5])
})

test('handles an empty list', () => {
  assert.deepEqual(listedPrices([]), [])
})

Run the tests before asking the agent to change anything:

node --test

The first test should fail. Because 0 is falsy in JavaScript, filter(Boolean) strips it right out.

We only want to remove null and undefined, not filter out every possible invalid price. Keep that scope clear in the prompt so the model doesn’t invent validation rules you didn’t ask for.

Commit the starting files so you can review the diff later:

git add prices.mjs prices.test.mjs
git commit -m "Add price filtering example"

Now open OpenCode inside this folder and select your LM Studio model.

Check reading before editing

Before asking for any edits, send a read-only prompt:

Read prices.mjs and prices.test.mjs using your file tools.
Explain why the first test fails. Don't edit files or run commands.

Watch OpenCode’s tool activity as it runs. You want to see a real file-read tool call happen, followed by an explanation that matches what’s in the file.

Some local models print text that looks like a tool call straight into their reply without invoking a real tool. If OpenCode shows no tool operation, check the model’s tool support and look at the LM Studio server logs.

Once file reading works, ask the agent to fix the bug:

Update listedPrices so it removes only null and undefined.
Preserve zero and preserve the order of the remaining entries.
Don't change the tests. Run node --test. Don't commit anything.

Review the diff yourself:

git diff
node --test

A clean fix filters with price !== null && price !== undefined. This small check shows whether the full loop works: OpenCode reads the files, makes a focused edit, and runs the test command you asked for.

What fully offline requires

LM Studio supports offline operation once the app and your models are downloaded. Running a complete coding workflow offline has a few more moving parts.

Prepare your project while you’re still connected. Install its packages, download any compiler or browser binaries its tests need, and make sure its test data lives locally. A test that hits a hosted database will still need that database.

OpenCode’s own tools can also reach the internet. Web search, a remote MCP server, Git operations, or a shell command can all make network requests even when inference runs locally.

If a task needs to work offline, turn off external integrations, stick to local fixtures, and disconnect your computer once everything is ready. Then run the same read and fix prompts again so you can verify the whole loop finishes with no network connection.

If your work requires a strict network boundary where nothing can reach the internet in the background, enforce it through your operating system or network setup and check the logs. Writing “stay offline” in a prompt won’t block network traffic.

Here’s how that boundary breaks down:

Local inference is one part of offline workAn offline coding workflow needs downloaded models, packages and test tools, local fixtures, and no required remote integrations; the whole flow must be tested disconnected.Local model selectedPrepare packages andtest toolsUse local test dataRemove requiredremote integrationsDisconnect andrepeat the taskEnforce networkboundary if required

Make sure the model itself runs on your machine too. A local server that forwards requests to another computer still sends traffic off your machine, even if OpenCode connects to a loopback address.

Fig 1 · 1/3Local inference has a boundary
The agent prepares a request from local project context.

When chat works but tool calls fail

LM Studio’s tool-use documentation lays out how the compatible API flow works: the model requests a tool, OpenCode executes it, and the result goes back to the model.

For that loop to hold up, both the model and its chat template matter. A general chat model can write fluent explanations while failing to emit valid tool calls.

If the read-only prompt fails, switch to the model’s recommended chat template and check whether the server reports tool support. Don’t force-mark a model as tool-capable just to make it show up in a list, because OpenCode will start sending tool calls the model still can’t handle.

If reading files works and editing breaks, narrow the task down. Ask for one specific replacement so you can separate code-reasoning mistakes from tool-call formatting errors.

When you hit context errors, start a fresh session with fewer files attached. Raising the context limit in a client config won’t create more RAM or increase the context window allocated on the LM Studio server.

If your machine starts swapping heavily, load a smaller model or lower the configured context length. Compare models by the total time it takes to get a reviewed change, retries included, instead of judging them by token generation speed alone.

How I would use this setup

Start with a small utility that already has local tests, especially when you want model requests to stay on your computer. Focused work like explaining a module, renaming a symbol, or fixing a bug with a failing test gives you a clear result you can verify quickly.

Don’t expect a local setup to replace a hosted coding model on every project. Even with no per-request API bill, fixing a messy edit by hand several times still costs your time, and running models locally costs electricity, hardware, and a large slice of memory.

Keep local and hosted models easy to tell apart in the model picker. If you switch providers halfway through a task, check what’s already in the session context before sending the next prompt, because files you attached locally will go out with the remote request.

Want me to talk about your product? You can sponsor this site.

Related posts about ai: