> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Integração com o Anthropic Claude

> Acesse os modelos Claude pelo Toqan Router. Use Claude Opus 5, Sonnet 5 e Haiku 4.5 com recursos aprimorados de roteamento, cache e gerenciamento de prompts.

## Configure sua chave de API

Para usar a Anthropic com o Toqan Router, siga estas etapas:

1. Navegue até **AI Gateway** > BYOK
2. Encontre **Anthropic** na lista
3. Clique no botão **Configure** ao lado de Anthropic
4. No modal que se abre, selecione <kbd>Setup your own API Key</kbd>
5. Insira um nome para esta configuração (por exemplo, "Anthropic Production")
6. Cole sua chave de API da Anthropic no campo indicado
7. Clique em **Save** para concluir a configuração

Sua chave de API da Anthropic agora está configurada e pronta para uso com o Toqan Router no **AI Studio** ou por meio do **AI Gateway**.

## Início rápido

Acesse os modelos Claude da Anthropic por meio do **AI Gateway**.

O **Anthropic SDK** aponta para `https://router.toqan.ai/eu/v3/anthropic` e acrescenta `/v1/messages` por conta própria; o cliente da OpenAI aponta para a URL base do router, `https://router.toqan.ai/eu/v3/router`. Consulte a referência da [Anthropic Messages API](/docs/pt-BR/ai-gateway/features/anthropic-messages-api.md) para ver todos os endpoints disponíveis.

```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://router.toqan.ai/eu/v3/router/responses \
  -H "Authorization: Bearer $TOQAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-5",
    "input": "Explain quantum computing in simple terms"
  }'
```

```typescript TypeScript (Anthropic SDK) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/anthropic",
});

const message = await client.messages.create({
  model: "anthropic/claude-sonnet-5",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Explain quantum computing in simple terms" }],
});

console.log(message.content[0].text);
```

```python Python (Anthropic SDK) theme={"theme":{"light":"github-light","dark":"github-dark"}}
from anthropic import Anthropic
import os

client = Anthropic(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/anthropic",
)

message = client.messages.create(
    model="anthropic/claude-sonnet-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Explain quantum computing in simple terms"}],
)

print(message.content[0].text)
```

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.responses.create({
  model: "anthropic/claude-sonnet-5",
  input: "Explain quantum computing in simple terms",
});

console.log(response.output_text);
```

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/router",
)

response = client.responses.create(
    model="anthropic/claude-sonnet-5",
    input="Explain quantum computing in simple terms",
)

print(response.output_text)
```

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5",
  messages: [
    {
      role: "user",
      content: "Explain quantum computing in simple terms",
    },
  ],
  max_tokens: 1024,
});

console.log(response.choices[0].message.content);
```

```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/router",
)

response = client.chat.completions.create(
    model="anthropic/claude-sonnet-5",
    messages=[
        {
            "role": "user",
            "content": "Explain quantum computing in simple terms",
        }
    ],
    max_tokens=1024,
)

print(response.choices[0].message.content)
```

## Modelos disponíveis

O Toqan Router é compatível com todos os modelos Anthropic Claude em vários provedores, para garantir a melhor disponibilidade e os melhores preços:

### Modelos mais recentes

| Modelo | Contexto | Pontos fortes | Ideal para |
| - | - | - | - |
| `claude-fable-5` | 1M | Máxima inteligência, raciocínio com thinking ativado | Programação, tarefas agênticas, raciocínio complexo |
| `claude-opus-5` | 1M | Máxima inteligência, esforço de raciocínio extra-alto | Programação, tarefas agênticas, raciocínio complexo |
| `claude-sonnet-5` | 1M | Melhor equilíbrio | A maioria das tarefas, programação |
| `claude-haiku-4-5-20251001` | 200K | Respostas rápidas | Tarefas simples, chat |

### Opções de provedor

Os modelos da Anthropic estão disponíveis por meio de vários provedores:

* **`anthropic/`**: API direta da Anthropic
* **`aws/`**: AWS Bedrock (recursos corporativos)
* **`google/`**: Google Vertex AI (integração com o GCP)

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Use these model strings inside your responses.create() or chat.completions.create() call

// Direct Anthropic
model: "anthropic/claude-sonnet-5"

// AWS Bedrock
model: "aws/global.anthropic.claude-sonnet-5"

// Google Vertex AI
model: "google/global.claude-opus-5"
```

Para ver a lista completa de modelos compatíveis, consulte [Modelos compatíveis](/docs/pt-BR/ai-gateway/supported-models.md).

## Usando o AI Gateway

Acesse os modelos Claude (Claude Opus 5, Sonnet 5 e Haiku 4.5) por meio do **AI Gateway** com APIs de mensagens avançadas, recursos de uso de ferramentas e roteamento inteligente de modelos. Todos os modelos Claude estão disponíveis com formatação e preços consistentes em vários provedores.

> [!NOTE]
>
> Os modelos Claude usam o formato de slug de provedor: `anthropic/model-name`. Por exemplo: `anthropic/claude-sonnet-5`

### Pré-requisitos

Antes de fazer solicitações ao **AI Gateway**, você precisa configurar seu ambiente e instalar os SDKs, caso opte por usá-los.

**Endpoint**

```
POST https://router.toqan.ai/eu/v3/router/responses
POST https://router.toqan.ai/eu/v3/anthropic/v1/messages
```

**Headers obrigatórios**

Inclua os seguintes headers em todas as solicitações:

```
Authorization: Bearer $TOQAN_API_KEY
Content-Type: application/json
```

**Obtendo sua chave de API:**

1. Acesse Chaves de API
2. Clique em <kbd>Create API Key</kbd> e copie a chave
3. Armazene-a no seu ambiente como `TOQAN_API_KEY`

**Instalação do SDK**

Instale o SDK correspondente:

```bash Node.js/TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
npm install openai
# or
yarn add openai
```

```bash Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
pip install openai
```

```bash Node.js/TypeScript (Anthropic SDK) theme={"theme":{"light":"github-light","dark":"github-dark"}}
npm install @anthropic-ai/sdk
```

```bash Python (Anthropic SDK) theme={"theme":{"light":"github-light","dark":"github-dark"}}
pip install anthropic
```

### Uso básico

> [!TIP]
>
> Se o seu código da OpenAI já estiver funcionando, basta alterar `base_url` e `api_key` para o endpoint do router e `TOQAN_API_KEY`.

#### Chat Completion

```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://router.toqan.ai/eu/v3/router/responses \
  -H "Authorization: Bearer $TOQAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-5",
    "input": "Explain quantum computing in simple terms"
  }'
```

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.responses.create({
  model: "anthropic/claude-sonnet-5",
  input: "Explain quantum computing in simple terms",
});

console.log(response.output_text);
```

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/router",
)

response = client.responses.create(
    model="anthropic/claude-sonnet-5",
    input="Explain quantum computing in simple terms",
)

print(response.output_text)
```

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5",
  messages: [
    {
      role: "user",
      content: "Explain quantum computing in simple terms",
    },
  ],
  max_tokens: 1024,
});

console.log(response.choices[0].message.content);
```

```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/router",
)

response = client.chat.completions.create(
    model="anthropic/claude-sonnet-5",
    messages=[{"role": "user", "content": "Explain quantum computing in simple terms"}],
    max_tokens=1024,
)

print(response.choices[0].message.content)
```

#### Streaming

Faça streaming das respostas para obter saída em tempo real em vez de esperar pela resposta completa:

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const stream = await client.responses.create({
  model: "anthropic/claude-sonnet-5",
  input: "Tell me a story",
  stream: true,
});

for await (const event of stream) {
  if (event.type === "response.output_text.delta") {
    process.stdout.write(event.delta);
  }
}
```

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/router",
)

stream = client.responses.create(
    model="anthropic/claude-sonnet-5",
    input="Tell me a story",
    stream=True,
)

for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
```

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const stream = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5",
  messages: [{ role: "user", content: "Tell me a story" }],
  max_tokens: 2048,
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
```

```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/router",
)

stream = client.chat.completions.create(
    model="anthropic/claude-sonnet-5",
    messages=[{"role": "user", "content": "Tell me a story"}],
    max_tokens=2048,
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)
```

### Uso avançado

#### Cache de prompts

> [!NOTE]
>
> O cache de prompts é compatível com o endpoint de Chat Completions (`/v3/router/chat/completions`). Os exemplos abaixo usam as abas de Chat Completions.

Para um guia completo, consulte [Cache de prompts](/docs/pt-BR/ai-gateway/features/prompt-caching.md).

Armazene em cache o contexto usado com frequência (prompts de sistema, documentos grandes, bases de código) para reduzir os custos em até 90% e a latência em até 85%.

```bash cURL (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://router.toqan.ai/eu/v3/router/chat/completions \
  -H "Authorization: Bearer $TOQAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-5",
    "messages": [
      {
        "role": "system",
        "content": [
          {
            "type": "text",
            "text": "You are an expert Python developer with deep knowledge of best practices.",
            "cache_control": { "type": "ephemeral" }
          }
        ]
      },
      {
        "role": "user",
        "content": "Write a function to parse JSON"
      }
    ],
    "max_tokens": 1024
  }'
```

```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get('TOQAN_API_KEY'),
    base_url='https://router.toqan.ai/eu/v3/router'
)

response = client.chat.completions.create(
    model='anthropic/claude-sonnet-5',
    messages=[
        {
            'role': 'system',
            'content': [
                {
                    'type': 'text',
                    'text': 'You are an expert Python developer with deep knowledge of best practices.',
                    'cache_control': {'type': 'ephemeral'}
                }
            ]
        },
        {
            'role': 'user',
            'content': 'Write a function to parse JSON'
        }
    ],
    max_tokens=1024
)
```

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5",
  messages: [
    {
      role: "system",
      content: [
        {
          type: "text",
          text: "You are an expert Python developer with deep knowledge of best practices.",
          cache_control: { type: "ephemeral" },
        },
      ],
    },
    {
      role: "user",
      content: "Write a function to parse JSON",
    },
  ],
  max_tokens: 1024,
});
```

**Como funciona**

O cache de prompts armazena blocos de conteúdo usados com frequência nos servidores da Anthropic para reutilização entre solicitações:

1. **Marque o conteúdo para cache**: adicione `cache_control: { type: "ephemeral" }` aos blocos de texto
2. **Primeira solicitação**: o conteúdo é processado normalmente e armazenado em cache (gravação no cache)
3. **Solicitações seguintes**: o conteúdo em cache é reutilizado (leitura do cache)
4. **Tempo de vida do cache**: 5 minutos a partir do último uso (gerenciado automaticamente)

**Configuração**

Marque os blocos de conteúdo para cache adicionando o parâmetro `cache_control`:

| Parâmetro | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `type` | `"ephemeral"` | Sim | Único tipo de cache compatível |
| `ttl` | `"5m"` \| `"1h"` | Não | Duração do cache (padrão: `"5m"`) |

**Opções de TTL do cache**

O parâmetro `ttl` controla por quanto tempo o conteúdo em cache é mantido:

* `"5m"` (5 minutos): duração padrão do cache
* `"1h"` (1 hora): duração estendida do cache para fluxos de trabalho mais longos

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "cache_control": {
    "type": "ephemeral",
    "ttl": "1h"
  }
}
```

**Regras de posicionamento do cache**

* Adicione `cache_control` à **última** mensagem ou ao último bloco de conteúdo que você deseja armazenar em cache
* Tudo até esse ponto é incluído no cache
* Máximo: 4 breakpoints de cache por solicitação

**Limites mínimos de tokens**

O cache só é ativado quando o conteúdo marcado atinge o mínimo do modelo. Solicitações abaixo do limite são processadas normalmente, com custo integral.

| Modelo | Mínimo de tokens |
| - | - |
| Claude Opus 5, Fable 5 | 512 |
| Claude Opus 4.8, Sonnet 5, Sonnet 4.6, Sonnet 4.5, Opus 4.1, Opus 4, Sonnet 4, Sonnet 3.7 | 1,024 |
| Claude Opus 4.7, Haiku 3.5, Haiku 3 | 2,048 |
| Claude Opus 4.6, Opus 4.5, Haiku 4.5 | 4,096 |

**Casos de uso**

> [accordion] Prompts de sistema estáticos
>
> Armazene em cache definições de papel e instruções que não mudam.
>
> ```bash cURL (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> curl -X POST https://router.toqan.ai/eu/v3/router/chat/completions \
>   -H "Authorization: Bearer $TOQAN_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "model": "anthropic/claude-sonnet-5",
>     "messages": [
>       {
>         "role": "system",
>         "content": [
>           {
>             "type": "text",
>             "text": "You are an expert software engineer specializing in Python.\nYour responses should be:\n- Clear and concise\n- Include code examples\n- Follow PEP 8 style guidelines\n- Include error handling",
>             "cache_control": { "type": "ephemeral" }
>           }
>         ]
>       },
>       {
>         "role": "user",
>         "content": "How do I read a CSV file?"
>       }
>     ],
>     "max_tokens": 1024
>   }'
> ```
>
> ```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> from openai import OpenAI
> import os
>
> client = OpenAI(
>     api_key=os.environ.get('TOQAN_API_KEY'),
>     base_url='https://router.toqan.ai/eu/v3/router'
> )
>
> system_prompt = """You are an expert software engineer specializing in Python.
> Your responses should be:
> - Clear and concise
> - Include code examples
> - Follow PEP 8 style guidelines
> - Include error handling"""
>
> response = client.chat.completions.create(
>     model='anthropic/claude-sonnet-5',
>     messages=[
>         {
>             'role': 'system',
>             'content': [
>                 {
>                     'type': 'text',
>                     'text': system_prompt,
>                     'cache_control': {'type': 'ephemeral'}
>                 }
>             ]
>         },
>         {
>             'role': 'user',
>             'content': 'How do I read a CSV file?'
>         }
>     ],
>     max_tokens=1024
> )
> ```
>
> ```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import OpenAI from "openai";
>
> const client = new OpenAI({
>   apiKey: process.env.TOQAN_API_KEY,
>   baseURL: "https://router.toqan.ai/eu/v3/router",
> });
>
> const response = await client.chat.completions.create({
>   model: 'anthropic/claude-sonnet-5',
>   messages: [
>     {
>       role: 'system',
>       content: [
>         {
>           type: 'text',
>           text: `You are an expert software engineer specializing in Python.
> Your responses should be:
> - Clear and concise
> - Include code examples
> - Follow PEP 8 style guidelines
> - Include error handling`,
>           cache_control: { type: 'ephemeral' },
>         },
>       ],
>     },
>     {
>       role: 'user',
>       content: 'How do I read a CSV file?',
>     },
>   ],
>   max_tokens: 1024,
> });
> ```

> [accordion] Contexto de documentos grandes
>
> Armazene em cache documentos, bases de código ou bases de conhecimento para reutilização em várias consultas.
>
> ```bash cURL (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> curl -X POST https://router.toqan.ai/eu/v3/router/chat/completions \
>   -H "Authorization: Bearer $TOQAN_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "model": "anthropic/claude-sonnet-5",
>     "messages": [
>       {
>         "role": "user",
>         "content": [
>           {
>             "type": "text",
>             "text": "Here is our API documentation:\n\n[Large documentation content here...]",
>             "cache_control": { "type": "ephemeral" }
>           },
>           {
>             "type": "text",
>             "text": "How do I authenticate with the API?"
>           }
>         ]
>       }
>     ],
>     "max_tokens": 1024
>   }'
> ```
>
> ```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> from openai import OpenAI
> import os
>
> client = OpenAI(
>     api_key=os.environ.get('TOQAN_API_KEY'),
>     base_url='https://router.toqan.ai/eu/v3/router'
> )
>
> api_docs = "Your large API documentation content goes here..."
>
> response = client.chat.completions.create(
>     model='anthropic/claude-sonnet-5',
>     messages=[
>         {
>             'role': 'user',
>             'content': [
>                 {
>                     'type': 'text',
>                     'text': f'Here is our API documentation:\n\n{api_docs}',
>                     'cache_control': {'type': 'ephemeral'}
>                 },
>                 {
>                     'type': 'text',
>                     'text': 'How do I authenticate with the API?'
>                 }
>             ]
>         }
>     ],
>     max_tokens=1024
> )
> ```
>
> ```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import OpenAI from "openai";
>
> const client = new OpenAI({
>   apiKey: process.env.TOQAN_API_KEY,
>   baseURL: "https://router.toqan.ai/eu/v3/router",
> });
>
> const apiDocs = "Your API documentation content goes here...";
>
> const response = await client.chat.completions.create({
>   model: 'anthropic/claude-sonnet-5',
>   messages: [
>     {
>       role: 'user',
>       content: [
>         {
>           type: 'text',
>           text: 'Here is our API documentation:\n\n' + apiDocs,
>           cache_control: { type: 'ephemeral' },
>         },
>         {
>           type: 'text',
>           text: 'How do I authenticate with the API?',
>         },
>       ],
>     },
>   ],
>   max_tokens: 1024,
> });
> ```

> [accordion] Conversas com vários turnos
>
> Armazene em cache o histórico de conversas longas para reduzir o tempo de processamento e os custos nas mensagens seguintes.
>
> ```bash cURL (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> curl -X POST https://router.toqan.ai/eu/v3/router/chat/completions \
>   -H "Authorization: Bearer $TOQAN_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "model": "anthropic/claude-sonnet-5",
>     "messages": [
>       {
>         "role": "user",
>         "content": "What is Python?"
>       },
>       {
>         "role": "assistant",
>         "content": "Python is a high-level programming language..."
>       },
>       {
>         "role": "user",
>         "content": [
>           {
>             "type": "text",
>             "text": "What are its main features?",
>             "cache_control": { "type": "ephemeral" }
>           }
>         ]
>       },
>       {
>         "role": "assistant",
>         "content": "Python's main features include..."
>       },
>       {
>         "role": "user",
>         "content": "Can you give me a code example?"
>       }
>     ],
>     "max_tokens": 1024
>   }'
> ```
>
> ```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> from openai import OpenAI
> import os
>
> client = OpenAI(
>     api_key=os.environ.get('TOQAN_API_KEY'),
>     base_url='https://router.toqan.ai/eu/v3/router'
> )
>
> conversation_history = [
>     {'role': 'user', 'content': 'What is Python?'},
>     {'role': 'assistant', 'content': 'Python is a high-level...'},
>     {'role': 'user', 'content': 'What are its main features?'},
>     {'role': 'assistant', 'content': 'Python\'s main features include...'},
> ]
>
> # Mark last history message for caching
> last_message = conversation_history[-1]
> messages = conversation_history[:-1] + [
>     {
>         'role': last_message['role'],
>         'content': [
>             {
>                 'type': 'text',
>                 'text': last_message['content'],
>                 'cache_control': {'type': 'ephemeral'}
>             }
>         ]
>     },
>     {
>         'role': 'user',
>         'content': 'Can you give me a code example?'
>     }
> ]
>
> response = client.chat.completions.create(
>     model='anthropic/claude-sonnet-5',
>     messages=messages,
>     max_tokens=1024
> )
> ```
>
> ```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import OpenAI from "openai";
>
> const client = new OpenAI({
>   apiKey: process.env.TOQAN_API_KEY,
>   baseURL: "https://router.toqan.ai/eu/v3/router",
> });
>
> const conversationHistory = [
>   { role: 'user', content: 'What is Python?' },
>   { role: 'assistant', content: 'Python is a high-level...' },
>   { role: 'user', content: 'What are its main features?' },
>   { role: 'assistant', content: "Python's main features include..." },
>   // ... more history
> ];
>
> // Mark last history message for caching
> const lastHistoryMessage = conversationHistory[conversationHistory.length - 1];
>
> const response = await client.chat.completions.create({
>   model: 'anthropic/claude-sonnet-5',
>   messages: [
>     ...conversationHistory.slice(0, -1),
>     {
>       ...lastHistoryMessage,
>       content: [
>         {
>           type: 'text',
>           text: lastHistoryMessage.content,
>           cache_control: { type: 'ephemeral' },
>         },
>       ],
>     },
>     {
>       role: 'user',
>       content: 'Can you give me a code example?',
>     },
>   ],
>   max_tokens: 1024,
> });
> ```

> [accordion] RAG com coleções de documentos
>
> Armazene em cache documentos recuperados para várias consultas em cenários de geração aumentada por recuperação.
>
> ```bash cURL (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> curl -X POST https://router.toqan.ai/eu/v3/router/chat/completions \
>   -H "Authorization: Bearer $TOQAN_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "model": "anthropic/claude-sonnet-5",
>     "messages": [
>       {
>         "role": "system",
>         "content": "You are a helpful assistant that answers based on provided context."
>       },
>       {
>         "role": "user",
>         "content": [
>           {
>             "type": "text",
>             "text": "Context:\n[Retrieved document content here...]",
>             "cache_control": { "type": "ephemeral" }
>           },
>           {
>             "type": "text",
>             "text": "Question: What is the main topic of these documents?"
>           }
>         ]
>       }
>     ],
>     "max_tokens": 1024
>   }'
> ```
>
> ```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> from openai import OpenAI
> import os
>
> client = OpenAI(
>     api_key=os.environ.get('TOQAN_API_KEY'),
>     base_url='https://router.toqan.ai/eu/v3/router'
> )
>
> user_question = "What is the main topic of these documents?"
> context_text = "Retrieved document content goes here..."
>
> response = client.chat.completions.create(
>     model='anthropic/claude-sonnet-5',
>     messages=[
>         {
>             'role': 'system',
>             'content': 'You are a helpful assistant that answers based on provided context.'
>         },
>         {
>             'role': 'user',
>             'content': [
>                 {
>                     'type': 'text',
>                     'text': f'Context:\n{context_text}',
>                     'cache_control': {'type': 'ephemeral'}
>                 },
>                 {
>                     'type': 'text',
>                     'text': f'Question: {user_question}'
>                 }
>             ]
>         }
>     ],
>     max_tokens=1024
> )
> ```
>
> ```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import OpenAI from "openai";
>
> const client = new OpenAI({
>   apiKey: process.env.TOQAN_API_KEY,
>   baseURL: "https://router.toqan.ai/eu/v3/router",
> });
>
> const userQuestion = "What is the main topic of these documents?";
> const contextText = "Retrieved document content goes here...";
>
> const response = await client.chat.completions.create({
>   model: 'anthropic/claude-sonnet-5',
>   messages: [
>     {
>       role: 'system',
>       content:
>         'You are a helpful assistant that answers based on provided context.',
>     },
>     {
>       role: 'user',
>       content: [
>         {
>           type: 'text',
>           text: `Context:\n${contextText}`,
>           cache_control: { type: 'ephemeral' },
>         },
>         {
>           type: 'text',
>           text: `Question: ${userQuestion}`,
>         },
>       ],
>     },
>   ],
>   max_tokens: 1024,
> });
> ```

#### Extended Thinking

Ative o raciocínio aprofundado para problemas complexos, alocando um orçamento de tokens para análise interna antes de gerar as respostas.

> [!NOTE]
>
> O extended thinking usa o parâmetro `thinking`, que só é compatível com o endpoint de Chat Completions (`POST /v3/router/chat/completions`). Use as abas de Chat Completions abaixo.

```bash cURL (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://router.toqan.ai/eu/v3/router/chat/completions \
  -H "Authorization: Bearer $TOQAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-haiku-4-5",
    "messages": [
      {
        "role": "user",
        "content": "Design a distributed rate limiting system for 1M requests/second"
      }
    ],
    "thinking": {
      "type": "enabled",
      "budget_tokens": 8000
    },
    "max_tokens": 16000
  }'
```

```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get('TOQAN_API_KEY'),
    base_url='https://router.toqan.ai/eu/v3/router'
)

response = client.chat.completions.create(
    model='anthropic/claude-haiku-4-5',
    messages=[
        {
            'role': 'user',
            'content': 'Design a distributed rate limiting system for 1M requests/second'
        }
    ],
    extra_body={
        'thinking': {
            'type': 'enabled',
            'budget_tokens': 8000
        }
    },
    max_tokens=16000
)
```

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-haiku-4-5",
  messages: [
    {
      role: "user",
      content: "Design a distributed rate limiting system for 1M requests/second",
    },
  ],
  thinking: {
    type: "enabled",
    budget_tokens: 8000,
  },
  max_tokens: 16000,
});
```

> [accordion] Extended thinking com vários turnos
>
> Inclua o conteúdo de raciocínio com sua assinatura ao dar continuidade às conversas:
>
> ```bash cURL (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> curl -X POST https://router.toqan.ai/eu/v3/router/chat/completions \
>   -H "Authorization: Bearer $TOQAN_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "model": "anthropic/claude-haiku-4-5",
>     "messages": [
>       {"role": "user", "content": "Design a rate limiting system"},
>       {
>         "role": "assistant",
>         "content": [
>           {
>             "type": "reasoning",
>             "reasoning": "...",
>             "signature": "..."
>           },
>           {
>             "type": "text",
>             "text": "Here'\''s a distributed rate limiting design..."
>           }
>         ]
>       },
>       {"role": "user", "content": "How would you handle 10M req/s?"}
>     ],
>     "thinking": {"type": "enabled", "budget_tokens": 8000},
>     "max_tokens": 16000
>   }'
> ```
>
> ```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import OpenAI from "openai";
>
> const client = new OpenAI({
>   apiKey: process.env.TOQAN_API_KEY,
>   baseURL: "https://router.toqan.ai/eu/v3/router",
> });
>
> const messages = [
>   { role: "user", content: "Design a rate limiting system" }
> ];
>
> const response = await client.chat.completions.create({
>   model: "anthropic/claude-haiku-4-5",
>   messages,
>   thinking: { type: "enabled", budget_tokens: 8000 },
>   max_tokens: 16000
> });
>
> // Map response to assistant message
> const msg = response.choices[0].message as any;
> const contentParts = [];
>
> if (msg.reasoning) {
>   contentParts.push({
>     type: "reasoning",
>     reasoning: msg.reasoning,
>     signature: msg.reasoning_signature
>   });
> }
>
> if (msg.redacted_reasoning) {
>   contentParts.push({
>     type: "redacted_reasoning",
>     data: msg.redacted_reasoning
>   });
> }
>
> if (msg.content) {
>   contentParts.push({
>     type: "text",
>     text: msg.content
>   });
> }
>
> const assistantMessage = {
>   role: "assistant",
>   content: contentParts
> };
>
> messages.push(assistantMessage);
> messages.push({ role: "user", content: "How would you handle 10M req/s?" });
>
> const followUp = await client.chat.completions.create({
>   model: "anthropic/claude-haiku-4-5",
>   messages,
>   thinking: { type: "enabled", budget_tokens: 8000 },
>   max_tokens: 16000
> });
> ```
>
> ```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> from openai import OpenAI
> import os
>
> client = OpenAI(
>     api_key=os.environ.get("TOQAN_API_KEY"),
>     base_url="https://router.toqan.ai/eu/v3/router",
> )
>
> messages = [
>   {"role": "user", "content": "Design a rate limiting system"}
> ]
>
> response = client.chat.completions.create(
>   model='anthropic/claude-haiku-4-5',
>   messages=messages,
>   extra_body={
>     'thinking': {
>       'type': 'enabled',
>       'budget_tokens': 8000
>     }
>   },
>   max_tokens=16000
> )
>
> msg = response.choices[0].message
> content_parts = []
>
> if getattr(msg, 'reasoning', None):
>   content_parts.append({
>     "type": "reasoning",
>     "reasoning": msg.reasoning,
>     "signature": getattr(msg, 'reasoning_signature', None)
>   })
>
> if getattr(msg, 'redacted_reasoning', None):
>   content_parts.append({
>     "type": "redacted_reasoning",
>     "data": msg.redacted_reasoning
>   })
>
> if msg.content:
>   content_parts.append({
>     "type": "text",
>     "text": msg.content
>   })
>
> assistant_message = {
>   "role": "assistant",
>   "content": content_parts
> }
>
> messages.append(assistant_message)
> messages.append({"role": "user", "content": "How would you handle 10M req/s?"})
>
> follow_up = client.chat.completions.create(
>   model='anthropic/claude-haiku-4-5',
>   messages=messages,
>   extra_body={
>     'thinking': {
>       'type': 'enabled',
>       'budget_tokens': 8000
>     }
>   },
>   max_tokens=16000
> )
> ```
>
> > [!WARNING]
> >
> > **Importante**: sempre inclua o campo `signature` ao enviar o conteúdo de raciocínio de volta à API. A assinatura verifica criptograficamente que o raciocínio foi gerado pelo modelo e é obrigatória em conversas com vários turnos.

> [accordion] Combine com o cache de prompts para contextos repetidos
>
> Armazene em cache prompts de sistema e contexto para reduzir custos e latência ao usar o extended thinking:
>
> ```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import OpenAI from "openai";
>
> const client = new OpenAI({
>   apiKey: process.env.TOQAN_API_KEY,
>   baseURL: "https://router.toqan.ai/eu/v3/router",
> });
>
> const response = await client.chat.completions.create({
>   model: "anthropic/claude-haiku-4-5",
>   messages: [
>     {
>       role: "system",
>       content: [{
>         type: "text",
>         text: "You are a system architect...", // Cache this
>         cache_control: { type: "ephemeral" }
>       }]
>     },
>     { role: "user", content: "Design a notification system" }
>   ],
>   max_tokens: 16000,
>   thinking: { type: "enabled", budget_tokens: 8000 }
> });
> ```
>
> ```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> from openai import OpenAI
> import os
>
> client = OpenAI(
>     api_key=os.environ.get("TOQAN_API_KEY"),
>     base_url="https://router.toqan.ai/eu/v3/router",
> )
>
> response = client.chat.completions.create(
>     model="anthropic/claude-haiku-4-5",
>     messages=[
>         {
>             "role": "system",
>             "content": [{
>                 "type": "text",
>                 "text": "You are a system architect...",
>                 "cache_control": {"type": "ephemeral"}
>             }]
>         },
>         {"role": "user", "content": "Design a notification system"}
>     ],
>     max_tokens=16000,
>     extra_body={"thinking": {"type": "enabled", "budget_tokens": 8000}}
> )
> ```

**Configuração e boas práticas**

| Aspecto | Orientação | Detalhes |
| - | - | - |
| `thinking.type` | Defina como `"enabled"` | Ativa o extended thinking com orçamento manual |
| `thinking.budget_tokens` | Defina de acordo com a complexidade | Mín.: 1024, deve ser \< `max_tokens`. Cobrado como tokens de saída. |

> [!NOTE]
>
> **Modelos compatíveis:** o Claude Haiku 4.5 usa extended thinking com `budget_tokens`. O Claude Opus 5 e o Sonnet 5 usam **adaptive thinking** (veja abaixo). Disponível pelos provedores `anthropic/`, `aws/` e `google/`.

> [card] [Modelos de raciocínio](/docs/pt-BR/ai-gateway/features/reasoning.md)
>
> Configure `thinking.budget_tokens` e outros controles de extended thinking do Claude por meio do **AI Gateway**.

#### Adaptive Thinking

O adaptive thinking é a forma recomendada de usar o extended thinking com o **Claude Opus 5** e o **Sonnet 5**. Em vez de definir manualmente um orçamento de tokens de raciocínio, o adaptive thinking permite que o Claude determine dinamicamente quando e quanto raciocinar com base na complexidade de cada solicitação.

> [!NOTE]
>
> O adaptive thinking usa o parâmetro `thinking`, que só é compatível com o endpoint de Chat Completions (`POST /v3/router/chat/completions`). Use as abas de Chat Completions abaixo.

```bash cURL (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://router.toqan.ai/eu/v3/router/chat/completions \
  -H "Authorization: Bearer $TOQAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-opus-5",
    "messages": [
      {
        "role": "user",
        "content": "Design a distributed rate limiting system for 1M requests/second"
      }
    ],
    "thinking": {
      "type": "adaptive"
    },
    "max_tokens": 16000
  }'
```

```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get('TOQAN_API_KEY'),
    base_url='https://router.toqan.ai/eu/v3/router'
)

response = client.chat.completions.create(
    model='anthropic/claude-opus-5',
    messages=[
        {
            'role': 'user',
            'content': 'Design a distributed rate limiting system for 1M requests/second'
        }
    ],
    extra_body={
        'thinking': {
            'type': 'adaptive'
        }
    },
    max_tokens=16000
)

print(response.choices[0].message.content)
```

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-opus-5",
  messages: [
    {
      role: "user",
      content: "Design a distributed rate limiting system for 1M requests/second",
    },
  ],
  thinking: {
    type: "adaptive",
  },
  max_tokens: 16000,
});

console.log(response.choices[0].message.content);
```

**Adaptive thinking x thinking manual**

| Modo | Configuração | Quando usar |
| - | - | - |
| **Adaptive** | `thinking: { type: "adaptive" }` | Recomendado para o Claude Opus 5 e o Sonnet 5. O Claude determina automaticamente a profundidade do raciocínio. |
| **Manual** | `thinking: { type: "enabled", budget_tokens: N }` | Quando você precisa de controle preciso sobre o gasto de tokens de raciocínio. Compatível com todos os modelos com suporte a thinking. |
| **Disabled** | Omita o parâmetro `thinking` | Quando você não precisa de extended thinking e quer a menor latência possível. |

> [!NOTE]
>
> **Modelos compatíveis:** o adaptive thinking está disponível somente no **Claude Opus 5** e no **Claude Sonnet 5**. O Claude Haiku 4.5 exige `type: "enabled"` com `budget_tokens`.

#### Recursos de visão

Todos os modelos Claude 3+ oferecem suporte à análise de imagens com alta precisão. Escolha entre imagens por URL ou codificadas em base64:

> [accordion] Imagem a partir de URL
>
> Use imagens a partir de URLs para arquivos remotos:
>
> ```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import OpenAI from "openai";
>
> const client = new OpenAI({
>   apiKey: process.env.TOQAN_API_KEY,
>   baseURL: "https://router.toqan.ai/eu/v3/router",
> });
>
> const response = await client.chat.completions.create({
>   model: "anthropic/claude-sonnet-5",
>   messages: [
>     {
>       role: "user",
>       content: [
>         { type: "text", text: "What's in this image?" },
>         {
>           type: "image_url",
>           image_url: { url: "https://picsum.photos/seed/sample-photo/800/600" }
>         },
>       ],
>     },
>   ],
> });
> ```
>
> ```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> from openai import OpenAI
> import os
>
> client = OpenAI(
>     api_key=os.environ.get("TOQAN_API_KEY"),
>     base_url="https://router.toqan.ai/eu/v3/router",
> )
>
> response = client.chat.completions.create(
>     model="anthropic/claude-sonnet-5",
>     messages=[
>         {
>             "role": "user",
>             "content": [
>                 {"type": "text", "text": "What's in this image?"},
>                 {
>                     "type": "image_url",
>                     "image_url": {"url": "https://picsum.photos/seed/sample-photo/800/600"},
>                 },
>             ],
>         }
>     ],
> )
> ```

> [accordion] Imagem a partir de Base64
>
> Incorpore imagens diretamente como strings codificadas em base64:
>
> ```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import OpenAI from "openai";
>
> const client = new OpenAI({
>   apiKey: process.env.TOQAN_API_KEY,
>   baseURL: "https://router.toqan.ai/eu/v3/router",
> });
>
> const imageBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
>
> const response = await client.chat.completions.create({
>   model: "anthropic/claude-sonnet-5",
>   messages: [
>     {
>       role: "user",
>       content: [
>         { type: "text", text: "What's in this image?" },
>         {
>           type: "image_url",
>           image_url: { url: `data:image/png;base64,${imageBase64}` }
>         },
>       ],
>     },
>   ],
> });
> ```
>
> ```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
> from openai import OpenAI
> import os
> import base64
>
> client = OpenAI(
>     api_key=os.environ.get("TOQAN_API_KEY"),
>     base_url="https://router.toqan.ai/eu/v3/router",
> )
>
> image_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
>
> response = client.chat.completions.create(
>     model="anthropic/claude-sonnet-5",
>     messages=[
>         {
>             "role": "user",
>             "content": [
>                 {"type": "text", "text": "What's in this image?"},
>                 {
>                     "type": "image_url",
>                     "image_url": {"url": f"data:image/png;base64,{image_base64}"},
>                 },
>             ],
>         }
>     ],
> )
> ```

#### Entrada de PDF

> [!NOTE]
>
> Os exemplos desta seção usam o endpoint de Chat Completions. Para o equivalente na Responses API, use `openai.responses.create()` com `POST /v3/router/responses` e adapte a estrutura das mensagens ao formato de entrada da Responses API.

O Claude Opus 5 oferece suporte à análise direta de PDFs:

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-opus-5",
  messages: [
    {
      role: "user",
      content: [
        { type: "text", text: "Summarize this document" },
        {
          type: "document",
          document: {
            type: "pdf",
            url: "https://example.com/document.pdf"
          }
        },
      ],
    },
  ],
  max_tokens: 2048,
});
```

> [card] [Multimodal](/docs/pt-BR/ai-gateway/features/multimodal.md)
>
> Referência completa sobre entrada de imagens, entrada de PDF, geração de imagens e áudio por meio do **AI Gateway**.

#### Uso de ferramentas (chamada de funções)

O Claude se destaca no uso de ferramentas, com planejamento e execução sofisticados.

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.responses.create({
  model: "anthropic/claude-sonnet-5",
  input: "What's the weather in Tokyo?",
  tools: [
    {
      type: "function",
      name: "get_weather",
      description: "Get current weather for a location",
      parameters: {
        type: "object",
        properties: {
          location: { type: "string" },
        },
        required: ["location"],
      },
    },
  ],
});
```

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/router",
)

response = client.responses.create(
    model="anthropic/claude-sonnet-5",
    input="What's the weather in Tokyo?",
    tools=[
        {
            "type": "function",
            "name": "get_weather",
            "description": "Get current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string"},
                },
                "required": ["location"],
            },
        }
    ],
)
```

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5",
  messages: [{ role: "user", content: "What's the weather in Tokyo?" }],
  tools: [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "Get current weather for a location",
        parameters: {
          type: "object",
          properties: {
            location: { type: "string" },
          },
          required: ["location"],
        },
      },
    },
  ],
});
```

```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/router",
)

response = client.chat.completions.create(
    model="anthropic/claude-sonnet-5",
    messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
    tools=[
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get current weather for a location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {"type": "string"},
                    },
                    "required": ["location"],
                },
            },
        }
    ],
)
```

> [card] [Chamada de ferramentas](/docs/pt-BR/ai-gateway/features/tool-calling.md)
>
> Referência completa sobre ferramentas de função, `tool_choice` e streaming com chamadas de ferramentas por meio do **AI Gateway**.

#### Estratégia com vários provedores

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.responses.create({
  model: "anthropic/claude-sonnet-5",
  input: "...",
  fallbacks: [
    { model: "aws/global.anthropic.claude-sonnet-5" },
    { model: "anthropic/claude-opus-5" },
  ],
});

console.log(response.output_text);
```

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/router",
)

response = client.responses.create(
    model="anthropic/claude-sonnet-5",
    input="...",
    extra_body={
        "fallbacks": [
            {"model": "aws/global.anthropic.claude-sonnet-5"},
            {"model": "anthropic/claude-opus-5"},
        ]
    },
)

print(response.output_text)
```

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5",
  messages: [{ role: "user", content: "..." }],
  // @ts-ignore -- unknown top-level fields are forwarded as-is by the TypeScript SDK
  fallbacks: [
    { model: "aws/global.anthropic.claude-sonnet-5" },
    { model: "anthropic/claude-opus-5" },
  ],
});

console.log(response.choices[0].message.content);
```

```python Python (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/router",
)

response = client.chat.completions.create(
    model="anthropic/claude-sonnet-5",
    messages=[{"role": "user", "content": "..."}],
    extra_body={
        "fallbacks": [
            {"model": "aws/global.anthropic.claude-sonnet-5"},
            {"model": "anthropic/claude-opus-5"},
        ]
    },
)

print(response.choices[0].message.content)
```

### Configuração

#### Parâmetros do modelo

| Parâmetro | Tipo | Descrição | Padrão |
| - | - | - | - |
| `max_tokens` | number | Máximo de tokens a gerar. O padrão é 4096. | - |
| `temperature` | number | Aleatoriedade (0-1) | 1 |
| `top_p` | number | Amostragem nucleus (0-1) | - |
| `top_k` | number | Amostragem top-K | - |
| `stop_sequences` | string\[] | Sequências de parada personalizadas | - |

**Observação**: se `max_tokens` for omitido, será usado o padrão de 4096 do gateway. Valores típicos: 1024 para respostas, 4096+ para conteúdo longo.

> [!WARNING]
>
> Não use `temperature` e `top_p` juntos nos modelos mais recentes da Anthropic. Usar os dois parâmetros simultaneamente resultará em um erro de API. Escolha um ou outro.

#### Gerenciamento de tokens

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Set appropriate max_tokens based on task
const getMaxTokens = (taskType: string) => {
  const limits = {
    chat: 1024,
    summary: 500,
    generation: 4096,
    analysis: 2048,
  };
  return limits[taskType as keyof typeof limits] ?? 1024;
};
```

### Solução de problemas

| Questão | Problema | Solução |
| - | - | - |
| Custos altos | O uso de tokens se acumula rapidamente em solicitações grandes | Ative o cache de prompts para contextos repetidos, use modelos menores (Haiku) em tarefas simples, monitore e otimize o uso de tokens |
| Limites de taxa | A Anthropic tem limites de taxa por níveis com base no uso | Use as novas tentativas e os fallbacks automáticos do Toqan Router ou considere os provedores AWS/Google para limites mais altos |

#### Limitações

* **Limites de taxa**: variam conforme o nível e o provedor
* **Janela de contexto**: varia conforme o modelo, até 1M de tokens. Consulte a tabela [Modelos disponíveis](#available-models) acima para ver a janela de contexto de cada modelo.
* **Prompts de sistema**: tratados de forma diferente da OpenAI (convertidos automaticamente pelo Toqan Router)

### Referência

* [Documentação da Anthropic](https://docs.anthropic.com/)
* [Preços dos modelos](https://www.anthropic.com/pricing)
* [Referência da API](https://docs.anthropic.com/en/api/messages)
* [Guia de engenharia de prompts](https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/overview)

## Claude Cowork

O **AI Gateway** do **Toqan Router** é compatível com o modo de inferência de terceiros do Claude Cowork. Encaminhe o tráfego do Cowork pelo **Toqan Router** para obter residência de dados na UE, fallbacks entre provedores e controle de custos sem alterar a interface do Cowork.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.