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

# 使用方法

> 创建 Rust 客户端，向 Gateway 发送请求，并处理响应和错误。

Rust 服务需要同步的 Phaseo Gateway 客户端时，请使用 `Phaseo`。

## 创建客户端

从环境变量中读取 API 密钥和可选的基础 URL：

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

let client = Phaseo::from_env()?;
```

也可以直接传入密钥：

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

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

`Phaseo` 会在 `Debug` 输出中隐藏 API 密钥和自定义标头值。

## 发送 Responses 请求

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

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Phaseo::from_env()?;
    let response = client.responses(&json!({
        "model": "openai/gpt-6-astra",
        "input": "Summarize why provider fallbacks improve reliability."
    }))?;

    let text = response.body
        .get("output")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter(|item| item.get("type").and_then(Value::as_str) == Some("message"))
        .flat_map(|item| {
            item.get("content")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
        })
        .find_map(|part| {
            (part.get("type").and_then(Value::as_str) == Some("output_text"))
                .then(|| part.get("text").and_then(Value::as_str))
                .flatten()
        })
        .unwrap_or("");

    println!("{text}");
    Ok(())
}
```

完整的 JSON 响应仍可通过 `response.body` 获取。

## 发送 Chat Completions 请求

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

## 调用其他 JSON 端点

如果某个 Phaseo 端点尚无高级辅助方法，请使用 `post(...)`：

```rust theme={null}
let response = client.post("/embeddings", &json!({
    "model": "openai/text-embedding-3-small",
    "input": "Phaseo routes across AI providers"
}))?;
```

路径开头的斜杠可以省略，也可以保留。

## 添加请求标头

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

## 处理 Gateway 错误

```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` 会包含 HTTP 状态和解析后的 JSON 正文。传输和配置错误没有 HTTP 状态。

## 下一步

* [Responses API](./responses.mdx)
* [Chat Completions](./chat-completions.mdx)
* [Rust API 参考](./api-reference.mdx)


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