> For the complete documentation index, see [llms.txt](https://docs.visdom.virtuslab.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.visdom.virtuslab.com/visdom-ai-gateway/llm-gateway/calling-models.md). Agents can also search and read this documentation through its [MCP server](https://docs.visdom.virtuslab.com/~gitbook/mcp).

# Calling models

Requests to the LLM gateway in the OpenAI and the Anthropic API style, with curl, Python and TypeScript: chat, messages, streamed Responses, embeddings, tool calling and the model list.

You call every model through one address with one key, in either API style. The examples below use the example address `https://llm.ai-gateway.example.com`; your deployment has its own, shown in the console next to every new key.

## Before you start

You need three things:

| What                  | Where it comes from                                                                                                                                                                                                                    |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The gateway's address | Shown in the console when a key is created (*API keys → Create API key*). OpenAI-style clients use it with `/v1` at the end; Anthropic-style clients use it without.                                                                   |
| A key (`sk-...`)      | An [API key](https://docs.visdom.virtuslab.com/visdom-ai-gateway/llm-gateway/api-keys.md) issued for a project, or your own [personal key](https://docs.visdom.virtuslab.com/visdom-ai-gateway/llm-gateway/api-keys.md#personal-keys). |
| A model alias         | The *Models* page in the console, or `GET /v1/models` with your key. Your key can call only the aliases on its project's allow-list.                                                                                                   |

The same key works for both API styles and for Claude Code and Codex. The console shows ready environment variables when it creates a key:

```bash
export OPENAI_BASE_URL=https://llm.ai-gateway.example.com/v1
export OPENAI_API_KEY=sk-...
export ANTHROPIC_BASE_URL=https://llm.ai-gateway.example.com
export ANTHROPIC_AUTH_TOKEN=sk-...
```

{% hint style="info" %}
On the Anthropic route `/v1/messages` the gateway accepts the key either as `x-api-key: sk-...` (the Anthropic SDKs' `api_key`) or as `Authorization: Bearer sk-...` (Claude Code's `ANTHROPIC_AUTH_TOKEN`). On the OpenAI routes use `Authorization: Bearer`.
{% endhint %}

## Chat completions (OpenAI style)

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

```bash
curl https://llm.ai-gateway.example.com/v1/chat/completions \
  -H "Authorization: Bearer sk-..." \
  -H "Content-Type: application/json" \
  -d '{
        "model": "demo-assistant",
        "messages": [{"role": "user", "content": "Summarise the card refund policy in one sentence."}]
      }'
```

```json
{
  "id": "chatcmpl-cdc07693-efd4-4738-a37d-0be1911d0dbf",
  "model": "demo-assistant",
  "object": "chat.completion",
  "choices": [{
    "finish_reason": "stop",
    "index": 0,
    "message": {"role": "assistant", "content": "Here is a short answer from the demo assistant, served through the Visdom AI Gateway."}
  }],
  "usage": {"completion_tokens": 22, "prompt_tokens": 22, "total_tokens": 44}
}
```

{% endtab %}

{% tab title="Python (openai SDK)" %}

```python
from openai import OpenAI

client = OpenAI(base_url="https://llm.ai-gateway.example.com/v1", api_key="sk-...")

reply = client.chat.completions.create(
    model="demo-assistant",
    messages=[{"role": "user", "content": "Summarise the card refund policy in one sentence."}],
)
print(reply.choices[0].message.content)
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://llm.ai-gateway.example.com/v1", apiKey: "sk-..." });

const reply = await client.chat.completions.create({
  model: "demo-assistant",
  messages: [{ role: "user", content: "Summarise the card refund policy in one sentence." }],
});
console.log(reply.choices[0].message.content);
```

{% endtab %}
{% endtabs %}

Add `"stream": true` for server-sent events, as the provider sends them. Structured output (`response_format` with a JSON schema) and image input (`image_url` content parts) pass through unchanged.

## Messages (Anthropic style)

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

```bash
curl https://llm.ai-gateway.example.com/v1/messages \
  -H "x-api-key: sk-..." \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
        "model": "demo-assistant",
        "max_tokens": 200,
        "messages": [{"role": "user", "content": "Summarise the card refund policy in one sentence."}]
      }'
```

```json
{
  "type": "message",
  "role": "assistant",
  "model": "demo-assistant",
  "content": [{"type": "text", "text": "Here is a short answer from the demo assistant, served through the Visdom AI Gateway."}],
  "stop_reason": "end_turn",
  "usage": {"input_tokens": 21, "output_tokens": 22}
}
```

{% endtab %}

{% tab title="Python (anthropic SDK)" %}

```python
import anthropic

client = anthropic.Anthropic(base_url="https://llm.ai-gateway.example.com", api_key="sk-...")

message = client.messages.create(
    model="claude-sonnet",
    max_tokens=200,
    messages=[{"role": "user", "content": "Summarise the card refund policy in one sentence."}],
)
print(message.content[0].text)
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({ baseURL: "https://llm.ai-gateway.example.com", apiKey: "sk-..." });

const message = await client.messages.create({
  model: "claude-sonnet",
  max_tokens: 200,
  messages: [{ role: "user", content: "Summarise the card refund policy in one sentence." }],
});
console.log(message.content);
```

{% endtab %}
{% endtabs %}

The model is an alias from the catalogue, not a provider's model name. Any alias works on this route, including models that are not Anthropic's: the gateway translates.

`max_tokens` is required, as on Anthropic's own API. Without it (or without `model` or `messages`), the gateway answers HTTP 400 in Anthropic's error shape before any provider is called, streamed or not:

```json
{"type": "error", "error": {"type": "invalid_request_error", "message": "max_tokens: Field required"}}
```

Count the tokens of a request without calling the model:

```bash
curl https://llm.ai-gateway.example.com/v1/messages/count_tokens \
  -H "x-api-key: sk-..." -H "anthropic-version: 2023-06-01" -H "Content-Type: application/json" \
  -d '{"model": "demo-assistant", "messages": [{"role": "user", "content": "hello there"}]}'
# {"input_tokens": 9}
```

## Streamed Responses API

The OpenAI Responses API is what Codex uses. Streamed, it ends with a `response.completed` event.

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

```bash
curl -N https://llm.ai-gateway.example.com/v1/responses \
  -H "Authorization: Bearer sk-..." \
  -H "Content-Type: application/json" \
  -d '{"model": "demo-assistant", "stream": true, "input": "Which payment rails does SEPA cover?"}'
```

```
data: {"type":"response.created","response":{"id":"resp_...", ...}}
data: {"type":"response.in_progress", ...}
data: {"type":"response.output_item.added", ...}
data: {"type":"response.output_text.delta","delta":"Here is a short answer f...", ...}
data: {"type":"response.output_text.done", ...}
data: {"type":"response.completed", ...}
```

{% endtab %}

{% tab title="Python (openai SDK)" %}

```python
from openai import OpenAI

client = OpenAI(base_url="https://llm.ai-gateway.example.com/v1", api_key="sk-...")

stream = client.responses.create(
    model="demo-assistant",
    input="Which payment rails does SEPA cover?",
    stream=True,
)
for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://llm.ai-gateway.example.com/v1", apiKey: "sk-..." });

const stream = await client.responses.create({
  model: "demo-assistant",
  input: "Which payment rails does SEPA cover?",
  stream: true,
});
for await (const event of stream) {
  if (event.type === "response.output_text.delta") process.stdout.write(event.delta);
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
With the output guard in `buffered` mode (the default), a stream is collected, checked and then released at once: the first token arrives when the model has finished. A model or project in `chunked` mode keeps the stream flowing. See [Guardrails](https://docs.visdom.virtuslab.com/visdom-ai-gateway/llm-gateway/guardrails.md#output-guard).
{% endhint %}

## Embeddings

Embeddings work with aliases marked `mode: embedding` in the catalogue, for example `demo-embed` or a local model such as `local-embed`.

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

```bash
curl https://llm.ai-gateway.example.com/v1/embeddings \
  -H "Authorization: Bearer sk-..." \
  -H "Content-Type: application/json" \
  -d '{"model": "demo-embed", "input": ["A customer asks about a card refund", "Klient pyta o zwrot za kartę"]}'
```

```json
{
  "model": "demo-embed",
  "object": "list",
  "data": [
    {"object": "embedding", "index": 0, "embedding": [0.094683, 0.370707, 0.223066, ...]},
    {"object": "embedding", "index": 1, "embedding": [0.307004, -0.300642, 0.058856, ...]}
  ]
}
```

{% endtab %}

{% tab title="Python (openai SDK)" %}

```python
from openai import OpenAI

client = OpenAI(base_url="https://llm.ai-gateway.example.com/v1", api_key="sk-...")

result = client.embeddings.create(
    model="demo-embed",
    input=["A customer asks about a card refund", "Klient pyta o zwrot za kartę"],
)
print(len(result.data), len(result.data[0].embedding))
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://llm.ai-gateway.example.com/v1", apiKey: "sk-..." });

const result = await client.embeddings.create({
  model: "demo-embed",
  input: ["A customer asks about a card refund", "Klient pyta o zwrot za kartę"],
});
console.log(result.data.length, result.data[0].embedding.length);
```

{% endtab %}
{% endtabs %}

The input of an embeddings request goes through the same guardrails as a prompt: personal data in it is masked before the provider sees it. The `dimensions` parameter is refused (HTTP 400) for a model the gateway does not know to support it, such as an OpenAI-compatible local model.

## Tool calling

Tool definitions and tool calls pass through unchanged, in both styles, streamed or not.

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

```bash
curl https://llm.ai-gateway.example.com/v1/chat/completions \
  -H "Authorization: Bearer sk-..." \
  -H "Content-Type: application/json" \
  -d '{
        "model": "demo-tools",
        "messages": [{"role": "user", "content": "What is the balance of my main account?"}],
        "tools": [{
          "type": "function",
          "function": {
            "name": "get_balance",
            "parameters": {"type": "object", "properties": {"account": {"type": "string"}}, "required": ["account"]}
          }
        }]
      }'
```

```json
{
  "model": "demo-tools",
  "choices": [{
    "finish_reason": "tool_calls",
    "message": {
      "role": "assistant",
      "content": null,
      "tool_calls": [{"id": "call_0c7b...", "type": "function",
                      "function": {"name": "get_balance", "arguments": "{\"account\":\"demo account\"}"}}]
    }
  }]
}
```

{% endtab %}

{% tab title="Python (openai SDK)" %}

```python
from openai import OpenAI

client = OpenAI(base_url="https://llm.ai-gateway.example.com/v1", api_key="sk-...")

tools = [{
    "type": "function",
    "function": {
        "name": "get_balance",
        "parameters": {"type": "object", "properties": {"account": {"type": "string"}}, "required": ["account"]},
    },
}]
reply = client.chat.completions.create(
    model="demo-tools",
    messages=[{"role": "user", "content": "What is the balance of my main account?"}],
    tools=tools,
)
call = reply.choices[0].message.tool_calls[0]
print(call.function.name, call.function.arguments)
```

{% endtab %}

{% tab title="Python (anthropic SDK)" %}

```python
import anthropic

client = anthropic.Anthropic(base_url="https://llm.ai-gateway.example.com", api_key="sk-...")

message = client.messages.create(
    model="demo-tools",
    max_tokens=200,
    messages=[{"role": "user", "content": "What is the balance of my main account?"}],
    tools=[{
        "name": "get_balance",
        "input_schema": {"type": "object", "properties": {"account": {"type": "string"}}},
    }],
)
print(message.stop_reason)  # tool_use
print([block for block in message.content if block.type == "tool_use"])
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://llm.ai-gateway.example.com/v1", apiKey: "sk-..." });

const reply = await client.chat.completions.create({
  model: "demo-tools",
  messages: [{ role: "user", content: "What is the balance of my main account?" }],
  tools: [{
    type: "function",
    function: {
      name: "get_balance",
      parameters: { type: "object", properties: { account: { type: "string" } }, required: ["account"] },
    },
  }],
});
console.log(reply.choices[0].message.tool_calls);
```

{% endtab %}
{% endtabs %}

Whether a model actually calls tools is up to the model: local models served by vLLM or Ollama rarely support it.

## Listing models

`GET /v1/models` returns the aliases your key can call: its project's allow-list, or the key's own list if it is limited to some models.

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

```bash
curl https://llm.ai-gateway.example.com/v1/models -H "Authorization: Bearer sk-..."
```

```json
{
  "object": "list",
  "data": [
    {"id": "demo-resilient", "object": "model", "created": 1677610602, "owned_by": "openai"},
    {"id": "demo-tools", "object": "model", "created": 1677610602, "owned_by": "openai"}
  ]
}
```

{% endtab %}

{% tab title="Python (openai SDK)" %}

```python
from openai import OpenAI

client = OpenAI(base_url="https://llm.ai-gateway.example.com/v1", api_key="sk-...")
print([m.id for m in client.models.list()])
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://llm.ai-gateway.example.com/v1", apiKey: "sk-..." });
for await (const model of client.models.list()) console.log(model.id);
```

{% endtab %}
{% endtabs %}

The `owned_by` field is LiteLLM's and does not name the provider. The console's *Models* page shows the provider, region and prices of each alias.

## Response headers

Every answer carries headers that tell you what the gateway did. An excerpt from a call whose prompt held a PESEL and an e-mail address:

```http
HTTP/1.1 200 OK
x-litellm-call-id: 094cd3bd-f61f-467e-9861-15b0bb28be67
x-litellm-model-group: demo-assistant
x-litellm-model-id: demo-assistant
x-litellm-response-cost: 0.000396
x-litellm-key-spend: 0.000396
x-litellm-attempted-retries: 0
x-litellm-attempted-fallbacks: 0
x-visdom-masked: PESEL=1, e-mail=1
x-visdom-output-guard: buffered
```

| Header                          | Meaning                                                                                              |
| ------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `x-visdom-masked`               | Personal data or a bank masking rule was masked in your request: kinds and counts, never the values. |
| `x-visdom-output-guard`         | The answer was checked: `buffered` or `chunked`.                                                     |
| `x-visdom-output-masked`        | Something was masked in the answer (non-streamed answers only).                                      |
| `x-litellm-model-group`         | The alias that answered. After a fallback it differs from the alias you asked for.                   |
| `x-litellm-attempted-fallbacks` | How many fallback hops it took (0: the alias you asked for answered).                                |
| `x-litellm-response-cost`       | The estimated cost of this call in USD, at the catalogue's prices.                                   |

The full list, with the status codes, is in [Status codes and headers](https://docs.visdom.virtuslab.com/visdom-ai-gateway/reference/errors-and-headers.md). What the guardrails mask and refuse is in [Guardrails](https://docs.visdom.virtuslab.com/visdom-ai-gateway/llm-gateway/guardrails.md).

## Errors you may see

| Status | Typical cause                                                                                                                                   |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| 400    | A parameter the provider does not support (the gateway does not drop it silently); `/v1/messages` without `max_tokens`.                         |
| 401    | Key unknown, revoked or expired; the project's LLM access is switched off.                                                                      |
| 403    | Alias not on the project's allow-list or the key's models; model switched off; a secret or a refusing bank rule in the prompt or the answer.    |
| 429    | Budget exceeded (project set to *Block new calls*, the key's own limit, or your personal budget); requests or tokens per minute over the limit. |
| 503    | Presidio is configured but cannot be reached, and the gateway is set to refuse calls then.                                                      |

Errors come in the OpenAI envelope on every route, `/v1/messages` included (the missing `max_tokens` case above is the one exception):

```json
{"error": {"message": "team not allowed to access model. This team can only access models=['demo-assistant']. Tried to access demo-tools",
           "type": "team_model_access_denied", "param": "model", "code": "403"}}
```

The messages of these errors are LiteLLM's: its "team" is the project.

## The Anthropic pass-through

The gateway also exposes Anthropic's own API unchanged under `/anthropic/*` (for example `/anthropic/v1/messages`, `/anthropic/v1/messages/count_tokens` and Message Batches). Use it only for Anthropic endpoints the unified route `/v1/messages` lacks. It differs from the unified route:

|                                           | `/v1/messages`                         | `/anthropic/*`                                                                     |
| ----------------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------------- |
| Model name                                | An alias from the catalogue            | Anthropic's own model name, which must be on the project's allow-list by that name |
| Fallback, routing to other providers      | Yes                                    | No                                                                                 |
| Budgets, rate limits, project attribution | Yes                                    | Yes                                                                                |
| Guardrails on the request                 | Yes, with `x-visdom-masked`            | Secrets refused and personal data masked, but no `x-visdom-masked` header          |
| Output guard on the answer                | Yes                                    | **No**                                                                             |
| Attribution and sessions in AI Tracing    | Yes                                    | **No** (the tracing headers reach Anthropic as sent)                               |
| Authentication                            | `x-api-key` or `Authorization: Bearer` | **`x-api-key` only**                                                               |

{% hint style="warning" %}
On `/anthropic/*` send the gateway key as `x-api-key` (`ANTHROPIC_API_KEY` in Claude Code and the SDKs), never as `Authorization: Bearer`. LiteLLM forwards an `Authorization` header to Anthropic as it came, so the gateway key would reach Anthropic next to the organisation's own key. Where answers must be checked, use `/v1/messages`.
{% endhint %}

```bash
curl https://llm.ai-gateway.example.com/anthropic/v1/messages \
  -H "x-api-key: sk-..." \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{"model": "claude-haiku-4-5", "max_tokens": 50, "messages": [{"role": "user", "content": "ready?"}]}'
```

The budget dialog on the *Budgets* page offers only catalogue aliases, so an operator puts an Anthropic model name such as `claude-haiku-4-5` on a project's allow-list through the console API (`PUT /api/projects/{id}/budget`, field `allowedModels`).

The gateway replaces your key with the organisation's `ANTHROPIC_API_KEY` before the call leaves. Cost is recorded from Anthropic's price list for non-streamed calls; streamed calls are costed when the target is `api.anthropic.com`.
