> For the complete documentation index, see [llms.txt](https://docs.nansen.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.nansen.ai/api/inference.md).

# Inference

OpenAI-compatible text generation billed to your Nansen API key and credits. Not live yet.

The Inference API gives you a text-generation model behind the same API key and credits as the rest of the Nansen API. It follows the OpenAI Chat Completions format, so the OpenAI SDKs and most OpenAI-compatible tools work by changing the base URL.

{% hint style="danger" %}
**This endpoint is not live yet.** The Inference API has not been released and is not available to customer accounts. This page is published ahead of launch and describes the upcoming beta under `/api/v1beta1`; details can change before release.
{% endhint %}

### Quick start <a href="#quick-start" id="quick-start"></a>

| Setting  | Value                                         |
| -------- | --------------------------------------------- |
| Base URL | `https://api.nansen.ai/api/v1beta1/inference` |
| API key  | Your Nansen API key                           |
| Model    | `qwen3p8-27b`                                 |

{% tabs %}
{% tab title="curl" %}

```bash
curl -s https://api.nansen.ai/api/v1beta1/inference/chat/completions \
  -H "Content-Type: application/json" \
  -H "apikey: $NANSEN_API_KEY" \
  -d '{
    "model": "qwen3p8-27b",
    "messages": [{"role": "user", "content": "Explain what a liquidity pool is in two sentences."}],
    "max_tokens": 300
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import os

from openai import OpenAI

client = OpenAI(
    base_url="https://api.nansen.ai/api/v1beta1/inference",
    api_key=os.environ["NANSEN_API_KEY"],
)

completion = client.chat.completions.create(
    model="qwen3p8-27b",
    messages=[{"role": "user", "content": "Explain what a liquidity pool is in two sentences."}],
    max_tokens=300,
)
print(completion.choices[0].message.content)
```

{% endtab %}

{% tab title="JavaScript" %}
Install the SDK with `npm install openai` and save the file as `.mjs`.

```javascript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.nansen.ai/api/v1beta1/inference",
  apiKey: process.env.NANSEN_API_KEY,
});

const completion = await client.chat.completions.create({
  model: "qwen3p8-27b",
  messages: [{ role: "user", content: "Explain what a liquidity pool is in two sentences." }],
  max_tokens: 300,
});
console.log(completion.choices[0].message.content);
```

{% endtab %}
{% endtabs %}

### Authentication <a href="#authentication" id="authentication"></a>

Send your Nansen API key in one of two headers:

* `apikey: YOUR_API_KEY`, as on the rest of the Nansen API
* `Authorization: Bearer YOUR_API_KEY`, which is what the OpenAI SDKs send

If you send both headers they must carry the same key. Keys in the query string and in the `x-api-key` header are not read. See [Authentication](https://docs.nansen.ai/getting-started/authentication.md) for how to create a key.

### Endpoints <a href="#endpoints" id="endpoints"></a>

All paths are relative to `https://api.nansen.ai/api/v1beta1/inference`.

| Method | Path                  | Purpose                                                                                                 |
| ------ | --------------------- | ------------------------------------------------------------------------------------------------------- |
| `POST` | `/chat/completions`   | Create a completion. This is the main endpoint, and new features arrive here first                      |
| `POST` | `/responses`          | OpenAI Responses format, for clients that only speak it, such as [Codex CLI](#use-it-with-coding-tools) |
| `POST` | `/v1/messages`        | Anthropic Messages format, for [Claude Code](#use-it-with-coding-tools) and the Anthropic SDKs          |
| `GET`  | `/models`             | List the available models. Needs a key, costs no credits                                                |
| `GET`  | `/usage/{request_id}` | Look up what a finished request was charged. Costs no credits                                           |

`/responses` and `/v1/messages` translate to the same model, limits and pricing as `/chat/completions`. They support the subset of each format that maps onto chat completions. Nothing is stored between requests: `previous_response_id` and other conversation references are refused, and `store: true` is accepted but treated as `false`, with a `Warning` header.

To point Claude Code or Codex CLI at these endpoints, see [Use it with coding tools](#use-it-with-coding-tools).

### Request <a href="#request" id="request"></a>

`POST /chat/completions` accepts these fields. Any other field is rejected with `400` and a message that names it, so remove fields such as `seed`, `user`, `logprobs` or `metadata` if your client adds them.

| Field                                   | Type             | Notes                                                                                                                                                                                                                                                                                                                 |
| --------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `model`                                 | string           | Required. `qwen3p8-27b`. Any other value returns `400 model_not_found`                                                                                                                                                                                                                                                |
| `messages`                              | array            | Required. 1 to 2,048 messages with role `system`, `developer`, `user`, `assistant` or `tool`. At least one `user` message. The model reads system text only at the start: leading `system` and `developer` messages are merged into one, and a later one is passed to the model as a `user` message in the same place |
| `max_tokens` / `max_completion_tokens`  | integer          | Optional, 1 to 16,384. Send at most one of the two. Includes thinking tokens. See [Output limit and credits](#output-limit-and-credits)                                                                                                                                                                               |
| `stream`                                | boolean          | Default `false`. See [Streaming](#streaming)                                                                                                                                                                                                                                                                          |
| `stream_options.include_usage`          | boolean          | Only with `stream: true`. Adds a final usage event                                                                                                                                                                                                                                                                    |
| `tools`                                 | array            | Up to 128 function tools. See [Tool calling](#tool-calling)                                                                                                                                                                                                                                                           |
| `tool_choice`                           | string or object | `none`, `auto`, `required`, or a named function                                                                                                                                                                                                                                                                       |
| `parallel_tool_calls`                   | boolean          | Default `false`. See [Tool calling](#tool-calling)                                                                                                                                                                                                                                                                    |
| `response_format`                       | object           | `text`, `json_object`, or `json_schema` with `strict: true`. See [Tool calling](#tool-calling) for use with tools                                                                                                                                                                                                     |
| `reasoning_effort` / `reasoning`        | string / object  | Optional. Turns thinking on or off; there are no effort levels. Send at most one of the two. See [Thinking](#thinking)                                                                                                                                                                                                |
| `temperature`                           | number           | 0 to 2                                                                                                                                                                                                                                                                                                                |
| `top_p`                                 | number           | 0 to 1                                                                                                                                                                                                                                                                                                                |
| `presence_penalty`, `frequency_penalty` | number           | -2 to 2                                                                                                                                                                                                                                                                                                               |
| `stop`                                  | string or array  | Up to 4 strings                                                                                                                                                                                                                                                                                                       |
| `n`                                     | integer          | Only `1`                                                                                                                                                                                                                                                                                                              |

Message content is text only: a string, or an array of `{"type": "text", "text": "..."}` parts. Images, audio and files are not supported. An `assistant` message that carries `tool_calls` may have `content: null`, and a `tool` message carries the result as text together with its `tool_call_id`; see [Tool calling](#tool-calling).

Requests must be `application/json`, uncompressed, at most 2 MiB, and without a query string. The one exception is `?beta=true` on `/v1/messages`, which the Anthropic SDKs add and which is accepted.

### Response <a href="#response" id="response"></a>

```json
{
  "id": "chatcmpl-9b1c0d2e3f4a5b6c7d8e9f0a",
  "object": "chat.completion",
  "created": 1763337600,
  "model": "qwen3p8-27b",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "A liquidity pool is a smart contract that holds two or more tokens so traders can swap between them without an order book. Liquidity providers deposit the tokens and earn a share of the trading fees."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 21,
    "completion_tokens": 42,
    "total_tokens": 63,
    "nansen_credits_cost": "0.0882"
  }
}
```

* `finish_reason` is `stop`, `length`, `tool_calls` or `content_filter`.
* `usage.nansen_credits_cost` is the exact charge for the request in credits, as a decimal string.
* `usage.prompt_tokens_details.cached_tokens` and `usage.completion_tokens_details.reasoning_tokens` appear when they apply.
* Every response has an `x-request-id` header. Keep it for support requests. On completions it is `req-` followed by 32 hex characters and also works in the [usage lookup](#checking-what-a-request-cost). Requests rejected before they reach the model, such as a bad key or a rate limit, can carry an id in another format that has no usage record.

### Streaming <a href="#streaming" id="streaming"></a>

Set `stream: true` to receive server-sent events. Add `stream_options.include_usage` to get the token counts and the credit cost in a final event before `data: [DONE]`. In rare cases the usage or the cost is missing from a response; the [usage lookup](#checking-what-a-request-cost) then has the settled amount.

{% tabs %}
{% tab title="curl" %}

```bash
curl -sN https://api.nansen.ai/api/v1beta1/inference/chat/completions \
  -H "Content-Type: application/json" \
  -H "apikey: $NANSEN_API_KEY" \
  -d '{
    "model": "qwen3p8-27b",
    "messages": [{"role": "user", "content": "Write a haiku about block times."}],
    "stream": true,
    "stream_options": {"include_usage": true}
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import os

from openai import OpenAI

client = OpenAI(
    base_url="https://api.nansen.ai/api/v1beta1/inference",
    api_key=os.environ["NANSEN_API_KEY"],
)

stream = client.chat.completions.create(
    model="qwen3p8-27b",
    messages=[{"role": "user", "content": "Write a haiku about block times."}],
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        cost = (chunk.usage.model_extra or {}).get("nansen_credits_cost", "unknown")
        print(f"\n{chunk.usage.total_tokens} tokens, {cost} credits")
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.nansen.ai/api/v1beta1/inference",
  apiKey: process.env.NANSEN_API_KEY,
});

const stream = await client.chat.completions.create({
  model: "qwen3p8-27b",
  messages: [{ role: "user", content: "Write a haiku about block times." }],
  stream: true,
  stream_options: { include_usage: true },
});
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
  if (chunk.usage) {
    console.log(`\n${chunk.usage.total_tokens} tokens, ${chunk.usage.nansen_credits_cost ?? "unknown"} credits`);
  }
}
```

{% endtab %}
{% endtabs %}

If you parse the stream yourself:

* **Skip comment lines.** After 15 seconds of silence the stream sends `: keep-alive`. Lines that start with `:` carry no data and are never billed. If nothing has been sent yet, the first of these is the opening `{"role": "assistant"}` event instead.
* **A stream without `data: [DONE]` has failed.** Once a stream is open, an error arrives as a single `data: {"error": {...}}` event and the stream ends without `[DONE]`.
* **Thinking streams separately.** Thinking text arrives in `delta.reasoning_content`, the answer in `delta.content`.

{% hint style="info" %}
Use streaming for long outputs. A non-streaming response sends nothing until it is complete, and connections that stay silent for about 100 seconds can be closed along the way.
{% endhint %}

### Thinking <a href="#thinking" id="thinking"></a>

Thinking is **off by default**. Turn it on per request with either field:

```json
{
  "model": "qwen3p8-27b",
  "messages": [{"role": "user", "content": "A token has a supply of 1 billion and 12% is staked. How many tokens are not staked?"}],
  "reasoning": {"enabled": true},
  "max_tokens": 8000
}
```

* **Thinking is a switch, not a dial.** It is either on or off; there are no reasoning levels.
* `"reasoning": {"enabled": true}` turns it on. `"reasoning_effort": "none"` or `"reasoning": {"enabled": false}` turns it off.
* Any other `reasoning_effort` value (`minimal`, `low`, `medium`, `high`, `xhigh`) also turns it on, and they all do exactly the same thing: `high` does not think more than `low`. The response then carries a `Warning` header saying that effort levels are not supported.
* The thinking text is returned in `message.reasoning_content`. Send `"reasoning": {"enabled": true, "exclude": true}` to think without returning the text.
* Thinking tokens are output tokens. They count toward `max_tokens` and are billed at the output price, so give thinking requests a larger `max_tokens`. If thinking uses the whole limit, the response ends with `finish_reason: "length"` and an empty `content`.
* `enable_thinking` and `chat_template_kwargs` are not accepted.

### Tool calling <a href="#tool-calling" id="tool-calling"></a>

Function tools follow the OpenAI format: up to 128 tools, with names of 1 to 64 letters, digits, `_` or `-`.

```bash
curl -s https://api.nansen.ai/api/v1beta1/inference/chat/completions \
  -H "Content-Type: application/json" \
  -H "apikey: $NANSEN_API_KEY" \
  -d '{
    "model": "qwen3p8-27b",
    "messages": [{"role": "user", "content": "What are the prices of ETH and SOL?"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_token_price",
        "description": "Get the current USD price of a token.",
        "parameters": {
          "type": "object",
          "properties": {"symbol": {"type": "string"}},
          "required": ["symbol"],
          "additionalProperties": false
        }
      }
    }],
    "tool_choice": "auto",
    "parallel_tool_calls": true
  }'
```

{% hint style="warning" %}
Send `"parallel_tool_calls": true` unless you need at most one call per turn. The default is `false`, and a turn in which the model makes more than one call then fails: with `500 invalid_model_response` when not streaming, and with `inference_unavailable` when streaming, either as a `503` or as an error event if the stream is already open.
{% endhint %}

To continue the conversation, send the assistant message back with its `tool_calls` (its `content` may be `null`), followed by one `tool` message per call. Each `tool` message needs `content` and the `tool_call_id` of the call it answers.

```bash
curl -s https://api.nansen.ai/api/v1beta1/inference/chat/completions \
  -H "Content-Type: application/json" \
  -H "apikey: $NANSEN_API_KEY" \
  -d '{
    "model": "qwen3p8-27b",
    "messages": [
      {"role": "user", "content": "What are the prices of ETH and SOL?"},
      {"role": "assistant", "content": null, "tool_calls": [
        {"id": "call_1", "type": "function", "function": {"name": "get_token_price", "arguments": "{\"symbol\": \"ETH\"}"}},
        {"id": "call_2", "type": "function", "function": {"name": "get_token_price", "arguments": "{\"symbol\": \"SOL\"}"}}
      ]},
      {"role": "tool", "tool_call_id": "call_1", "content": "{\"price_usd\": 3120.55}"},
      {"role": "tool", "tool_call_id": "call_2", "content": "{\"price_usd\": 148.2}"}
    ],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_token_price",
        "description": "Get the current USD price of a token.",
        "parameters": {
          "type": "object",
          "properties": {"symbol": {"type": "string"}},
          "required": ["symbol"],
          "additionalProperties": false
        }
      }
    }],
    "parallel_tool_calls": true
  }'
```

Completed tool call arguments are checked against your schema before a non-streaming response is returned. When streaming, argument fragments arrive before that check, so run a tool only after the stream ends with `data: [DONE]`. Arguments cut off by `finish_reason: "length"` or `"content_filter"` are not checked.

Structured output (`response_format` with `json_object` or `json_schema`) can be sent together with tools only when `tool_choice` is `"none"`; otherwise the request is rejected with `400`. The `text` format has no such restriction.

### Pricing <a href="#pricing" id="pricing"></a>

Inference is billed per token from the same credit balance as the rest of the API. See [Credits](https://docs.nansen.ai/getting-started/credits.md) for how credits work.

| Token type                              | Credits per 1M tokens |
| --------------------------------------- | --------------------- |
| Input                                   | 200                   |
| Cached input, when the discount applies | 50                    |
| Output, including thinking              | 2,000                 |

* You pay for the tokens a request actually used. There is no per-request fee and no minimum charge.
* Charges are fractional. A request that uses 100 input tokens and 150 output tokens costs 0.32 credits.
* Rejected requests, service errors, timeouts and capacity rejections are not charged. A response that was sent to you in full is charged, even if the connection then fails before it closes cleanly. A stream whose output was fully sent and then failed the final check against your tools or schema is charged. Use the [usage lookup](#checking-what-a-request-cost) when unsure.
* If you close a **streaming** request after the model has started responding and before the final usage event, the request can be charged for its input and for the output generated before you disconnected. Those token counts are measured by the service rather than reported by the model and leave out anything generated after you disconnected. The input is charged at the full input rate, except the part that an earlier request from your account sent in the last 10 minutes (such as the conversation history of the previous turn), which is charged at the cached input rate. The charge never exceeds the credits held. The usage lookup then shows `"usage_estimated": true`. Closing a stream before the model starts responding, or closing a non-streaming request before its response has been sent, is not charged.
* Reported cached tokens do not always earn the cached price; `nansen_credits_cost` is the amount actually charged.
* `GET /models` and `GET /usage/{request_id}` cost no credits.

### Output limit and credits <a href="#output-limit-and-credits" id="output-limit-and-credits"></a>

Before a request runs, credits are held for the most it could cost: an upper bound on its input, based on the size of the request, plus `max_tokens` output tokens, rounded up to whole credits. The hold is therefore usually larger than the final charge. When the request finishes you are charged for actual usage and the rest of the hold is released.

* **If you set `max_tokens`**, the value is used exactly. If your balance cannot cover the hold, the request fails with `403 insufficient_credits` and a message that states the possible cost and your balance.
* **If you leave it out**, the largest limit that fits both your balance and the key's remaining credit limits is applied, up to 16,384. At 16,384 the hold is about 34 credits for a small request, so set `max_tokens` when you run requests in parallel. If fewer than 512 tokens fit, the request fails: `403 insufficient_credits` for the balance, `429 api_key_credit_limit_reached` for a key limit.
* **Parallel requests share the balance.** Credits held by requests in progress are not available to new ones until they finish.
* **API key credit limits apply.** A key's daily and monthly credit limits count inference like any other paid call. A request with an explicit `max_tokens` whose hold would pass a limit fails with `429 api_key_credit_limit_reached`.

To run short requests on a low balance, send a small `max_tokens`.

Successful responses report what was decided:

| Header                        | Meaning                                                                   |
| ----------------------------- | ------------------------------------------------------------------------- |
| `X-Nansen-Max-Tokens-Applied` | The output limit used: your `max_tokens`, or the default that was applied |
| `X-Nansen-Credits-Held`       | Whole credits held while the request ran                                  |
| `X-Nansen-Credits-Cost`       | The exact charge, in credits. Non-streaming responses only, when known    |

### Checking what a request cost <a href="#checking-what-a-request-cost" id="checking-what-a-request-cost"></a>

* **Non-streaming:** read the `X-Nansen-Credits-Cost` header or `usage.nansen_credits_cost` in the body.
* **Streaming:** read `usage.nansen_credits_cost` in the final usage event. On `/chat/completions` that event is sent only with `stream_options.include_usage: true`.
* **Afterwards:** look the request up by its `x-request-id`.

```bash
curl -s https://api.nansen.ai/api/v1beta1/inference/usage/req-0123456789abcdef0123456789abcdef \
  -H "apikey: $NANSEN_API_KEY"
```

```json
{
  "id": "req-0123456789abcdef0123456789abcdef",
  "object": "inference.usage",
  "model": "qwen3p8-27b",
  "status": "charged",
  "usage": {"prompt_tokens": 100, "completion_tokens": 150, "total_tokens": 250},
  "credits_charged": "0.32",
  "credits_held": 0,
  "created": 1763337600,
  "finished": 1763337602
}
```

| `status`   | Meaning                                                                               |
| ---------- | ------------------------------------------------------------------------------------- |
| `pending`  | Still running, or not settled yet. `credits_held` is reserved, nothing is charged     |
| `charged`  | Settled with a charge. `credits_charged` is the exact amount                          |
| `refunded` | Settled without a charge, and the hold was released. The record has no `usage` object |

Use the same API key account that made the request. An id that is unknown, malformed or belongs to another account returns `404 usage_not_found`.

The lookup is authoritative: if a response did not reach you completely, check here rather than relying on a partial response. Your remaining balance is `credits_remaining` on `GET /api/v1/account`.

### Limits <a href="#limits" id="limits"></a>

| Limit                        | Value                            |
| ---------------------------- | -------------------------------- |
| Context window               | 250,000 tokens                   |
| Output per request           | 16,384 tokens, thinking included |
| Request body                 | 2 MiB                            |
| Messages per request         | 2,048                            |
| Tools per request            | 128                              |
| Requests in progress at once | 4 on Free, 12 on paid plans      |
| Generation time per request  | 240 seconds                      |

A change to your limit, for example after a plan change, can take up to 48 hours to apply.

Request-rate limits also apply per account. When you exceed a limit, or when the service is at capacity, you get a `429` that you can retry. Honour the `Retry-After` header when it is present. The `x-ratelimit-limit-second` and `x-ratelimit-limit-minute` response headers show the request-rate limit for all inference requests. Generation requests have a lower per-minute limit that depends on your plan, so a `429` can arrive before those headers reach zero.

### Errors <a href="#errors" id="errors"></a>

Errors from `/chat/completions` and `/responses` use the OpenAI shape:

```json
{
  "error": {
    "message": "Unknown parameter: seed",
    "type": "invalid_request_error",
    "param": "seed",
    "code": "invalid_request"
  }
}
```

| Status | `code`                                                                                  | What to do                                                                                                                                                                                                               |
| ------ | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `400`  | `invalid_request`, `unknown_parameter`, `unsupported_parameter`, `unsupported_encoding` | Fix the request. `param` names the field when a single field is at fault. Rules that involve two fields, such as sending both `max_tokens` and `max_completion_tokens`, return a general message with no `param`         |
| `400`  | `model_not_found`                                                                       | Use a model id from `GET /models`                                                                                                                                                                                        |
| `400`  | `context_length_exceeded`                                                               | Shorten the input or lower `max_tokens`                                                                                                                                                                                  |
| `401`  | `invalid_api_key`                                                                       | Check the key and the header                                                                                                                                                                                             |
| `403`  | `inference_not_enabled`                                                                 | Your account does not have access to the beta yet                                                                                                                                                                        |
| `403`  | `insufficient_credits`                                                                  | Lower `max_tokens` or add credits                                                                                                                                                                                        |
| `403`  | `api_key_disabled`                                                                      | Enable the key or use another one                                                                                                                                                                                        |
| `404`  | `account_profile_unavailable`                                                           | The key's account has no Nansen profile. Do not retry. Sign in to the Nansen app to check the account, or contact support. On `/v1/messages` this is a `403`                                                             |
| `404`  | `usage_not_found`                                                                       | Check the request id. It must come from a completion made by your account                                                                                                                                                |
| `413`  | `request_too_large`                                                                     | Keep the body under 2 MiB                                                                                                                                                                                                |
| `429`  | `rate_limit_exceeded`                                                                   | Slow down and retry                                                                                                                                                                                                      |
| `429`  | `inference_capacity`                                                                    | The service is at capacity, or your account already has its maximum number of requests in progress (see [Limits](#limits)). Retry after the `Retry-After` delay, or wait for one of your requests to finish. Not charged |
| `429`  | `api_key_credit_limit_reached`                                                          | Wait for the key's limit to reset, or raise it                                                                                                                                                                           |
| `500`  | `inference_timeout`                                                                     | Retry. Use streaming and a smaller `max_tokens` for long outputs                                                                                                                                                         |
| `500`  | `invalid_model_response`, `invalid_tool_arguments`, `invalid_structured_output`         | The output did not match your tools or schema. Retry, and see [Tool calling](#tool-calling)                                                                                                                              |
| `503`  | `inference_unavailable`                                                                 | Retry after the `Retry-After` delay                                                                                                                                                                                      |

The Inference API does not return `502` or `504`. `/v1/messages` returns errors in the Anthropic shape, `{"type": "error", "error": {"type": "...", "message": "..."}}`.

Two groups of errors can have a different body on every endpoint, so handle errors by HTTP status first:

* Errors raised before a request reaches the model, such as an invalid key, an oversized body or a rate limit, use the OpenAI shape, on `/v1/messages` too.
* API key restriction errors, such as a disabled key or a key without the required permissions, use the standard Nansen error format described in [Error Handling](https://docs.nansen.ai/getting-started/error-handling.md).

Each retry is a new request and is billed like one, so cap automatic retries in your client.

### Use it with coding tools <a href="#use-it-with-coding-tools" id="use-it-with-coding-tools"></a>

{% tabs %}
{% tab title="Claude Code" %}
Claude Code uses the `/v1/messages` endpoint. Set every model variable to the Nansen model id, otherwise background requests ask for a Claude model and fail with `400`.

```bash
export ANTHROPIC_BASE_URL=https://api.nansen.ai/api/v1beta1/inference
export ANTHROPIC_AUTH_TOKEN=$NANSEN_API_KEY
export ANTHROPIC_MODEL=qwen3p8-27b
export ANTHROPIC_DEFAULT_OPUS_MODEL=qwen3p8-27b
export ANTHROPIC_DEFAULT_SONNET_MODEL=qwen3p8-27b
export ANTHROPIC_DEFAULT_HAIKU_MODEL=qwen3p8-27b
export ANTHROPIC_SMALL_FAST_MODEL=qwen3p8-27b
claude
```

Use `ANTHROPIC_AUTH_TOKEN`, not `ANTHROPIC_API_KEY`: the key must be sent as a Bearer token. The same applies to the Anthropic SDKs, where you pass `auth_token` instead of `api_key`. Token counting (`/v1/messages/count_tokens`) is not available.
{% endtab %}

{% tab title="Codex CLI" %}
Codex uses the `/responses` endpoint. Add this to `~/.codex/config.toml` and export `NANSEN_API_KEY`:

```toml
model = "qwen3p8-27b"
model_provider = "nansen"
model_context_window = 250000
model_auto_compact_token_limit = 200000
web_search = "disabled"
# Optional: turn thinking on. Any value except "none" has the same effect;
# there are no effort levels.
# model_reasoning_effort = "high"

[model_providers.nansen]
name = "Nansen"
base_url = "https://api.nansen.ai/api/v1beta1/inference"
wire_api = "responses"
env_key = "NANSEN_API_KEY"
stream_max_retries = 1
```

`stream_max_retries = 1` keeps Codex from repeating a failed request several times, since each retry is billed as a new request. Codex warns that it has no metadata for the model; that is expected.
{% endtab %}
{% endtabs %}

### Not supported <a href="#not-supported" id="not-supported"></a>

* Image, audio and file input
* Embeddings, files and batch endpoints
* More than one choice per request (`n` greater than 1)
* Stored conversations (`previous_response_id` on `/responses`)
* Server-run tools such as web search or code execution. `/chat/completions` rejects them with `400`; `/responses` leaves them out and adds a `Warning` header
* Token counting on `/v1/messages`


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.nansen.ai/api/inference.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
