Skip to main content

lellm_agent/runtime/
event.rs

1//! Agent 层流式事件与停止原因。
2
3/// Agent 层流式事件 — 封闭、强类型、exhaustive match
4///
5/// 终态契约:
6/// - 正常结束:`LoopEnd` 恰好一次,然后 channel 关闭
7/// - 异常结束:`LoopError` 恰好一次,然后 channel 关闭
8/// - 终态事件后不再发送任何事件
9#[derive(Debug, Clone)]
10pub enum AgentEvent {
11    /// Provider 层事件
12    Provider(lellm_provider::ProviderEvent),
13    /// 工具开始执行
14    ToolStart { tool_call_id: String, name: String },
15    /// 工具执行完成
16    ToolEnd {
17        tool_call_id: String,
18        result: super::ToolResult,
19        duration: std::time::Duration,
20    },
21    /// 工具重试(RetryPolicy 触发)
22    Retry {
23        tool_call_id: String,
24        attempt: usize,
25        max_attempts: usize,
26        reason: String,
27    },
28    /// 上下文压缩完成(可观测性事件)
29    ContextCompacted {
30        before_tokens: usize,
31        after_tokens: usize,
32        removed_messages: usize,
33    },
34    /// Agent loop 正常结束(恰好一次,后不再发送)
35    LoopEnd { result: super::ToolUseResult },
36    /// Agent loop 异常结束(恰好一次,后不再发送)— 不含 messages,消费者自行维护
37    LoopError {
38        error: lellm_core::LlmError,
39        iterations: usize,
40    },
41}
42
43/// Agent loop 停止原因 — 描述"为什么停止",而非"响应长什么样"
44#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
45pub enum StopReason {
46    /// Agent 已获得最终答案并正常结束
47    Complete,
48    /// 达到最大轮次
49    MaxIterationsReached,
50    /// 外部取消(消费者断开、task 终止等)
51    Cancelled,
52    /// 输出预算超限(单轮或总输出 token 超过限制)
53    OutputBudgetExceeded,
54    /// 推理预算超限(thinking token 超过限制)
55    ReasoningBudgetExceeded,
56}
57
58/// Agent 层流式事件通道类型别名
59pub type AgentStream = tokio::sync::mpsc::Receiver<AgentEvent>;