> ## 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.

# Utilisation des SDK clients

> Un court exemple par endpoint du Gateway, dans chaque SDK client Phaseo.

Chaque section ci-dessous donne un court exemple par endpoint. Un langage est absent d’une section quand son SDK n’a pas de wrapper pour cet endpoint ; le [tableau des méthodes](https://phaseo.app/docs/fr/v1/sdk-reference/client/overview.md#find-the-method-for-each-endpoint) indique l’alternative. Les pages d’endpoint de cette section listent tous les paramètres.

## Configuration

```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() // lit PHASEO_API_KEY
if err != nil {
  panic(err)
}
ctx := context.Background()
```

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

var client = new Phaseo(); // lit PHASEO_API_KEY
```

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

use Phaseo\Sdk\Phaseo;

$client = new Phaseo(); // lit PHASEO_API_KEY
```

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

client = PhaseoSdk::Phaseo.new # lit 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);
```

Seuls TypeScript et Python proposent un flux de chat analysé. [Chat completions](https://phaseo.app/docs/fr/v1/sdk-reference/client/chat-completions.md#stream-the-response) montre l’alternative Java avec le flux brut.

## 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/fr/v1/sdk-reference/client/responses.md) couvre le streaming en C#, PHP et Java, ainsi que la lecture du texte de sortie en Rust.

## Messages (compatible 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` renvoie des fragments analysés ; `stream_messages` renvoie les lignes SSE brutes. Go, C#, PHP, Ruby et Java proposent `createAnthropicMessage`, selon la convention de nommage de chaque langage.

## Images

```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"
));
```

Consultez [Génération d’images](https://phaseo.app/docs/fr/v1/sdk-reference/client/images-generations.md) et [Retouches d’images](https://phaseo.app/docs/fr/v1/sdk-reference/client/images-edits.md).

## Audio

Les transcriptions et les traductions prennent un envoi multipart. TypeScript envoie un corps `FormData` en multipart. Les méthodes Python, Go, C#, PHP et Ruby envoient du JSON : la transcription ne fonctionne donc qu’avec une URL passée à un modèle qui accepte `file_url`, et la traduction exige un envoi multipart. Pour envoyer un fichier audio depuis ces SDK, consultez [STT (reconnaissance vocale)](https://phaseo.app/docs/fr/v1/sdk-reference/client/audio-transcriptions.md#upload-an-audio-file) et [Traductions](https://phaseo.app/docs/fr/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",
});

// Les transcriptions et les traductions prennent un envoi 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 envoie du JSON : passez une URL à un modèle qui accepte 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'
)
```

Consultez [Traductions](https://phaseo.app/docs/fr/v1/sdk-reference/client/audio-translations.md) pour `generateTranslation()`. **Java :** `createSpeech` attend du JSON et ne sait pas décoder l’audio binaire : utilisez donc `rawClient().requestBytes` pour la synthèse vocale ; envoyez les fichiers de transcription et de traduction avec le client HTTP standard de Java, comme le montrent les pages [STT](https://phaseo.app/docs/fr/v1/sdk-reference/client/audio-transcriptions.md) et [Traductions](https://phaseo.app/docs/fr/v1/sdk-reference/client/audio-translations.md).

## Vidéo

```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 et Java créent la tâche et la renvoient sans attendre ; voir le [tableau des méthodes](https://phaseo.app/docs/fr/v1/sdk-reference/client/overview.md#find-the-method-for-each-endpoint).

## Embeddings, rerank et modération

```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(...) envoie du JSON vers un endpoint qui n’a pas d’assistant de haut niveau.
// Le chemin peut inclure ou omettre la barre oblique initiale.
let response = client.post("/embeddings", &json!({
    "model": "openai/text-embedding-3-small",
    "input": "Phaseo routes across AI providers"
}))?;
```

## Lots et fichiers

```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 et Java proposent `createBatch` et `retrieveBatch`, selon la convention de nommage de chaque langage ; [Fichiers](https://phaseo.app/docs/fr/v1/sdk-reference/client/files.md) couvre l’envoi de fichiers dans chaque SDK.

## URL WebSocket des tâches asynchrones

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

## Modèles, état de santé et compte

Les crédits et l’activité nécessitent une clé API de gestion.

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

// Les crédits et l’activité nécessitent une clé API de gestion.
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...")

# Les crédits et l’activité nécessitent une clé API de gestion.
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"));
```

## Gérer les erreurs

```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) contient un statut HTTP et le corps JSON analysé quand le Gateway a renvoyé une erreur ; les échecs de transport et de configuration n’ont pas de statut. La [présentation](https://phaseo.app/docs/fr/v1/sdk-reference/client/overview.md#request-controls-and-errors) liste les champs d’erreur de chaque SDK.

## Ajouter un en-tête de requête

**Rust :** `with_header` ajoute un en-tête à toutes les requêtes suivantes.

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