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

# OpenAI

> Use os modelos GPT da OpenAI pelo AI Gateway do Toqan Router com configuração de chave de API BYOK, cache, fallbacks, streaming e observabilidade completa das solicitações.

## Configure sua chave de API

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

1. Navegue até **AI Gateway** > BYOK
2. Encontre **OpenAI** na lista
3. Clique no botão **Configure** ao lado de OpenAI
4. No modal que se abre, selecione <kbd>Setup your own API Key</kbd>
5. Insira um nome para esta configuração (por exemplo, "OpenAI Production")
6. Cole sua chave de API da OpenAI no campo indicado
7. Defina **Geography** como a região para a qual a OpenAI emitiu a chave. O padrão, **Global (Recommended for most use cases)**, usa o endpoint padrão da OpenAI. **US**, **Europe**, **Japan**, **South Korea**, **Canada**, **Singapore**, **India**, **Australia** e **United Kingdom** roteiam as solicitações para o endpoint de residência de dados da OpenAI dessa região.
8. Clique em **Save** para concluir a configuração

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

## Modelos disponíveis

O **AI Gateway** é compatível com todos os modelos atuais da OpenAI. Estes são os mais usados:

### Modelos recomendados

| Modelo | Contexto | Ideal para |
| - | - | - |
| `openai/gpt-5.6-sol` | 1.05M | Trabalho profissional complexo e programação agêntica |
| `openai/gpt-5.6-terra` | 1.05M | Equilíbrio entre inteligência e custo para o trabalho do dia a dia |
| `openai/gpt-5.6-luna` | 1.05M | Cargas de trabalho rápidas, econômicas e de alto volume |
| `openai/gpt-5.4` | 1.05M | Trabalho profissional complexo |
| `openai/gpt-5.4-mini` | 400K | Programação e raciocínio visual econômicos |

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

> [!TIP]
>
> Escolha um modelo de acordo com a carga de trabalho. Use `openai/gpt-5.6-sol` para trabalhos complexos, `openai/gpt-5.6-terra` para o trabalho equilibrado do dia a dia ou `openai/gpt-5.6-luna` para cargas de trabalho de alto volume.

> [!NOTE]
>
> Os modelos de raciocínio (`o1`, `o3`, `o4-mini`) exigem que o modo de desenvolvedor esteja ativado na sua conta da OpenAI. Ative-o nas configurações da conta e aceite os termos dos modelos de raciocínio antes de usá-los.

> [card] [Busca na web](/docs/pt-BR/ai-gateway/features/web-search.md)
>
> Adicione busca na web às chamadas da Responses API com ferramentas `web_search_preview`.

> [card] [Modelos de raciocínio](/docs/pt-BR/ai-gateway/features/reasoning.md)
>
> Configure `reasoning_effort` para os modelos o1 e o3 por meio do **AI Gateway**.

## Início rápido

Acesse os modelos GPT da OpenAI por meio do **AI Gateway**.

```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": "openai/gpt-5.6-sol",
    "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: "openai/gpt-5.6-sol",
  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="openai/gpt-5.6-sol",
    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: "openai/gpt-5.6-sol",
  messages: [
    {
      role: "user",
      content: "Explain quantum computing in simple terms",
    },
  ],
});

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="openai/gpt-5.6-sol",
    messages=[
        {
            "role": "user",
            "content": "Explain quantum computing in simple terms",
        }
    ],
)

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

## Usando o AI Gateway

Acesse os modelos GPT da OpenAI por meio do **AI Gateway** usando a Responses API ou Chat Completions, com streaming, chamada de funções e roteamento inteligente de modelos. Todos os modelos da OpenAI estão disponíveis com formatação consistente e registro automático de solicitações.

> [!NOTE]
>
> Os modelos da OpenAI usam o formato de slug de provedor: `openai/model-name`. Por exemplo: `openai/gpt-5.6-sol`

### 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 do router**

Para usar o **AI Gateway** com modelos da OpenAI, configure o cliente do SDK da OpenAI com a URL base:

```
https://router.toqan.ai/eu/v3/router
```

**Headers obrigatórios**

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

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

Headers opcionais para roteamento avançado:

```
X-Toqan-Provider: openai
X-Toqan-Virtual-Key: your-virtual-key-name (optional)
```

**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 da OpenAI para a sua linguagem:

```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
```

> [!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`.

### Uso básico

Envie mensagens aos modelos da OpenAI e obtenha respostas inteligentes:

```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": "openai/gpt-5.6-sol",
    "instructions": "You are a helpful assistant that explains complex concepts simply.",
    "input": "Explain machine learning"
  }'
```

```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: "openai/gpt-5.6-sol",
  instructions: "You are a helpful assistant that explains complex concepts simply.",
  input: "Explain machine learning",
});

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="openai/gpt-5.6-sol",
    instructions="You are a helpful assistant that explains complex concepts simply.",
    input="Explain machine learning",
)

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: "openai/gpt-5.6-sol",
  messages: [
    {
      role: "system",
      content: "You are a helpful assistant that explains complex concepts simply.",
    },
    {
      role: "user",
      content: "Explain machine learning",
    },
  ],
  temperature: 0.7,
  max_tokens: 500,
});

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="openai/gpt-5.6-sol",
    messages=[
        {
            "role": "system",
            "content": "You are a helpful assistant that explains complex concepts simply.",
        },
        {
            "role": "user",
            "content": "Explain machine learning",
        },
    ],
    temperature=0.7,
    max_tokens=500,
)

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

### Chamada de funções

Os modelos da OpenAI oferecem suporte a chamada de funções para interações estruturadas:

```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": "openai/gpt-5.6-sol",
    "input": "What'\''s the weather in San Francisco?",
    "tools": [
      {
        "type": "function",
        "name": "get_weather",
        "description": "Get the current weather in a location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"]
            }
          },
          "required": ["location"]
        }
      }
    ]
  }'
```

```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: "openai/gpt-5.6-sol",
  input: "What's the weather in San Francisco?",
  tools: [
    {
      type: "function",
      name: "get_weather",
      description: "Get the current weather in a location",
      parameters: {
        type: "object",
        properties: {
          location: {
            type: "string",
            description: "The city and state, e.g. San Francisco, CA",
          },
          unit: {
            type: "string",
            enum: ["celsius", "fahrenheit"],
          },
        },
        required: ["location"],
      },
    },
  ],
});

const toolCall = response.output.find((item) => item.type === "function_call");
if (toolCall?.type === "function_call") {
  console.log(`Calling function: ${toolCall.name}`);
  console.log(`Arguments: ${toolCall.arguments}`);
}
```

```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="openai/gpt-5.6-sol",
    input="What's the weather in San Francisco?",
    tools=[
        {
            "type": "function",
            "name": "get_weather",
            "description": "Get the current weather in a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"]
                    }
                },
                "required": ["location"]
            }
        }
    ]
)

tool_call = next((item for item in response.output if item.type == "function_call"), None)
if tool_call:
    print(f"Calling function: {tool_call.name}")
    print(f"Arguments: {tool_call.arguments}")
```

```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: "openai/gpt-5.6-sol",
  messages: [
    {
      role: "user",
      content: "What's the weather in San Francisco?",
    },
  ],
  tools: [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "Get the current weather in a location",
        parameters: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "The city and state, e.g. San Francisco, CA",
            },
            unit: {
              type: "string",
              enum: ["celsius", "fahrenheit"],
            },
          },
          required: ["location"],
        },
      },
    },
  ],
});

const toolCall = response.choices[0].message.tool_calls?.[0];
if (toolCall?.type === "function") {
  console.log(`Calling function: ${toolCall.function.name}`);
  console.log(`Arguments: ${toolCall.function.arguments}`);
}
```

```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="openai/gpt-5.6-sol",
    messages=[
        {
            "role": "user",
            "content": "What's the weather in San Francisco?"
        }
    ],
    tools=[
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get the current weather in a location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA"
                        },
                        "unit": {
                            "type": "string",
                            "enum": ["celsius", "fahrenheit"]
                        }
                    },
                    "required": ["location"]
                }
            }
        }
    ]
)

tool_call = next(iter(response.choices[0].message.tool_calls or []), None)
if tool_call:
    print(f"Calling function: {tool_call.function.name}")
    print(f"Arguments: {tool_call.function.arguments}")
```

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

### Streaming

Faça streaming das respostas para obter saída em tempo real e uma melhor experiência do usuário:

```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": "openai/gpt-5.6-sol",
    "input": "Write a short poem about the ocean",
    "stream": true
  }'
```

```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": "openai/gpt-5.6-sol",
    "messages": [
      {
        "role": "user",
        "content": "Write a short poem about the ocean"
      }
    ],
    "stream": true
  }'
```

## Usando a Responses API

A Responses API combina o melhor das APIs Chat Completions e Assistants. Use `responses.create()` com o **AI Gateway**:

> [card] [Busca na web](/docs/pt-BR/ai-gateway/features/web-search.md)
>
> Adicione busca na web às chamadas da Responses API com ferramentas `web_search_preview`.

> [card] [Modelos de raciocínio](/docs/pt-BR/ai-gateway/features/reasoning.md)
>
> Use o objeto `reasoning` com os modelos da série o na Responses API.

### Endpoint

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

### Uso básico

Configure o SDK da OpenAI para usar o **AI Gateway** e chamar a Responses API:

```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": "openai/gpt-5.6-sol",
    "input": "Write a three sentence bedtime story about a unicorn"
  }'
```

```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: "openai/gpt-5.6-sol",
  input: "Write a short poem about the ocean",
  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="openai/gpt-5.6-sol",
    input="Write a short poem about the ocean",
    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: "openai/gpt-5.6-sol",
  messages: [{ role: "user", content: "Write a short poem about the ocean" }],
  stream: true,
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content || "";
  process.stdout.write(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="openai/gpt-5.6-sol",
    messages=[{"role": "user", "content": "Write a short poem about the ocean"}],
    stream=True,
)

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

## Registro automático de solicitações

Todas as solicitações feitas por meio do **AI Gateway** são registradas automaticamente no seu painel. Você pode ver:

* **Detalhes da solicitação**: modelo usado, tokens, latência
* **Acompanhamento de custos**: custos por solicitação e agregados
* **Monitoramento de erros**: solicitações com falha e mensagens de erro
* **Métricas de desempenho**: tempos de resposta e throughput

Nenhuma configuração adicional é necessária. O registro acontece automaticamente.

## Solução de problemas

| Questão | Problema | Solução |
| - | - | - |
| Limitação de taxa | Solicitações demais para a API da OpenAI | Implemente backoff exponencial para novas tentativas. O AI Gateway repete automaticamente solicitações com falha usando intervalos adequados. |
| Alta latência | Tempos de resposta lentos | Acompanhe o desempenho do modelo no painel. Considere usar `gpt-5.4-mini` em aplicações sensíveis à latência. |
| Erros de solicitação inválida | Solicitações de API malformadas | Verifique o formato do nome do modelo (`openai/model-name`). Garanta que os campos obrigatórios estejam presentes no array de mensagens. Confira se as mensagens contêm valores de role válidos (user, assistant, system). |
| Erros de API | Erros HTTP da OpenAI | Trate os erros com try/catch. Verifique os códigos de status e as mensagens de erro. Use o mecanismo de repetição automática do AI Gateway. |

## Referência

* [Documentação da API da OpenAI](https://platform.openai.com/docs/)
* [Preços dos modelos](https://openai.com/pricing)
* [Referência da API](https://developers.openai.com/api/reference/overview)
* [Guia de Chat Completions](https://platform.openai.com/docs/guides/chat-completions)


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