> ## 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 智能体的同步运行，并处理模型或工具故障。

## 生命周期事件

使用 `run_with_events(...)` 或 `continue_with_events(...)` 同步接收事件：

```rust theme={null}
use phaseo_agent::{AgentEvent, RunOptions};

let mut on_event = |event: &AgentEvent| {
    println!(
        "{} run={} details={}",
        event.event_type,
        event.run_id,
        event.details
    );
};

let result = agent.run_with_events(
    &mut client,
    RunOptions::new("Check project health"),
    Some(&mut on_event),
)?;
```

运行时目前会发出以下事件：

* `run.started`
* `model.request.started`
* `model.response.completed`
* `tool.started`
* `tool.completed`
* `run.paused`
* `run.resumed`
* `run.completed`
* `run.stopped`

回调在运行所在的线程中执行。请保持回调快速，或将工作交给其他组件。

## 模型重试

```rust theme={null}
use std::time::Duration;

let definition = AgentDefinition::new(
    "resilient-agent",
    "openai/gpt-6-astra",
)
.model_retries(2, Duration::from_millis(250));
```

`max_retries`统计首次请求之后的额外尝试次数。`RunStep.model_attempts`记录获得成功模型响应所需的尝试次数。

## 用量

`RunResult.usage`汇总以下数据：

* `input_tokens`
* `output_tokens`
* `cached_tokens`
* `total_tokens`
* 如果模型客户端填充了该值，则包含 `cost`

每个 `RunStep` 还包含自己的用量摘要、请求 ID、提供商、模型和结束原因。

内置的 `0.1` Gateway 适配器不会将 Gateway 的 `cost_nanos` 或 `cost_cents` 映射到 `UsageSummary.cost`。如需精确费用，请查看 Gateway 响应或生成记录。

## 错误

所有运行时故障均使用 `AgentError`：

```rust theme={null}
match agent.run(&mut client, options) {
    Ok(result) => println!("{}", result.output),
    Err(error) => eprintln!("Agent failed: {}", error.message()),
}
```

Gateway 的 `PhaseoError` 会转换为 `AgentError`。如果应用需要原始 Gateway 状态和响应正文，请直接调用 `phaseo` 客户端，或实现自定义 `ModelClient`，并在错误处理中保留这些字段。

本地工具执行器错误会作为工具结果返回给模型，而不会立即结束运行。

## 步骤上限

`AgentDefinition::max_steps(...)`设置默认模型轮次上限。可为单次运行覆盖此值：

```rust theme={null}
let mut options = RunOptions::new("Investigate this issue");
options.max_steps = Some(4);
```

达到上限时，`run.status`为 `stopped`，`run.stop_reason`为 `max_steps:<limit>`。


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