Ollama for Claude. Use your Claude Code subscription as a local AI API. For free.
A Really Artificial project · Website · npm · github
otterly serve → localhost:11435/playground to poke the API, or /dashboard for live spend, tokens, latency, and tool usage.
This is a fork of Otterly by Harsh Joshi. I use it every day to run Claude inside AiderDesk. The original is at github.com/ReallyArtificial/otterly; everything else on this page describes the fork.
Claude can't touch your computer on its own
- In the original, a plain chat request gave Claude its full set of built-in tools with every action pre-approved, so it could read and change files and run commands on the machine without asking. Here, every request through the server runs with all of Claude's own tools switched off. That includes any tool a future Claude Code release adds.
- Claude also starts without your personal Claude Code settings, CLAUDE.md files, plugins, hooks or add-on tool servers (MCP).
- Before the server starts, it checks the installed
claudeprogram at no cost, and refuses to start ifclaudeis missing or still offers any tools.
Uses only the claude program you installed
- The original could quietly fall back to an old copy of Claude Code bundled inside it (version 1.0.128, from September 2025). That fallback is gone: Otterly now needs the
claudeprogram on your PATH, and the startup banner shows which version it is using. - A test suite checks the installed
claudeagainst everything Otterly relies on. Run it after each Claude Code upgrade (see After upgrading Claude Code).
Better tool calls for apps like AiderDesk
- Tool calls are streamed to the app as Claude writes them, instead of all at once at the end.
- A tool call that is slightly malformed (a missing closing bracket) is repaired. One that can't be repaired is rejected instead of being shown to you as a wall of broken text.
- When a streamed reply goes wrong, Otterly cuts the connection. AiderDesk, like other apps built on the AI SDK, then retries automatically, and the retry starts with a short note saying what happened.
- If Claude tries to use one of its own tools instead of the app's, the reply is rejected the same way.
You can watch Claude think
- Claude's thinking is streamed live as
reasoning_content, which AiderDesk shows in its collapsible thinking box. - Keep-alive pings stop apps from giving up while Claude is still working.
It never hangs
- Each request has time limits: 45 minutes in total, and 5 minutes without any output. Both can be changed (
--request-timeout,--stream-timeout,--idle-timeout). - A stuck
claudeprocess is stopped properly, and Ctrl+C stops everyclaudeprocess the server started. - Every request gets an answer, even when something fails.
See how much of your Claude subscription is left
GET /api/quotareports the 5-hour and weekly usage of the subscription theclaudeprogram is signed in to, in the same shape as Anthropic's own usage figures. The numbers come fromclaudeitself (its/usagecommand, and the usage note it prints after every reply). Otterly reads none of Claude Code's files and contacts no Anthropic address.- When the subscription hits its usage limit, Otterly answers new requests at once with HTTP 429 and a
Retry-Aftertime, instead of starting aclauderun that would only fail.
Works as a provider in 9router
- My fork of 9router adds an Otterly provider. Point it at an Otterly server's
/v1address and 9router sends Claude requests through it, and shows the subscription's usage from/api/quota.
Up-to-date model list
- The model list offers Claude Fable 5.2 and 5.1, Opus 5.5 and 5, Sonnet 5.5 and 5, Haiku 5.5 and Haiku 4.5. The default is
claude-opus-5-5.
Other additions
reasoning_effortis supported (low,medium,high,xhigh,max); the default ismedium.- Optional request tracing for debugging (
OTTERLY_TRACE=1): each request's input, output and timings are saved under~/.otterly/traces, and traces older than 7 days are deleted. - Multi-turn sessions (
/ws) and permission prompts now work through the installedclaudeprogram. --host(-H) chooses the network address the server listens on, e.g.--host 127.0.0.1to keep it to this machine.
One change for people who call Otterly from their own code
If you import Otterly into a Node.js script rather than running the server, Claude now gets no built-in tools unless you ask for them, e.g. { tools: ["Read", "Grep"] } or { tools: ["default"] }. The examples in examples/ show how.
You already pay $20–$200/month for Claude Code. Then you build a side project, a script, a tiny agent, and Anthropic charges you again per token via the API. That's double-paying for the same brain.
Otterly fixes that. It turns your existing Claude Code subscription into a local, OpenAI-compatible API, exactly like Ollama does for open-source models, powered by the Claude that you're already paying for.
npx otterly serve otterly: local inference server
──────────────────────────────────────
OpenAI compat : http://localhost:11435/v1/chat/completions
Playground : http://localhost:11435/playground
Ready. Point any OpenAI client at it.
Same OpenAI-compatible API. Zero per-token cost. No API keys.
Otterly drives your Claude Code subscription through the claude CLI that is
already installed and signed in on your machine. It never handles API keys.
npm i -g @anthropic-ai/claude-code
claude # browser login, persists afterwardsOtterly requires the claude CLI on your PATH. At startup it checks it, and
refuses to start if claude is missing, rejects one of Otterly's flags, or
still offers tools or MCP servers with them. The startup banner's Claude CLI
line shows the version and path in use.
The server runs Claude inside a working directory, set with -d:
otterly serve -d /path/to/project # Claude works in this dir
otterly serve # uses a clean scratch dirWith no -d, otterly creates an empty scratch directory under your system
temp folder and uses that, so the model reasons only over what each request
sends.
otterly serve -p 11435In an OpenAI-compatible client (e.g. AiderDesk, Cherry Studio), add an OpenAI-Compatible provider:
| Provider | Base URL | API key |
|---|---|---|
| Otterly | http://localhost:11435/v1 |
any non-empty string |
Start the server before launching the client so model discovery
(GET /v1/models) populates the provider's dropdown.
Claude Code ships often, and Otterly depends on its command-line flags and its stream-json protocol. After each upgrade, run the CLI suite from a clone of this repository:
pnpm install
pnpm exec vitest run --config vitest.cli.config.tsIt checks every flag Otterly passes (at no cost), then makes a few short,
low-effort calls on your subscription. The startup banner warns when the
installed version is not the one the suite was last recorded against
(TESTED_CLAUDE_CLI_VERSION in src/engine.ts). If the suite fails, go back to
the previous Claude Code version and open an issue with the failing output.
Claude runs with no built-in tools, no MCP servers, and none of your Claude Code
settings, CLAUDE.md files, hooks or plugins, so it answers purely from each
request and never reads, edits, or executes anything on your machine on its own. When a request includes OpenAI tools, Claude emits
structured tool_calls JSON for your client to execute and feed back — your
client orchestrates every tool call.
| Library | CLI server | Embedded server | |
|---|---|---|---|
| How | import { claude } from "otterly" |
npx otterly serve |
await startApiServer({ port }) |
| Best for | Node.js scripts & agents | Any language, any tool | Bundling the server into your app |
| Network | None, in-process | localhost HTTP/WS | localhost HTTP/WS |
| Analogy | Direct function call | ollama serve |
ollama as a library |
Pick one. Mix all three.
// Without otterly: pay Anthropic twice
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({ apiKey: "sk-ant-..." }); // $3 / MTok in
const res = await client.messages.create({ // $15 / MTok out
model: "claude-sonnet-4-20250514",
messages: [{ role: "user", content: "Fix the failing tests" }],
});// With otterly (library): direct, in-process, $0
import { claude } from "otterly";
const result = await claude.run("Fix the failing tests", { cwd: "./app" });
console.log(result.text, result.cost);// With otterly (server): your existing OpenAI SDK, any language, $0
import OpenAI from "openai";
const ai = new OpenAI({ baseURL: "http://localhost:11435/v1", apiKey: "unused" });
const res = await ai.chat.completions.create({
model: "claude-sonnet-5-5",
messages: [{ role: "user", content: "Fix the failing tests" }],
});That's the whole product. Keep reading if you want details.
npm install otterlyYou also need Claude Code installed and signed in. Otterly auto-detects npm installs, Homebrew, and standalone binaries. Anything that gives you a working claude command.
# Verify
claude --version"Claude Code subscribers can no longer use their Claude subscription limits for third-party harnesses including OpenClaw." TechCrunch, April 4, 2026
If you use OpenClaw, this is the section that pays for otterly.
On April 4, 2026, Anthropic severed the direct path between OpenClaw and your Claude Code subscription. Overnight, OpenClaw users had three new (worse) options: buy extra usage bundles, supply a separate Anthropic API key at full pay-per-token rates, or drain a small parallel "Agent SDK credit" pool. Heavy users reported bills jumping up to 50× their previous monthly outlay. The OpenClaw author publicly called it a betrayal.
otterly is the routing layer. OpenClaw talks to localhost:11435. otterly spawns your authenticated claude CLI, which is Anthropic's own product and still allowed to use your subscription, and the request arrives at the exact destination OpenClaw was locked out of. No extra bundles, no API key, no credit-pool draining. Same model, same brain, same subscription.
# 1. install Claude Code on the same machine, sign in once
npm i -g @anthropic-ai/claude-code
claude # browser-based login, persists after
# 2. install + run otterly
npm i -g otterly
otterly serve # listens on localhost:11435// 3. add otterly as a model provider in your OpenClaw config
{
agents: {
defaults: { model: { primary: "otterly/claude-sonnet-5-5" } },
},
models: {
providers: {
otterly: {
baseUrl: "http://localhost:11435/v1",
apiKey: "unused",
api: "openai-completions",
timeoutSeconds: 600,
models: [{
id: "claude-sonnet-5-5",
name: "Claude Sonnet 5.5 (via subscription)",
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 1000000,
maxTokens: 8192,
}],
},
},
},
}openclaw models set otterly/claude-sonnet-5-5That's the whole patch. Every OpenClaw call now lands on your Claude Code subscription via the local claude CLI. The Agent SDK credit pool never moves, no API-key meter ticks, no extra-usage bundles get consumed. Watch your Anthropic dashboard. The only thing that moves is your normal Claude Code subscription usage.
Running headless? (Raspberry Pi, EC2, a container.) Run
claudeonce over an interactive SSH session to complete the browser login. The token persists. Then runotterly serveas a systemd user service. Same pattern as any long-lived daemon.
The defaults work fine on a developer laptop. On a Pi or any small machine, four dials make Friday feel instant instead of flaky.
Match concurrency to the box. Each claude spawn uses about 1–2 GB of RAM and a full CPU core while it runs. On a Pi or a 2-vCPU VPS, set --max-concurrent 2. On a 16 GB laptop the default of 5 is fine. Going higher than your real parallelism mostly creates queue contention.
Raise the queue timeout for slow first spawns. Claude Code's first cold spawn can take 20–30 seconds when the OpenClaw prompt is large (workspace files, skills, tool schemas). Set --queue-timeout 300 so a burst of concurrent OpenClaw cron jobs does not 408 itself into a death loop while waiting for a worker slot.
Use otterly 0.5.0 or newer. Earlier versions silently dropped streaming response text when otterly was driving the claude CLI binary (the common install path). OpenClaw uses stream: true. If you see "Agent couldn't generate a response" on a turn that should obviously work, you are on an older otterly. Upgrade.
Run otterly as a system service, not a tmux pane. Drop this into ~/.config/systemd/user/otterly.service:
[Unit]
Description=otterly local inference server
After=network-online.target
[Service]
ExecStart=/usr/bin/node /home/youruser/.npm-global/bin/otterly serve --port 11435 --max-concurrent 2 --queue-timeout 300
Restart=always
RestartSec=5
Environment=HOME=/home/youruser
Environment=PATH=/usr/bin:/home/youruser/.npm-global/bin
[Install]
WantedBy=default.targetThen:
systemctl --user enable --now otterly.service
loginctl enable-linger youruser # survives reboot without a loginSanity check before flipping the default model. Once openclaw.json is patched, test the new provider before pointing all of OpenClaw at it:
openclaw capability model run --model otterly/claude-sonnet-5-5 --prompt "ping"If that returns text in a few seconds, you are good: openclaw models set otterly/claude-sonnet-5-5. If it hangs, curl http://localhost:11435/api/status tells you exactly which queue slot is stuck.
Anything that speaks the OpenAI Chat Completions API can use otterly as a provider. Run otterly serve once, then drop one of these snippets in.
In Cline's settings (Cmd-Shift-P → Cline: Open Settings), pick OpenAI Compatible as the API provider, then:
| Field | Value |
|---|---|
| Base URL | http://localhost:11435/v1 |
| API Key | unused (any non-empty string) |
| Model ID | claude-sonnet-5-5 |
Cline streams by default — otterly handles SSE with keepalives so cold spawns don't time out the extension.
Settings → Models → toggle Override OpenAI Base URL:
http://localhost:11435/v1
Set API Key to anything (e.g. unused), then add claude-sonnet-5-5 to Model Names. Cursor will call otterly for chat, autocomplete, and Composer.
{
"models": [
{
"title": "Claude Sonnet 5.5 (via otterly)",
"provider": "openai",
"model": "claude-sonnet-5-5",
"apiBase": "http://localhost:11435/v1",
"apiKey": "unused"
}
]
}provider: "openai" is intentional — Continue's OpenAI provider speaks the same chat-completions shape otterly serves.
export OPENAI_API_BASE=http://localhost:11435/v1
export OPENAI_API_KEY=unused
aider --model openai/claude-sonnet-5-5The openai/ prefix tells Aider to use the OpenAI-compatible path. Add to your shell profile to make it permanent.
Same pattern everywhere: point the base URL at http://localhost:11435/v1, send any non-empty API key, name the model claude-sonnet-5-5. If your client talks to OpenAI today, it talks to otterly with one config change.
Just import and call. Perfect for Node scripts, custom agents, cron jobs, build tools.
import { claude } from "otterly";
// One-shot
const result = await claude.run("Add validation to user.ts", { cwd: "./app" });
console.log(result.text); // assistant reply
console.log(result.cost); // USD cost for this turn (tracked from Claude Code)
console.log(result.tools); // every tool call Claude made
// Stream tokens
for await (const event of claude.stream("Refactor auth", { cwd: "." })) {
if (event.type === "text_delta") process.stdout.write(event.delta);
if (event.type === "tool_use") console.log(`\n[using ${event.tool}]`);
}
// Multi-turn session. Context persists in-memory, no server.
const session = claude.session({ cwd: "./app", tools: ["default"] });
await session.send("Create a REST API");
await session.send("Now add auth to it"); // remembers the API you just built
session.close();A session is one long-lived claude process: each send() is another turn of the same conversation, so Claude keeps its context. No WebSocket. No HTTP.
By default Claude gets no built-in tools. Pass tools: ["default"] for Claude Code's default set, or a list such as ["Read", "Grep"], when you want it to read or change files. Add onPermission to approve or deny each tool use.
When you want one running daemon that any tool, any language, any framework can talk to.
npx otterly serveThat's it. Now you have an OpenAI-compatible API on localhost:11435. Point anything at it:
// TypeScript with the OpenAI SDK
import OpenAI from "openai";
const ai = new OpenAI({ baseURL: "http://localhost:11435/v1", apiKey: "unused" });
const res = await ai.chat.completions.create({
model: "claude-sonnet-5-5",
messages: [{ role: "user", content: "Write a haiku about otters" }],
});# Python with the OpenAI SDK
from openai import OpenAI
ai = OpenAI(base_url="http://localhost:11435/v1", api_key="unused")
res = ai.chat.completions.create(
model="claude-sonnet-5-5",
messages=[{"role": "user", "content": "Write a haiku about otters"}],
)# Anything that speaks HTTP. curl, your shell, your dog.
curl -X POST http://localhost:11435/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-5-5",
"messages": [{"role": "user", "content": "Hello"}]
}'It works in Cursor, Continue, Aider, Open WebUI, LiteLLM, LangChain, llamafile UIs, your own clients. Anything with a baseURL field. If it talks to OpenAI, it talks to otterly.
Open the playground at http://localhost:11435/playground to poke the API from your browser, or the dashboard at http://localhost:11435/dashboard to see live spend, latency, and tool usage.
otterly answers Ollama's own API — so Ollama-only tools (Open WebUI's native
connection, Raycast, oterm, homelab dashboards) that auto-discover a local Ollama
by polling GET /api/tags find otterly and list your models in their picker. To
match Ollama's default port exactly, start otterly with --port 11434.
# Discovery — exactly what Ollama tools hit on startup
curl http://localhost:11435/api/tags
# Ollama-native chat (NDJSON stream, like `ollama run`)
curl http://localhost:11435/api/chat -d '{
"model": "claude-sonnet-5-5",
"messages": [{ "role": "user", "content": "Write a haiku about otters" }]
}'Point any tool that expects an Ollama endpoint at http://localhost:11435 and it
just works. OLLAMA_HOST=http://localhost:11435 is all most of them need.
Send OpenAI-format tools and otterly returns real tool_calls with
finish_reason: "tool_calls" — so agentic clients (Cline, Aider, your own
scripts) get the structured function calls they expect. Your code runs the
function and sends the result back as a role: "tool" message, exactly like the
OpenAI API. Claude runs with its own built-in file and shell tools disabled, so a
request never touches your filesystem or shell — every tool call is emitted as
structured tool_calls JSON for your client to execute.
const res = await ai.chat.completions.create({
model: "claude-sonnet-5-5",
messages: [{ role: "user", content: "What's the weather in Paris?" }],
tools: [{
type: "function",
function: {
name: "get_weather",
description: "Get current weather for a city",
parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
},
}],
});
// res.choices[0].message.tool_calls → [{ function: { name: "get_weather", arguments: '{"city":"Paris"}' } }]Run the full HTTP + WebSocket server inside your own Node app. Same endpoints, same playground, same WebSocket sessions, but no separate process to babysit.
import { startApiServer } from "otterly";
const handle = await startApiServer({
port: 11435,
workingDir: "./my-project",
maxConcurrent: 5,
});
// handle.server → Node http.Server
// handle.wss → WebSocketServer
// handle.port → bound port
// handle.shutdown → graceful drain + close
// later, on app exit
await handle.shutdown(10_000);This is exactly what npx otterly serve runs under the hood. Bundle it inside an Electron app, an internal dev tool, a Tauri sidecar, a Cloudflare-style edge worker. Anything that benefits from an AI endpoint without managing a second process.
| Endpoint | Format | What it's for |
|---|---|---|
POST /v1/chat/completions |
OpenAI | Drop-in for any OpenAI client/SDK (incl. function calling) |
GET /v1/models |
OpenAI | Model list — clients probe this on startup |
POST /api/chat |
Ollama | Ollama-native chat (NDJSON stream) |
POST /api/generate |
Ollama | Ollama-native completion (NDJSON stream) |
GET /api/tags |
Ollama | Model discovery — Ollama-only tools poll this to find otterly |
POST /api/show |
Ollama | Model metadata (context length, capabilities) |
POST /api/run |
JSON | Native one-shot with cost + tool logs |
POST /api/stream |
NDJSON | Streaming with rich events |
WS /ws |
WebSocket | Persistent multi-turn sessions |
GET /dashboard |
HTML | Live spend, latency, recent runs, tool usage |
GET /playground |
HTML | Interactive API explorer in your browser |
GET /api/status |
JSON | Health + queue stats |
GET /api/metrics |
JSON | Today + lifetime usage, recent runs, top tools |
GET /api/quota |
JSON | Usage of your Claude subscription: the 5-hour and weekly windows, read from claude /usage and the CLI's own rate-limit events, in the shape of Anthropic's own usage endpoint. Needs the Bearer token when OTTERLY_API_KEY is set |
GET /swagger.json |
OpenAPI 3.0 | Full spec. Generate a client in any language. |
Plus all the boring-but-essential stuff:
- Concurrency control. Request queue prevents fork-bombing your machine.
- Rate limiting. Per-IP token bucket, configurable.
- Circuit breaker. Bails out on cascading Claude Code failures.
- Auth. Set
OTTERLY_API_KEYto requireBearertokens. - Graceful shutdown. Drains in-flight requests before exiting.
- CORS. Works straight from the browser.
npx otterly serve --port 11435 --dir ./project --max-concurrent 3| Flag | Default | |
|---|---|---|
-p, --port |
11435 |
Port to listen on |
-H, --host |
all interfaces | Interface to listen on, e.g. 127.0.0.1 |
-d, --dir |
an empty scratch directory, otterly-scratch in the system temp folder |
Working directory Claude runs in |
--max-concurrent |
5 |
Parallel Claude processes |
--max-queue |
50 |
Max queued requests |
--queue-timeout |
120 |
Seconds a request may wait in the queue before 408 |
--rate-limit |
60 |
Requests/min per client |
--request-timeout |
2700 |
Seconds a non-streamed request may run before 504 |
--stream-timeout |
2700 |
Seconds a streamed request may run before it is stopped |
--idle-timeout |
300 |
Seconds a Claude run may go without any output before it is stopped |
Programmatic options on startApiServer() mirror the flags, plus requestTimeoutMs, streamTimeoutMs, queueTimeoutMs, and verifyCli (default true; false skips the startup check of the claude CLI). Set OTTERLY_API_KEY in the environment to require Bearer auth.
cd otterly # your clone of this repository
pnpm run build
pnpm i -g .Then stop otterly serve (Ctrl+C) and start it again:
otterly serve -p 11435
import { claude, ClaudeEngine, READONLY, AUTOPILOT, verifyClaudeCLI } from "otterly";
// One-shot
const result = await claude.run(prompt, options);
// → { text, cost, duration, sessionId, usage, tools }
// Streaming
for await (const event of claude.stream(prompt, options)) {
// event.type: text_delta | tool_use | tool_result | system | result | error
}
// Multi-turn session (in-process)
const session = claude.session(options);
await session.send(message); // → AgentResult
session.close();
// Custom engine with defaults
const engine = new ClaudeEngine({ model: "claude-sonnet-5-5", maxTurns: 10 });
// Built-in tools are off unless you name them; a handler approves each use
await claude.run(prompt, { tools: ["Read", "Grep"], onPermission: READONLY }); // read-only
await claude.run(prompt, { tools: ["default"], onPermission: AUTOPILOT }); // approve everything
// Check the installed claude CLI, as the server does at startup
const check = await verifyClaudeCLI(); // → { ok, cli: { path, version }, problem? }
// Embedded server
import { startApiServer } from "otterly";
const handle = await startApiServer({ port: 11435 });Otterly is a transport layer. It does not jailbreak Claude, does not bypass any usage limits, does not redistribute model weights, does not store your prompts. Every request flows through your own authenticated Claude Code installation, subject to your subscription's normal limits.
What you save is the second meter: the per-token API bill on top of the subscription you already pay.
Why is it called "otterly"? Because otters carry their tools with them, and your local Claude already has all the tools it needs. Also because the domain was available.
- Node.js 18+
- Claude Code CLI (
claude) on your PATH and signed in (claude --versionto confirm). Otterly checks it at startup and will not start without it. - An active Claude subscription (Pro, Max, or Team)
PRs and issues welcome at github.com/ReallyArtificial/otterly. Especially interested in:
- More language SDK examples (Go, Rust, Elixir)
- Integration recipes for Cursor / Continue / 7C10 Aider / Open WebUI
- Bugs from running it in production-ish environments
MIT. Use it for anything, ship it anywhere, don't blame me when an otter gets in your codebase.
These checks cover the fork's claims above: GET /api/quota, the usage-limit
answer, -H, --host, the model list, the ports and the CLI suite command. Run
from the Z-Book. Expected values follow #.
cd /home/inigo/code/iwd/otterly
grep -F -c 'req.method === "GET" && path === "/api/quota"' src/server/index.ts # 1
grep -A4 'path === "/api/quota"' src/server/index.ts | grep -c 'checkAuth(req, ctx)' # 1
grep -F -c 'const EVENT_WINDOWS = ["five_hour", "seven_day"];' src/server/quota.ts # 1
grep -c 'api.anthropic.com' src/server/quota.ts # 0
grep -F -c 'host: { type: "string", short: "H" },' src/cli.ts # 1
grep -F -c 'host: values.host,' src/cli.ts # 1
grep -F -c 'server.listen({ port, host: opts.host }' src/server/index.ts # 1
grep -F -c 'export const DEFAULT_MODEL = "claude-opus-5-5";' src/server/models.ts # 1
grep -c '{ id: "claude-' src/server/models.ts # 8
grep -F -c 'const INFERENCE_PATHS = new Set(' src/server/index.ts # 1
grep -F -c '"Retry-After": String(limit.retryAfterS)' src/server/index.ts # 1
grep -c 'localhost:1143[4]' README.md # 0
grep -c 'pnpm dl[x]' README.md # 0
grep -F -c 'pnpm exec vitest run --config vitest.cli.config.ts' src/server/index.ts # 1Manual checks:
- The link to the 9router fork in "About this fork" opens the fork on GitHub.