# Claude Code

Claude Code speaks the Anthropic Messages protocol, and the Model API answers it at `POST /v1/messages`. So Claude Code needs only our address and a Model API key: nothing else to install. The model is `auto`, which picks a model of the catalogue for the conversation.

Requirements: Claude Code (`claude --version` shows the version), a Model API key and money on the [organization balance](https://console.samreshuuu.ru).

## 1. Create a key

In the [developer console](https://console.samreshuuu.ru), open API keys, keep **Model API key** in the **Access** field and create the key. Copy it: the secret is shown once.

## 2. Set the variables

Claude Code reads the `env` object of `~/.claude/settings.json` (or of `settings.json` in the folder named by `CLAUDE_CONFIG_DIR`), in the terminal and in the IDE extensions alike. Create the file if there is none. If it already has an `env` object, add these keys to it rather than replacing it. If you would rather keep the key out of the file, export the same variables from your shell profile (`~/.zshrc`, `~/.bashrc`): that is the **Shell** tab.

**settings.json**

```json
{
  "env": {
    "ANTHROPIC_BASE_URL": "https://api.samreshuuu.ru",
    "ANTHROPIC_AUTH_TOKEN": "sk-org-your_api_key",
    "ANTHROPIC_API_KEY": "",
    "ANTHROPIC_MODEL": "auto",
    "ANTHROPIC_DEFAULT_FABLE_MODEL": "auto",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "auto",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "auto",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "auto",
    "CLAUDE_CODE_SUBAGENT_MODEL": "auto"
  }
}
```

**Shell**

```bash
export ANTHROPIC_BASE_URL="https://api.samreshuuu.ru"
export ANTHROPIC_AUTH_TOKEN="$SAMRESHUUU_API_KEY"
export ANTHROPIC_API_KEY=""
export ANTHROPIC_MODEL="auto"
export ANTHROPIC_DEFAULT_FABLE_MODEL="auto"
export ANTHROPIC_DEFAULT_OPUS_MODEL="auto"
export ANTHROPIC_DEFAULT_SONNET_MODEL="auto"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="auto"
export CLAUDE_CODE_SUBAGENT_MODEL="auto"
claude
```

| Variable | What it does |
| --- | --- |
| `ANTHROPIC_BASE_URL` | Sends Claude Code's requests to the Model API. The address has no `/v1`: Claude Code appends `/v1/messages` itself. |
| `ANTHROPIC_AUTH_TOKEN` | The Model API key, sent as `Authorization: Bearer`. |
| `ANTHROPIC_API_KEY` | Left empty. Claude Code sends this one as `x-api-key` and takes it for a key of Anthropic itself, so a real key left in the shell would win over the token. |
| `ANTHROPIC_MODEL` | The model a session starts on. |
| `ANTHROPIC_DEFAULT_FABLE_MODEL`, `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, `ANTHROPIC_DEFAULT_HAIKU_MODEL` | The models of Claude Code's tiers: `/model opus`, plan mode and a subagent with its own tier ask for a tier, not for `ANTHROPIC_MODEL`, and background tasks go to the Haiku tier. Without them such a call names an Anthropic model the catalogue does not have and gets `model_not_found`. |
| `CLAUDE_CODE_SUBAGENT_MODEL` | The model of subagents that name no tier of their own. |

If you were signed in to Claude Code with an Anthropic account, run `/logout` once and start `claude` again: a saved login conflicts with the token.

## 3. Check the connection

Start `claude` in a project folder and run `/status`. The auth token line names `ANTHROPIC_AUTH_TOKEN`, the base URL line names `https://api.samreshuuu.ru`. If it names an Anthropic account or `ANTHROPIC_API_KEY` instead, the variables did not reach the session: reload the shell or check the JSON of `settings.json`.

Send a prompt. The call shows up in the call log of the [console](https://console.samreshuuu.ru) with the model `auto` picked and its cost.

## Models

`auto` picks the model itself and keeps it for the conversation, so the cache holds; how it picks is under [Model choice auto](/docs/model-api-routing#model-choice-auto). Any variable of the block takes a model id instead: from the [Models](/models) page or `GET /v1/models`, a cheaper model for the Haiku tier for example. For one session, `claude --model <id>` names the model at start. A `[1m]` suffix on a model name, as OpenRouter's guide writes it, is dropped before the model is looked up.

Claude Code does not know the window of `auto` or of a catalogue model and keeps a conversation within the window it assumes, compacting it when needed. If you pin a model with a smaller window, set `CLAUDE_CODE_AUTO_COMPACT_WINDOW` to its `context_length` from `GET /v1/models`.

## Thinking and effort

With its own address replaced, Claude Code takes the Model API for Anthropic's and sends `thinking` and the `/effort` level (`output_config.effort`) for any model. The API reads them the way it reads `reasoning` on the OpenAI wire: a level the answering host does not take is brought to the nearest one (see [reasoning](/docs/model-api-requests#reasoning)), and a model that does not reason answers without thinking.

## Cache and cost

Claude Code sends the `x-claude-code-session-id` header: it keeps the calls of one session in one [cache](/docs/model-api-routing#prompt-caching). The attribution line Claude Code puts first in the system prompt changes on every request, and we remove it before the host, so it does not break the cache.

Each call is paid from the balance at the price of the host that answered, and the answer states it in `usage.cost`. Claude Code does not read that field: `/cost` shows its own estimate at Anthropic's list prices, not what the balance was charged. The script in the next section puts the charged amount in the status line. The call log of the [console](https://console.samreshuuu.ru) shows every call of the session with its model, host and cost; from code, `GET /v1/generation?id=gen-…` returns one call, with the `gen-…` from the answer's `x-request-id` header (see [Answer and cost](/docs/model-api-anthropic#answer-and-cost)).

## Cost in the status line

Claude Code draws its status line with a command you assign. The script below reads the answer ids from the session transcript, asks `GET /v1/generation` about each new one and shows the model `auto` chose, the host and what the session has charged the balance: `glm-5.3 · deepinfra · 12,40 ₽`. It takes the key and the address from the same `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN`. It needs Node.js 18 or newer.

Save the script as `~/.claude/statusline-cost.mjs`:

```js
import { readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

const base = (process.env.ANTHROPIC_BASE_URL ?? "").replace(/\/+$/, "");
const token = process.env.ANTHROPIC_AUTH_TOKEN ?? "";
const perRefresh = 50;

function readState(path) {
  try {
    return JSON.parse(readFileSync(path, "utf8"));
  } catch {
    return { seen: [], kop: 0, model: "", host: "" };
  }
}

function callIds(transcriptPath) {
  let text = "";
  try {
    text = readFileSync(transcriptPath, "utf8");
  } catch {
    return [];
  }
  const ids = new Set();
  for (const line of text.split("\n")) {
    try {
      const id = JSON.parse(line)?.message?.id;
      if (typeof id === "string" && id.startsWith("msg_")) ids.add(`gen-${id.slice(4)}`);
    } catch {}
  }
  return [...ids];
}

async function generation(id) {
  try {
    const res = await fetch(`${base}/v1/generation?id=${id}`, {
      headers: { Authorization: `Bearer ${token}` },
    });
    return res.ok ? (await res.json()).data : null;
  } catch {
    return null;
  }
}

let input = "";
for await (const chunk of process.stdin) input += chunk;
const { session_id: sessionId, transcript_path: transcriptPath } = JSON.parse(input);

if (!base || !token) {
  process.stdout.write("ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN?");
} else {
  const statePath = join(tmpdir(), `claude-cost-${sessionId}.json`);
  const state = readState(statePath);
  const seen = new Set(state.seen);
  const fresh = callIds(transcriptPath).filter((id) => !seen.has(id));
  const batch = fresh.slice(0, perRefresh);
  const answers = await Promise.all(batch.map(generation));
  batch.forEach((id, i) => {
    const data = answers[i];
    if (!data) return;
    seen.add(id);
    state.kop += Math.round((data.total_cost ?? 0) * 100);
    state.model = data.model ?? state.model;
    state.host = data.provider_name ?? state.host;
  });
  state.seen = [...seen];
  writeFileSync(statePath, JSON.stringify(state));
  const rub = (state.kop / 100).toLocaleString("ru-RU", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const parts = [state.model, state.host, `${rub} ₽`].filter(Boolean);
  const pending = fresh.length - answers.filter(Boolean).length;
  process.stdout.write(parts.join(" · ") + (pending > 0 ? ` · +${pending}…` : ""));
}
```

Add this to `~/.claude/settings.json` next to `env`:

```json
{
  "statusLine": {
    "type": "command",
    "command": "node ~/.claude/statusline-cost.mjs"
  }
}
```

The line refreshes after every answer. A call that has not reached the log yet is asked about on the next refresh, and until then their count follows the sum: `+1…`. The session's sum is kept in the system temp folder in `claude-cost-<session id>.json`, which you can delete at any time. `settings.json` holds one status line, so this one replaces yours if you had one.

## Undo the setup

Remove the keys you added from `env` in `settings.json`, or the exports from your shell profile. Claude Code then goes back to your Anthropic account.

## Troubleshooting

| What you see | What to check |
| --- | --- |
| Claude Code asks you to sign in to Anthropic | `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN` are not both read. Check that they are in the `env` object of the file Claude Code loads and that the JSON is valid. |
| A warning about an auth conflict at start | A saved Anthropic login or a real `ANTHROPIC_API_KEY`. Run `/logout`, leave `ANTHROPIC_API_KEY` empty and restart `claude`. |
| `401` | The key is wrong or revoked. Check it under API keys in the console. |
| `model_not_found` naming a `claude-…` model | One of the `ANTHROPIC_DEFAULT_*_MODEL` variables is not set: a tier asked for its Anthropic name. The error names the variables; no other model stands in. |
| `402` | The balance does not cover the call's hold, or the key's spend limit is reached. |

| HTTP | type | Code | message | Retry |
| --- | --- | --- | --- | --- |
| 401 | `authentication_error` | `invalid_api_key` | The API key is unknown, disabled, revoked or expired. Switch a disabled key back on in the developer console; create a new one in place of a revoked or expired key. | no |
| 404 | `not_found_error` | `model_not_found` | The model does not exist. GET /v1/models lists the models this API sells. | no |
| 400 | `invalid_request_error` | `no_auto_model` | No model meets the request for auto. | no |
| 402 | `billing_error` | `insufficient_balance` | The organization balance does not cover this request (max_tokens is held in full until the answer is settled). Top up the balance or lower max_tokens. | no |
| 402 | `billing_error` | `key_limit_exceeded` | This API key has reached its spending limit. Raise the limit or use another key. | no |

If an error persists, write to support with the `x-request-id` of the answer.
