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

> ## Agent Instructions
> Phaseo Gateway base URL: https://api.phaseo.app/v1. Send `Authorization: Bearer $PHASEO_API_KEY` with every request.
> Model IDs look like `provider/model`, for example `openai/gpt-6-astra`. Do not guess IDs: list them with `GET /v1/models` or check https://phaseo.app/models. `phaseo/free` routes to an available free model and needs no wallet balance.
> For new text integrations prefer `POST /v1/responses`. `POST /v1/chat/completions` (OpenAI format) and `POST /v1/messages` (Anthropic format) suit existing code.
> The full API contract is https://phaseo.app/docs/openapi/v1/openapi.yaml. Official SDKs: `@phaseo/sdk` (TypeScript) and `phaseo` (Python), plus Go, C#, PHP, Ruby and Rust.
> Search these docs over MCP at https://phaseo.app/docs/mcp, and install Phaseo skills with `npx skills add https://phaseo.app/docs`. If a page is wrong or out of date, report it with the MCP `submit_feedback` tool.
> Manage Phaseo accounts with the `phaseo` CLI (`npm install -g @phaseo/cli`, then `phaseo login` or `phaseo login --device-code`), the `/v1` Management API or the MCP server at `https://mcp.phaseo.app/mcp?access=manage`. Do not send users to the dashboard for account tasks. A person is still needed for sign-up, approving a sign-in, paying the first top-up on the checkout link that `phaseo credits add` returns when no card is saved, confirming each saved-card top-up from the emailed link, and account security (password, MFA, passkeys). Create API keys with `phaseo keys create --name <name> --json`; never guess one. Credit top-ups need `phaseo login --scopes billing:write` first. Task map: https://phaseo.app/docs/v1/developers/manage-from-an-agent.md.

# Uso dos SDKs de cliente

> Um exemplo curto por endpoint do Gateway em cada SDK de cliente do Phaseo.

Cada seção abaixo traz um exemplo curto por endpoint. Uma linguagem fica de fora de uma seção quando o SDK dela não tem wrapper para esse endpoint; a [tabela de métodos](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/overview.md#find-the-method-for-each-endpoint) mostra a alternativa. As páginas de endpoint desta seção listam todos os parâmetros.

## Configuração

```typescript TypeScript theme={null}
import Phaseo from "@phaseo/sdk";

const client = new Phaseo({ apiKey: process.env.PHASEO_API_KEY! });
```

```python Python theme={null}
from phaseo import Phaseo

client = Phaseo(api_key="your-api-key")
```

```go Go theme={null}
import (
  "context"

  phaseo "github.com/phaseoteam/Phaseo/packages/sdk/sdk-go/v3"
)

client, err := phaseo.NewFromEnv() // lê PHASEO_API_KEY
if err != nil {
  panic(err)
}
ctx := context.Background()
```

```csharp C# theme={null}
using PhaseoSdk;

var client = new Phaseo(); // lê PHASEO_API_KEY
```

```php PHP theme={null}
<?php
require 'vendor/autoload.php';

use Phaseo\Sdk\Phaseo;

$client = new Phaseo(); // lê PHASEO_API_KEY
```

```ruby Ruby theme={null}
require 'phaseo_sdk'

client = PhaseoSdk::Phaseo.new # lê PHASEO_API_KEY
```

```java Java theme={null}
import app.phaseo.sdk.Phaseo;

Phaseo client = new Phaseo(System.getenv("PHASEO_API_KEY"));
```

```rust Rust theme={null}
use phaseo::Phaseo;
use serde_json::json;

let client = Phaseo::from_env()?; // ou Phaseo::new("phaseo_v1_sk_...")?
```

## Chat completions

```typescript TypeScript theme={null}
const completion = await client.generateText({
  model: "openai/gpt-6-astra",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "What is Phaseo?" },
  ],
});

for await (const chunk of client.streamChat({
  model: "openai/gpt-6-astra",
  messages: [{ role: "user", content: "Tell me a story" }],
})) {
  if (chunk.text) process.stdout.write(chunk.text);
}
```

```python Python theme={null}
completion = client.generate_text(
    {
        "model": "openai/gpt-6-astra",
        "messages": [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "What is Phaseo?"},
        ],
    }
)

for chunk in client.stream_chat(
    {
        "model": "openai/gpt-6-astra",
        "messages": [{"role": "user", "content": "Tell me a story"}],
    }
):
    if chunk.get("text"):
        print(chunk["text"], end="", flush=True)
```

```go Go theme={null}
chat, err := client.GenerateText(ctx, phaseo.ChatCompletionsRequest{
  Model:    "openai/gpt-6-astra",
  Messages: []map[string]interface{}{{"role": "user", "content": "Hello"}},
})
```

```csharp C# theme={null}
var chat = await client.GenerateText(new Dictionary<string, object>
{
    ["model"] = "openai/gpt-6-astra",
    ["messages"] = new[]
    {
        new Dictionary<string, object> { ["role"] = "user", ["content"] = "Hello" },
    },
});
```

```php PHP theme={null}
$chat = $client->generateText([
    'model' => 'openai/gpt-6-astra',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello'],
    ],
]);
```

```ruby Ruby theme={null}
chat = client.generate_text(
  model: 'openai/gpt-6-astra',
  messages: [{ role: 'user', content: 'Hello' }]
)
```

```java Java theme={null}
var chat = client.createChatCompletion(Map.of(
    "model", "openai/gpt-6-astra",
    "messages", List.of(Map.of("role", "user", "content", "Hello"))
));
```

```rust Rust theme={null}
let response = client.chat_completions(&json!({
    "model": "openai/gpt-6-astra",
    "messages": [{
        "role": "user",
        "content": "Reply with exactly: chat works"
    }]
}))?;

println!("{}", response.body);
```

Só TypeScript e Python têm um stream de chat já interpretado. [Chat completions](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/chat-completions.md#stream-the-response) mostra a alternativa de stream bruto em Java.

## Responses

```typescript TypeScript theme={null}
const response = await client.generateResponse({
  model: "openai/gpt-6-astra",
  input: [{ role: "user", content: [{ type: "input_text", text: "Summarise this" }] }],
});

for await (const chunk of client.streamResponses({
  model: "openai/gpt-6-astra",
  input: [{ role: "user", content: [{ type: "input_text", text: "Stream this" }] }],
})) {
  if (chunk.text) process.stdout.write(chunk.text);
}
```

```python Python theme={null}
resp = client.generate_response(
    {
        "model": "openai/gpt-6-astra",
        "input": [{"role": "user", "content": [{"type": "input_text", "text": "Summarise this"}]}],
    }
)

for chunk in client.stream_responses(
    {
        "model": "openai/gpt-6-astra",
        "input": [{"role": "user", "content": [{"type": "input_text", "text": "Stream this"}]}],
    }
):
    if chunk.get("text"):
        print(chunk["text"], end="", flush=True)
```

```go Go theme={null}
resp, err := client.GenerateResponse(ctx, phaseo.ResponsesRequest{
  Model: "openai/gpt-6-astra",
  Input: "Reply with: go sdk works",
})
```

```csharp C# theme={null}
var resp = await client.GenerateResponse(new Dictionary<string, object>
{
    ["model"] = "openai/gpt-6-astra",
    ["input"] = "Reply with: csharp sdk works",
});
```

```php PHP theme={null}
$response = $client->generateResponse([
    'model' => 'openai/gpt-6-astra',
    'input' => 'Reply with: php sdk works',
]);
```

```ruby Ruby theme={null}
response = client.generate_response(
  model: 'openai/gpt-6-astra',
  input: 'Reply with: ruby sdk works'
)
```

```java Java theme={null}
var response = client.createResponse(Map.of(
    "model", "openai/gpt-6-astra",
    "input", "Reply with: Java SDK works"
));

try (var lines = client.streamResponse(Map.of(
    "model", "openai/gpt-6-astra", "input", "Hello"
))) {
    lines.forEach(System.out::println);
}
```

```rust Rust theme={null}
let response = client.responses(&json!({
    "model": "openai/gpt-6-astra",
    "input": "Summarise why provider fallbacks improve reliability."
}))?;

println!("{}", response.body);
```

[Responses](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/responses.md) cobre o streaming em C#, PHP e Java e a leitura do texto de saída em Rust.

## Messages (compatível com a Anthropic)

```typescript TypeScript theme={null}
const message = await client.generateMessage({
  model: "anthropic/claude-haiku-4.5",
  messages: [{ role: "user", content: "Hello from the Messages API" }],
  max_tokens: 128,
});

for await (const chunk of client.streamMessages({
  model: "anthropic/claude-haiku-4.5",
  messages: [{ role: "user", content: "Stream a short hello" }],
  max_tokens: 128,
})) {
  if (chunk.text) process.stdout.write(chunk.text);
}
```

```python Python theme={null}
message = client.generate_message(
    {
        "model": "anthropic/claude-haiku-4.5",
        "messages": [{"role": "user", "content": "Hello from the Messages API"}],
        "max_tokens": 128,
    }
)

for chunk in client.stream_message(
    {
        "model": "anthropic/claude-haiku-4.5",
        "messages": [{"role": "user", "content": "Stream a short hello"}],
        "max_tokens": 128,
    }
):
    if chunk.get("text"):
        print(chunk["text"], end="", flush=True)
```

**Python:** `stream_message` produz chunks já interpretados; `stream_messages` produz as linhas SSE brutas. Go, C#, PHP, Ruby e Java têm `createAnthropicMessage` no estilo de nomes de cada linguagem.

## Imagens

```typescript TypeScript theme={null}
await client.generateImage({
  model: "openai/gpt-image-1",
  prompt: "A lighthouse at golden hour",
});

await client.generateImageEdit({
  model: "openai/gpt-image-1",
  prompt: "Make it sunset",
  image: "data:image/png;base64,...",
});
```

```python Python theme={null}
image = client.generate_image(
    {"model": "openai/gpt-image-1", "prompt": "A lighthouse at golden hour"}
)

edited = client.generate_image_edit(
    {
        "model": "openai/gpt-image-1",
        "prompt": "Make it sunset",
        "image": "data:image/png;base64,...",
    }
)
```

```go Go theme={null}
image, err := client.CreateImage(ctx, map[string]interface{}{
  "model":  "openai/gpt-image-1",
  "prompt": "A lighthouse at golden hour",
})
```

```csharp C# theme={null}
var image = await client.GenerateImage(new Dictionary<string, object>
{
    ["model"] = "openai/gpt-image-1",
    ["prompt"] = "A lighthouse at golden hour",
});
```

```php PHP theme={null}
$image = $client->generateImage([
    'model' => 'openai/gpt-image-1',
    'prompt' => 'A lighthouse at golden hour',
]);

$edit = $client->generateImageEdit([
    'model' => 'openai/gpt-image-1',
    'prompt' => 'Make it sunset',
    'image' => 'data:image/png;base64,...',
]);
```

```ruby Ruby theme={null}
image = client.generate_image(
  model: 'openai/gpt-image-1',
  prompt: 'A lighthouse at golden hour'
)

edit = client.generate_image_edit(
  model: 'openai/gpt-image-1',
  prompt: 'Make it sunset',
  image: 'data:image/png;base64,...'
)
```

```java Java theme={null}
var image = client.createImage(Map.of(
    "model", "openai/gpt-image-1",
    "prompt", "A lighthouse at golden hour"
));
```

Veja [Geração de imagens](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/images-generations.md) e [Edição de imagens](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/images-edits.md).

## Áudio

Transcrições e traduções recebem um upload multipart. O TypeScript envia um corpo `FormData` como multipart. Os métodos de Python, Go, C#, PHP e Ruby enviam JSON, então a transcrição só funciona com uma URL passada a um modelo que aceita `file_url`, e a tradução exige um upload multipart. Para enviar um arquivo de áudio a partir desses SDKs, veja [STT (fala para texto)](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/audio-transcriptions.md#upload-an-audio-file) e [Traduções](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/audio-translations.md).

```typescript TypeScript theme={null}
import { readFile } from "node:fs/promises";

const speech = await client.generateSpeech({
  model: "openai/gpt-4o-mini-tts",
  input: "Hello world",
});

// Transcrições e traduções recebem um upload multipart.
const form = new FormData();
form.append("model", "openai/gpt-4o-transcribe");
form.append("file", new Blob([await readFile("call.mp3")], { type: "audio/mpeg" }), "call.mp3");
const transcript = await client.generateTranscription(form as unknown as Record<string, unknown>);
```

```python Python theme={null}
speech = client.generate_speech(
    {"model": "openai/gpt-4o-mini-tts", "input": "Hello world"}
)

# generate_transcription envia JSON, então passe uma URL para um modelo que aceita file_url.
transcription = client.generate_transcription(
    {"model": "mistral/voxtral-mini-transcribe-2", "file_url": "https://example.com/call.mp3"}
)
```

```go Go theme={null}
speech, err := client.CreateSpeech(ctx, map[string]interface{}{
  "model": "openai/gpt-4o-mini-tts",
  "input": "Hello from Go",
})
```

```csharp C# theme={null}
var speech = await client.CreateSpeech(new Dictionary<string, object>
{
    ["model"] = "openai/gpt-4o-mini-tts",
    ["input"] = "Hello from .NET",
});
```

```php PHP theme={null}
$speech = $client->createSpeech([
    'model' => 'openai/gpt-4o-mini-tts',
    'input' => 'Hello from PHP',
]);

$transcript = $client->generateTranscription([
    'model' => 'mistral/voxtral-mini-transcribe-2',
    'file_url' => 'https://example.com/meeting.mp3',
]);
```

```ruby Ruby theme={null}
speech = client.generate_speech(
  model: 'openai/gpt-4o-mini-tts',
  input: 'Hello world'
)

transcription = client.generate_transcription(
  model: 'mistral/voxtral-mini-transcribe-2',
  file_url: 'https://example.com/meeting.mp3'
)
```

Veja [Traduções](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/audio-translations.md) para `generateTranslation()`. **Java:** `createSpeech` espera JSON e não consegue decodificar áudio binário, então use `rawClient().requestBytes` para fala; envie os uploads de transcrição e tradução com o cliente HTTP padrão do Java, como mostram as páginas de [STT](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/audio-transcriptions.md) e [Traduções](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/audio-translations.md).

## Vídeo

```typescript TypeScript theme={null}
const video = await client.videos.generateAndWait({
  model: "openai/sora-2",
  prompt: "A serene mountain lake at sunrise",
});
```

```python Python theme={null}
video = client.videos.generate_and_wait(
    {"model": "openai/sora-2", "prompt": "A serene mountain lake at sunrise"}
)
```

Go, C#, PHP, Ruby e Java criam a tarefa e a retornam sem esperar; veja a [tabela de métodos](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/overview.md#find-the-method-for-each-endpoint).

## Embeddings, rerank e moderação

```typescript TypeScript theme={null}
const embedding = await client.generateEmbedding({
  model: "openai/text-embedding-3-large",
  input: "Sample text",
});

const ranked = await client.rerank.create({
  model: "voyage/rerank-2",
  query: "How do I list models?",
  documents: ["Call GET /v1/models.", "Create an image with POST /v1/images/generations."],
});

await client.generateModeration({
  model: "openai/omni-moderation",
  input: "Some text to check",
});
```

```python Python theme={null}
embedding = client.generate_embedding(
    {"model": "openai/text-embedding-3-large", "input": "Sample text"}
)

ranked = client.rerank.create(
    {
        "model": "voyage/rerank-2",
        "query": "How do I list models?",
        "documents": ["Call GET /v1/models.", "Create an image with POST /v1/images/generations."],
    }
)

moderation = client.generate_moderation(
    {"model": "openai/omni-moderation", "input": "Text to check"}
)
```

```go Go theme={null}
embedding, err := client.GenerateEmbedding(ctx, map[string]interface{}{
  "model": "openai/text-embedding-3-large",
  "input": "Sample text",
})

moderation, err := client.GenerateModeration(ctx, map[string]interface{}{
  "model": "openai/omni-moderation",
  "input": "Some text to check",
})
```

```csharp C# theme={null}
var embedding = await client.CreateEmbedding(new Dictionary<string, object>
{
    ["model"] = "openai/text-embedding-3-large",
    ["input"] = "Sample text",
});

var moderation = await client.GenerateModeration(new Dictionary<string, object>
{
    ["model"] = "openai/omni-moderation",
    ["input"] = "Some text to check",
});
```

```php PHP theme={null}
$embedding = $client->generateEmbedding([
    'model' => 'openai/text-embedding-3-large',
    'input' => 'Sample text',
]);

$moderation = $client->generateModeration([
    'model' => 'openai/omni-moderation',
    'input' => 'Some text to check',
]);
```

```ruby Ruby theme={null}
embedding = client.generate_embedding(
  model: 'openai/text-embedding-3-large',
  input: 'Sample text'
)

moderation = client.generate_moderation(
  model: 'openai/omni-moderation',
  input: 'Some text to check'
)
```

```java Java theme={null}
var embedding = client.createEmbedding(Map.of(
    "model", "openai/text-embedding-3-large",
    "input", "Sample text"
));
```

```rust Rust theme={null}
// post(...) envia JSON para um endpoint sem helper de alto nível.
// O caminho pode incluir ou omitir a barra inicial.
let response = client.post("/embeddings", &json!({
    "model": "openai/text-embedding-3-small",
    "input": "Phaseo routes across AI providers"
}))?;
```

## Lotes e arquivos

```typescript TypeScript theme={null}
const file = await client.uploadFile({
  purpose: "batch",
  file: new Blob(["{}"], { type: "application/json" }),
  filename: "batch.jsonl",
});

const batch = await client.createBatch({
  input_file_id: file.id,
  endpoint: "/v1/responses",
  completion_window: "24h",
});

const batchStatus = await client.getBatch(batch.id);
```

```python Python theme={null}
uploaded = client.upload_file(
    purpose="batch",
    file=b'{"test": true}',
    filename="batch.jsonl",
    content_type="application/json",
)

batch = client.create_batch(
    {
        "endpoint": "/v1/responses",
        "input_file_id": uploaded["id"],
        "completion_window": "24h",
        "session_id": "agent-run-42",
    }
)

status = client.get_batch(batch["id"])
```

Go, C#, PHP, Ruby e Java têm `createBatch` e `retrieveBatch` no estilo de nomes de cada linguagem; [Arquivos](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/files.md) cobre os uploads em cada SDK.

## URLs de WebSocket de tarefas assíncronas

```typescript TypeScript theme={null}
const batchSocketUrl = client.batches.websocketUrl(batch.id, {
  intervalMs: 1500,
  closeOnTerminal: false,
});

const videoSocketUrl = client.videos.websocketUrl(video.id);
```

```python Python theme={null}
batch_socket_url = client.batches.websocket_url(
    batch["id"], interval_ms=1500, close_on_terminal=False
)

video_socket_url = client.videos.websocket_url(video["id"])
```

```java Java theme={null}
String batchSocketUrl = client.getBatchWebSocketUrl(batchId, 1500, false);
String videoSocketUrl = client.getVideoWebSocketUrl(videoId);
```

## Modelos, saúde e conta

Créditos e atividade exigem uma chave de API de gerenciamento.

```typescript TypeScript theme={null}
const models = await client.getModels();
const health = await client.getHealth();
const providers = await client.listProviders();

// Créditos e atividade exigem uma chave de API de gerenciamento.
const credits = await client.getCredits();
const activity = await client.getActivity({ days: 30 });
```

```python Python theme={null}
models = client.get_models()
health = client.get_health()
providers = client.list_providers()
generation = client.get_generation("G-01ABC...")

# Créditos e atividade exigem uma chave de API de gerenciamento.
credits = client.get_credits()
activity = client.get_activity({"days": 30})
```

```go Go theme={null}
models, err := client.GetModels(ctx, map[string]string{"limit": "10"})
health, err := client.Health(ctx)
```

```csharp C# theme={null}
var models = await client.ListModels(new Dictionary<string, string> { ["limit"] = "10" });
var health = await client.Health();
```

```php PHP theme={null}
$models = $client->listModels(['limit' => 10]);
$health = $client->health();
```

```ruby Ruby theme={null}
models = client.list_models(limit: 10)
health = client.health
```

```java Java theme={null}
var models = client.listModels(Map.of("limit", "10"));
```

## Trate erros

```typescript TypeScript theme={null}
import { PhaseoHttpError } from "@phaseo/sdk";

try {
  await client.generateText({ model: "invalid", messages: [{ role: "user", content: "Hi" }] });
} catch (error) {
  if (error instanceof PhaseoHttpError) {
    console.error(error.status, error.code, error.requestId, error.traceUrl);
  } else {
    throw error;
  }
}
```

```python Python theme={null}
from phaseo import PhaseoHTTPError

try:
    client.generate_text({"model": "invalid", "messages": [{"role": "user", "content": "Hi"}]})
except PhaseoHTTPError as error:
    print(error.status, error.code, error.request_id, error.trace_url)
```

```java Java theme={null}
import app.phaseo.gen.Client;
import app.phaseo.sdk.Phaseo;
import java.time.Duration;
import java.util.Map;

Phaseo client = new Phaseo(System.getenv("PHASEO_API_KEY"))
    .setTimeout(Duration.ofSeconds(30))
    .setMaxRetries(2);

try {
    var result = client.requestWithResponse("GET", "/models",
        Map.of("limit", "5"), null, null, null);
    System.out.println(result.requestId());
    System.out.println(result.data);
} catch (Client.ApiException error) {
    System.err.println(error.getStatusCode());
    System.err.println(error.getRequestId());
    System.err.println(error.getResponseBody());
}
```

```rust Rust theme={null}
let request = serde_json::json!({
    "model": "openai/gpt-6-astra",
    "input": "Handle this request"
});

match client.responses(&request) {
    Ok(response) => println!("{}", response.body),
    Err(error) => {
        eprintln!("message: {}", error.message);
        eprintln!("status: {:?}", error.status);
        eprintln!("body: {:?}", error.body);
    }
}
```

`PhaseoError` (Rust) tem um status HTTP e o corpo JSON interpretado quando o Gateway retornou um erro; falhas de transporte e de configuração não têm status. A [visão geral](https://phaseo.app/docs/pt-BR/v1/sdk-reference/client/overview.md#request-controls-and-errors) lista os campos de erro em cada SDK.

## Adicione um header de solicitação

**Rust:** `with_header` adiciona um header a todas as solicitações seguintes.

```rust Rust theme={null}
let client = Phaseo::from_env()?
    .with_header("x-phaseo-workspace-id", "workspace_123");
```


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