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

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

var client = new Phaseo(); // 读取 PHASEO_API_KEY
```

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

use Phaseo\Sdk\Phaseo;

$client = new Phaseo(); // 读取 PHASEO_API_KEY
```

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

client = PhaseoSdk::Phaseo.new # 读取 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()?; // 或使用 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 提供解析后的对话流。[对话补全](https://phaseo.app/docs/zh-Hans/v1/sdk-reference/client/chat-completions.md#stream-the-response)展示了 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/zh-Hans/v1/sdk-reference/client/responses.md) 介绍了 C#、PHP 和 Java 中的流式输出，以及在 Rust 中读取输出文本的方法。

## 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/zh-Hans/v1/sdk-reference/client/images-generations.md)和[图片编辑](https://phaseo.app/docs/zh-Hans/v1/sdk-reference/client/images-edits.md)。

## 音频

转写和翻译需要 multipart 上传。TypeScript 以 multipart 发送 `FormData` 正文。Python、Go、C#、PHP 和 Ruby 的方法发送 JSON，因此转写只能把 URL 传给接受 `file_url` 的模型，而翻译需要 multipart 上传。要从这些 SDK 上传音频文件，请参阅 [STT（语音转文本）](https://phaseo.app/docs/zh-Hans/v1/sdk-reference/client/audio-transcriptions.md#upload-an-audio-file)和[翻译](https://phaseo.app/docs/zh-Hans/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",
});

// 转写和翻译需要 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 发送 JSON，所以要把 URL 传给接受 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/zh-Hans/v1/sdk-reference/client/audio-translations.md)。**Java：** `createSpeech` 期望 JSON，无法解码二进制音频，因此语音请使用 `rawClient().requestBytes`；转写和翻译的上传请用 Java 的标准 HTTP 客户端发送，如 [STT](https://phaseo.app/docs/zh-Hans/v1/sdk-reference/client/audio-transcriptions.md) 和[翻译](https://phaseo.app/docs/zh-Hans/v1/sdk-reference/client/audio-translations.md)页面所示。

## 视频

```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/zh-Hans/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(...) 向没有高层辅助方法的端点发送 JSON。
// 路径可以带开头的斜杠，也可以不带。
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`；[文件](https://phaseo.app/docs/zh-Hans/v1/sdk-reference/client/files.md)介绍了每个 SDK 中的上传方式。

## 异步任务 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();

// 额度和活动需要管理 API 密钥。
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...")

# 额度和活动需要管理 API 密钥。
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 正文；传输和配置失败没有状态。[概览](https://phaseo.app/docs/zh-Hans/v1/sdk-reference/client/overview.md#request-controls-and-errors)列出了每个 SDK 中的错误字段。

## 添加请求头

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