|
| 1 | +--- |
| 2 | +title: "RunAgentSubscriber" |
| 3 | +description: |
| 4 | + "Event-driven subscriber system for agent lifecycle and event handling" |
| 5 | +--- |
| 6 | + |
| 7 | +# RunAgentSubscriber |
| 8 | + |
| 9 | +The `RunAgentSubscriber` interface provides a comprehensive event-driven system |
| 10 | +for handling agent lifecycle events, message updates, and state mutations during |
| 11 | +agent execution. It allows you to hook into various stages of the agent's |
| 12 | +operation and modify its behavior. |
| 13 | + |
| 14 | +```typescript |
| 15 | +import { RunAgentSubscriber } from "@ag-ui/client" |
| 16 | +``` |
| 17 | + |
| 18 | +## Core Interfaces |
| 19 | + |
| 20 | +### RunAgentSubscriber |
| 21 | + |
| 22 | +The main interface that defines all available event handlers and lifecycle |
| 23 | +hooks. |
| 24 | + |
| 25 | +```typescript |
| 26 | +interface RunAgentSubscriber { |
| 27 | + // Lifecycle events |
| 28 | + onRunInitialized?(): MaybePromise<Omit< |
| 29 | + AgentStateMutation, |
| 30 | + "stopPropagation" |
| 31 | + > | void> |
| 32 | + onRunFailed?(params: { |
| 33 | + error: Error |
| 34 | + }): MaybePromise<Omit<AgentStateMutation, "stopPropagation"> | void> |
| 35 | + onRunFinalized?(): MaybePromise<Omit< |
| 36 | + AgentStateMutation, |
| 37 | + "stopPropagation" |
| 38 | + > | void> |
| 39 | + |
| 40 | + // Event handlers |
| 41 | + onEvent?(params: { |
| 42 | + event: BaseEvent |
| 43 | + }): MaybePromise<AgentStateMutation | void> |
| 44 | + |
| 45 | + // State change handlers |
| 46 | + onMessagesChanged?(): MaybePromise<void> |
| 47 | + onStateChanged?(): MaybePromise<void> |
| 48 | + onNewMessage?(params: { message: Message }): MaybePromise<void> |
| 49 | + onNewToolCall?(params: { toolCall: ToolCall }): MaybePromise<void> |
| 50 | + |
| 51 | + // ... and many more event-specific handlers |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +### AgentStateMutation |
| 56 | + |
| 57 | +Defines how subscribers can modify the agent's state and control event |
| 58 | +propagation. |
| 59 | + |
| 60 | +```typescript |
| 61 | +interface AgentStateMutation { |
| 62 | + messages?: Message[] // Update the message history |
| 63 | + state?: State // Update the agent state |
| 64 | + stopPropagation?: boolean // Prevent further subscribers from processing |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +### RunAgentSubscriberParams |
| 69 | + |
| 70 | +Common parameters passed to most subscriber methods. |
| 71 | + |
| 72 | +```typescript |
| 73 | +interface RunAgentSubscriberParams { |
| 74 | + messages: Message[] // Current message history |
| 75 | + state: State // Current agent state |
| 76 | + agent: AbstractAgent // The agent instance |
| 77 | + input: RunAgentInput // The original input parameters |
| 78 | +} |
| 79 | +``` |
| 80 | + |
| 81 | +## Event Handlers |
| 82 | + |
| 83 | +### Lifecycle Events |
| 84 | + |
| 85 | +#### onRunInitialized() |
| 86 | + |
| 87 | +Called when the agent run is first initialized, before any processing begins. |
| 88 | + |
| 89 | +#### onRunFailed() |
| 90 | + |
| 91 | +Called when the agent run encounters an error. |
| 92 | + |
| 93 | +#### onRunFinalized() |
| 94 | + |
| 95 | +Called when the agent run completes, regardless of success or failure. |
| 96 | + |
| 97 | +### Message Events |
| 98 | + |
| 99 | +#### onTextMessageStartEvent() |
| 100 | + |
| 101 | +Triggered when a text message starts being generated. |
| 102 | + |
| 103 | +#### onTextMessageContentEvent() |
| 104 | + |
| 105 | +Called for each chunk of text content as it's generated. |
| 106 | + |
| 107 | +```typescript |
| 108 | +onTextMessageContentEvent?(params: { |
| 109 | + event: TextMessageContentEvent |
| 110 | + textMessageBuffer: string // Accumulated text so far |
| 111 | +}): MaybePromise<AgentStateMutation | void> |
| 112 | +``` |
| 113 | +
|
| 114 | +#### onTextMessageEndEvent() |
| 115 | +
|
| 116 | +Called when a text message generation is complete. |
| 117 | +
|
| 118 | +### Tool Call Events |
| 119 | +
|
| 120 | +#### onToolCallStartEvent() |
| 121 | +
|
| 122 | +Triggered when a tool call begins. |
| 123 | +
|
| 124 | +#### onToolCallArgsEvent() |
| 125 | +
|
| 126 | +Called as tool call arguments are being parsed. |
| 127 | +
|
| 128 | +```typescript |
| 129 | +onToolCallArgsEvent?(params: { |
| 130 | + event: ToolCallArgsEvent |
| 131 | + toolCallBuffer: string // Raw argument buffer |
| 132 | + toolCallName: string // Name of the tool being called |
| 133 | + partialToolCallArgs: Record<string, any> // Parsed arguments so far |
| 134 | +}): MaybePromise<AgentStateMutation | void> |
| 135 | +``` |
| 136 | +
|
| 137 | +#### onToolCallEndEvent() |
| 138 | +
|
| 139 | +Called when a tool call is complete with final arguments. |
| 140 | +
|
| 141 | +#### onToolCallResultEvent() |
| 142 | +
|
| 143 | +Triggered when a tool call result is received. |
| 144 | +
|
| 145 | +### State Events |
| 146 | +
|
| 147 | +#### onStateSnapshotEvent() |
| 148 | +
|
| 149 | +Called when a complete state snapshot is provided. |
| 150 | +
|
| 151 | +#### onStateDeltaEvent() |
| 152 | +
|
| 153 | +Triggered when partial state changes are applied. |
| 154 | +
|
| 155 | +#### onMessagesSnapshotEvent() |
| 156 | +
|
| 157 | +Called when a complete message history snapshot is provided. |
| 158 | +
|
| 159 | +## State Management |
| 160 | +
|
| 161 | +### Mutation Control |
| 162 | +
|
| 163 | +Subscribers can modify the agent's state by returning an `AgentStateMutation` |
| 164 | +object: |
| 165 | +
|
| 166 | +```typescript |
| 167 | +const subscriber: RunAgentSubscriber = { |
| 168 | + onTextMessageEndEvent: ({ event, textMessageBuffer, messages, state }) => { |
| 169 | + // Add the completed message to history |
| 170 | + const newMessage: Message = { |
| 171 | + id: generateId(), |
| 172 | + role: "assistant", |
| 173 | + content: [{ type: "text", text: textMessageBuffer }], |
| 174 | + } |
| 175 | + |
| 176 | + return { |
| 177 | + messages: [...messages, newMessage], |
| 178 | + state: { ...state, lastResponse: textMessageBuffer }, |
| 179 | + } |
| 180 | + }, |
| 181 | +} |
| 182 | +``` |
| 183 | + |
| 184 | +### Stopping Propagation |
| 185 | + |
| 186 | +Use `stopPropagation: true` to prevent subsequent subscribers from processing |
| 187 | +the event: |
| 188 | + |
| 189 | +```typescript |
| 190 | +const prioritySubscriber: RunAgentSubscriber = { |
| 191 | + onRunErrorEvent: ({ error }) => { |
| 192 | + if (error.message.includes("critical")) { |
| 193 | + // Handle critical error and stop other subscribers |
| 194 | + return { stopPropagation: true } |
| 195 | + } |
| 196 | + }, |
| 197 | +} |
| 198 | +``` |
| 199 | + |
| 200 | +## Utility Functions |
| 201 | + |
| 202 | +### runSubscribersWithMutation() |
| 203 | + |
| 204 | +Executes multiple subscribers in sequence and accumulates their mutations. |
| 205 | + |
| 206 | +```typescript |
| 207 | +async function runSubscribersWithMutation( |
| 208 | + subscribers: RunAgentSubscriber[], |
| 209 | + initialMessages: Message[], |
| 210 | + initialState: State, |
| 211 | + executor: ( |
| 212 | + subscriber, |
| 213 | + messages, |
| 214 | + state |
| 215 | + ) => MaybePromise<AgentStateMutation | void> |
| 216 | +): Promise<AgentStateMutation> |
| 217 | +``` |
| 218 | + |
| 219 | +## Usage Examples |
| 220 | + |
| 221 | +### Basic Event Logging |
| 222 | + |
| 223 | +```typescript |
| 224 | +const loggingSubscriber: RunAgentSubscriber = { |
| 225 | + onRunStartedEvent: ({ event }) => { |
| 226 | + console.log("Agent run started:", event.runId) |
| 227 | + }, |
| 228 | +
|
| 229 | + onTextMessageContentEvent: ({ textMessageBuffer }) => { |
| 230 | + console.log("Text content:", textMessageBuffer) |
| 231 | + }, |
| 232 | +
|
| 233 | + onRunFinishedEvent: ({ event, result }) => { |
| 234 | + console.log("Agent run completed:", result) |
| 235 | + }, |
| 236 | +} |
| 237 | +``` |
| 238 | + |
| 239 | +### Message History Management |
| 240 | + |
| 241 | +```typescript |
| 242 | +const historySubscriber: RunAgentSubscriber = { |
| 243 | + onTextMessageEndEvent: ({ textMessageBuffer, messages }) => { |
| 244 | + const assistantMessage: Message = { |
| 245 | + id: crypto.randomUUID(), |
| 246 | + role: "assistant", |
| 247 | + content: [{ type: "text", text: textMessageBuffer }], |
| 248 | + } |
| 249 | +
|
| 250 | + return { |
| 251 | + messages: [...messages, assistantMessage], |
| 252 | + } |
| 253 | + }, |
| 254 | +} |
| 255 | +``` |
| 256 | + |
| 257 | +### State Persistence |
| 258 | + |
| 259 | +```typescript |
| 260 | +const persistenceSubscriber: RunAgentSubscriber = { |
| 261 | + onStateChanged: async ({ state }) => { |
| 262 | + await saveStateToDatabase(state) |
| 263 | + }, |
| 264 | +
|
| 265 | + onMessagesChanged: async ({ messages }) => { |
| 266 | + await saveMessagesToDatabase(messages) |
| 267 | + }, |
| 268 | +} |
| 269 | +``` |
| 270 | + |
| 271 | +### Error Handling |
| 272 | + |
| 273 | +```typescript |
| 274 | +const errorHandlingSubscriber: RunAgentSubscriber = { |
| 275 | + onRunFailed: ({ error, state }) => { |
| 276 | + console.error("Agent run failed:", error) |
| 277 | +
|
| 278 | + return { |
| 279 | + state: { |
| 280 | + ...state, |
| 281 | + error: error.message, |
| 282 | + errorTimestamp: new Date().toISOString(), |
| 283 | + }, |
| 284 | + } |
| 285 | + }, |
| 286 | +} |
| 287 | +``` |
| 288 | + |
| 289 | +## Integration with Agents |
| 290 | + |
| 291 | +Subscribers are typically used with agents during the `runAgent()` call: |
| 292 | + |
| 293 | +```typescript |
| 294 | +const agent = new HttpAgent({ url: "https://api.example.com/agent" }) |
| 295 | +
|
| 296 | +// Register subscribers |
| 297 | +agent.addSubscriber(loggingSubscriber) |
| 298 | +agent.addSubscriber(historySubscriber) |
| 299 | +agent.addSubscriber(persistenceSubscriber) |
| 300 | +
|
| 301 | +// Run the agent |
| 302 | +const eventStream = agent.runAgent({ |
| 303 | + tools: [myTool], |
| 304 | + context: [{ type: "text", content: "Context information" }], |
| 305 | +}) |
| 306 | +``` |
| 307 | + |
| 308 | +## Best Practices |
| 309 | + |
| 310 | +1. **Error Handling**: Always wrap subscriber logic in try-catch blocks or |
| 311 | + handle promise rejections |
| 312 | +2. **Performance**: Keep subscribers lightweight; heavy operations should be |
| 313 | + async |
| 314 | +3. **State Immutability**: Always create new objects when modifying state or |
| 315 | + messages |
| 316 | +4. **Event Ordering**: Subscribers run in registration order; critical |
| 317 | + subscribers should be registered first |
| 318 | +5. **Propagation Control**: Use `stopPropagation` sparingly, only for critical |
| 319 | + error conditions |
0 commit comments