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

# クライアント SDK の使い方

> すべての Phaseo クライアント SDK について、Gateway のエンドポイントごとの短い例。

以下の各セクションは、エンドポイントごとの短い例です。SDK にそのエンドポイントのラッパーがない言語はセクションから省いています。代わりの方法は[メソッドの表](https://phaseo.app/docs/ja/v1/sdk-reference/client/overview.md#find-the-method-for-each-endpoint)にあります。すべてのパラメーターは、このセクションの各エンドポイントのページにあります。

## セットアップ

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

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

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

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

use Phaseo\Sdk\Phaseo;

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

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

client = PhaseoSdk::Phaseo.new # reads 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()?; // or Phaseo::new("phaseo_v1_sk_...")?
```

## チャット補完

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

解析済みのチャットストリームがあるのは TypeScript と Python だけです。Java で生のストリームを使う方法は[チャット補完](https://phaseo.app/docs/ja/v1/sdk-reference/client/chat-completions.md#stream-the-response)にあります。

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

C#、PHP、Java でのストリーミングと、Rust での出力テキストの読み方は [Responses](https://phaseo.app/docs/ja/v1/sdk-reference/client/responses.md) にあります。

## Messages（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` は解析済みのチャンクを返し、`stream_messages` は生の SSE 行を返します。Go、C#、PHP、Ruby、Java には、それぞれの命名規則に沿った `createAnthropicMessage` があります。

## 画像

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

[画像生成](https://phaseo.app/docs/ja/v1/sdk-reference/client/images-generations.md)と[画像編集](https://phaseo.app/docs/ja/v1/sdk-reference/client/images-edits.md)を参照してください。

## 音声

文字起こしと翻訳はマルチパートのアップロードを受け取ります。TypeScript は `FormData` の本文をマルチパートとして送信します。Python、Go、C#、PHP、Ruby のメソッドは JSON を送信するため、文字起こしは `file_url` を受け付けるモデルに URL を渡す場合にしか使えず、翻訳にはマルチパートのアップロードが必要です。これらの SDK から音声ファイルをアップロードするには、[STT（音声認識）](https://phaseo.app/docs/ja/v1/sdk-reference/client/audio-transcriptions.md#upload-an-audio-file)と[音声翻訳](https://phaseo.app/docs/ja/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",
});

// Transcriptions and translations take a multipart upload.
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 sends JSON, so pass a URL to a model that accepts 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'
)
```

`generateTranslation()` については[音声翻訳](https://phaseo.app/docs/ja/v1/sdk-reference/client/audio-translations.md)を参照してください。**Java：** `createSpeech` は JSON を想定しておりバイナリの音声をデコードできないため、音声合成には `rawClient().requestBytes` を使ってください。文字起こしと翻訳のアップロードは、[STT](https://phaseo.app/docs/ja/v1/sdk-reference/client/audio-transcriptions.md) と[音声翻訳](https://phaseo.app/docs/ja/v1/sdk-reference/client/audio-translations.md)のページにあるとおり、Java の標準 HTTP クライアントで送信します。

## 動画

```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、Java はジョブを作成し、完了を待たずに返します。[メソッドの表](https://phaseo.app/docs/ja/v1/sdk-reference/client/overview.md#find-the-method-for-each-endpoint)を参照してください。

## 埋め込み、リランク、モデレーション

```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(...) sends JSON to an endpoint without a high-level helper.
// The path may include or omit its leading slash.
let response = client.post("/embeddings", &json!({
    "model": "openai/text-embedding-3-small",
    "input": "Phaseo routes across AI providers"
}))?;
```

## バッチとファイル

```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、Java には、それぞれの命名規則に沿った `createBatch` と `retrieveBatch` があります。各 SDK でのアップロードは[ファイル](https://phaseo.app/docs/ja/v1/sdk-reference/client/files.md)にあります。

## 非同期ジョブの WebSocket URL

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

## モデル、ヘルス、アカウント

クレジットとアクティビティには管理用 API キーが必要です。

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

// Credits and activity need a management API key.
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...")

# Credits and activity need a management API key.
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"));
```

## エラーを処理する

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

Gateway がエラーを返した場合、`PhaseoError`（Rust）には HTTP ステータスと解析済みの JSON 本文があります。通信と設定の失敗にはステータスがありません。各 SDK のエラーのフィールドは[概要](https://phaseo.app/docs/ja/v1/sdk-reference/client/overview.md#request-controls-and-errors)にあります。

## リクエストヘッダーを追加する

**Rust：** `with_header` は、以降のすべてのリクエストにヘッダーを追加します。

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