Events API¶
Agent.run() yields event objects. Use isinstance(event, TextChunkEvent) or
compare event.type to an EventType member; EventType is not a string enum.
Usage is attached to events, not emitted as a separate "usage" event.
See Events for consumption patterns.
TextDoneEvent completes a model response; DoneEvent completes the agent
interaction. Do not display both text chunks and final text as if they were
different answers. Tool failures use ToolResultEvent.error; generation
failures use ErrorEvent.message. Initialization and extension failures can
also raise exceptions instead of emitting an error event.
Streaming tool generation emits ToolCallProgressEvent before an executable
ToolCallEvent is available. The preview contains a cumulative arguments_text
snapshot (at most 16,384 characters), arguments_truncated, a unique
generation_id, and a stable output index. Call IDs and names may arrive after
the first snapshot. Use the generation/index pair to update one preview rather
than appending every snapshot. The final call carries the same identifiers in
extra and retains its complete, validated arguments.
Progress status is streaming, ready after protocol validation, or abandoned
after a failed attempt. A preview is never executed or stored as conversation
history. A cancelled consumer may close before an abandonment event can be sent;
clients must stop loading indicators when their enclosing run ends. A ready call
can still be queued behind another call or require approval.
ToolExecutionStartedEvent identifies the next tool the agent invokes. The tool
may request approval as part of that invocation; this event is not proof that
side effects have occurred. ToolResultEvent remains the execution outcome.
When the agent exhausts its configured model/tool rounds, it emits
ErrorEvent(code="MAX_TOOL_ROUNDS", recoverable=False) followed by
DoneEvent(finish_reason=FinishReason.UNKNOWN). The existing error message and
usage totals are retained. For a positive plain integer limit, the error includes
extra={"max_tool_rounds": 30} (using the actual configured value); booleans and
other values are never coerced into this metadata. This is a round budget, not an
aggregate tool-call count: one round can contain several calls. No extra model
turn or automatic retry is added when the budget is exhausted.
ResponseMetadataEvent is a cumulative, display-only snapshot for one provider
call. response_id is unique per call (including retries and tool rounds),
response_session_id identifies its actual root or child session, and revision
increases when the snapshot changes. Text and tool events carry the same identity
in extra. history_id names the exact saved assistant row when available;
interrupted or reasoning-only responses can have no assistant row.
summary contains only text explicitly marked for display, capped at 16,384
characters. Custom providers opt in with ReasoningChunkEvent(displayable=True);
the default False keeps private framework reasoning out of display metadata.
Responses summary chunks also carry summary_part=(output_index, summary_index).
Each chunk is still a delta for that part; an empty tuple denotes an unkeyed
stream. The response trace assembles nonempty parts in index order with paragraph
separators, including late body text for an earlier part. Consumers that need the
assembled display text can use cumulative ResponseMetadataEvent.summary.
summary_truncated indicates this cap. Status thinking is emitted
only after a provider reports a thinking phase or summary; responding means the
reported phase has ended or no thinking phase has been reported. Neither status
estimates tokens. The terminal states are completed, cancelled, and failed.
Core consumers that close a generator early may receive no terminal event; the
web host separately checkpoints the latest producer snapshot during cleanup.
usage_reported distinguishes unavailable usage from actual zero counts.
prompt_reported, completion_reported, and total_reported identify which
individual counters were supplied; a reasoning-only frame does not claim zero
input or output, and an inferred provider total is not labelled reported.
Usage.reasoning_reported makes the same distinction for reasoning alone.
reasoning_in_output is included, separate, or unknown; never add reasoning
again when it is already included in output. Repeated cumulative usage snapshots
are merged per provider call, preserving earlier counts when a later frame only
contains a reasoning breakdown. Session reasoning totals carry a coverage flag:
reasoning_reported is true only if every observed call reported that breakdown.
These billing totals do not change the context-size estimate.
The web UI describes this known error as a round limit using fixed safe text. A native child that reaches its limit remains failed, retains its history, and reports a fixed budget explanation to its parent. These diagnostics do not change the library, Harness, or child round limits or their cleanup behavior.
If a descendant finishes while its immediate parent is stopping or cancelled,
the Harness keeps the descendant's TaskCompleted outcome and withholds delivery.
It emits the host-owned TaskDeliveryWarning subtype of ErrorEvent, with code
TASK_DELIVERY_SKIPPED and recoverable=True. Recoverable refers to the root run:
it may continue or delegate replacement work, but descendant data is never routed
directly to Main and the failed/cancelled child outcomes are not changed.
This diagnostic carries the child's short session_id, display title, short
parent_session_id (empty for a direct child), actual root root_session_id,
depth, activation, and followup. The web client retains only these
host-owned scope fields and fixed safe text, so a child warning does not clear
Main's tool preview or mark its run failed. Private storage IDs and task execution
handles are not part of the public event. Ordinary provider errors cannot gain
this scope by copying the code or adding metadata. Missing or mismatched parent
identities remain fatal errors.
Built-in text providers attach safe diagnostics to caught generation failures in
ErrorEvent.extra["transport"]. Existing code, message, and recoverable
values keep their meaning; diagnostics do not enable retries or change deadlines.
Authentication, model-discovery, and other failures may omit this metadata.
Native Codex also omits it for early request validation and non-200 HTTP replies,
which keep their existing specific error codes.
| Field | Meaning |
|---|---|
category |
A fixed classification: dns, connect, tls, connect_timeout, read_timeout, timeout, connection_lost, connection, response_payload, decode, invalid_data, protocol, http, or unknown. |
phase |
Native Codex reports request before response headers and response after headers arrive. The shared provider path reports unknown because its outer error handler does not observe that boundary. |
generation_elapsed_ms |
Elapsed time for the generation invocation through failure, including retries and backoff; this is not an individual HTTP request duration. |
model_call_id |
The current observation scope's existing call ID, when available and valid. It is not a newly minted HTTP request ID; direct provider calls can inherit the current context or omit it. |
A generic timeout remains timeout; it does not prove a read, connect, or total
request deadline expired. Generic ValueError remains invalid_data, rather
than being misreported as decoding. Diagnostics contain no exception messages,
URLs, headers, response/request bodies, or authentication values. Raw HTTP
logging and the opt-in payload observer remain separate facilities. Library
consumers and ngn --json retain the nested metadata. The normal web error view
and other human-readable clients continue to show their existing safe messages.
nagents.EventType
¶
Bases: Enum
Types of events that can be emitted during generation.
Source code in src/nagents/events/types.py
nagents.Event
dataclass
¶
Base event with common fields.
Source code in src/nagents/events/types.py
nagents.TextChunkEvent
dataclass
¶
nagents.ReasoningChunkEvent
dataclass
¶
Bases: Event
Reasoning text; only explicitly displayable provider summaries enter UI metadata.
Source code in src/nagents/events/types.py
nagents.TextDoneEvent
dataclass
¶
nagents.ToolCallEvent
dataclass
¶
Bases: Event
Model requesting a tool call.
Source code in src/nagents/events/types.py
nagents.ToolCallProgressEvent
dataclass
¶
Bases: Event
Bounded cumulative preview; never an instruction to execute a tool.
A generation ID belongs to one provider attempt. Index remains stable even when the provider supplies the call ID or function name in later chunks. Ready means protocol validation passed, not that the tool has executed.
Source code in src/nagents/events/types.py
nagents.ToolExecutionStartedEvent
dataclass
¶
Bases: Event
The agent is invoking a tool; its callable may still request approval.
Source code in src/nagents/events/types.py
nagents.ToolResultEvent
dataclass
¶
nagents.ErrorEvent
dataclass
¶
nagents.RateLimitEvent
dataclass
¶
Bases: Event
Rate limit hit during generation, automatic retry in progress.
Emitted each time a retryable HTTP error (429 or 5xx) is encountered and the provider will retry after a delay.
Source code in src/nagents/events/types.py
nagents.DoneEvent
dataclass
¶
nagents.FinishReason
¶
Bases: Enum
Reason why the model stopped generating.
Source code in src/nagents/events/types.py
nagents.Usage
dataclass
¶
Token usage statistics with current generation and session totals.
Attributes:
| Name | Type | Description |
|---|---|---|
prompt_tokens |
int
|
Input tokens for current generation |
completion_tokens |
int
|
Output tokens for current generation |
total_tokens |
int
|
Total tokens for current generation |
cached_tokens |
int
|
Cached prompt tokens (OpenAI) |
audio_tokens |
int
|
Audio input/output tokens |
reasoning_tokens |
int
|
Tokens used for reasoning/thinking (chain-of-thought models) |
reasoning_reported |
bool
|
Distinguishes a provider-reported zero from an absent breakdown |
reasoning_in_output |
Literal['included', 'separate', 'unknown']
|
Whether reasoning is included in completion_tokens |
reported |
bool
|
The provider supplied usage counts, even if every count is zero |
prompt_reported |
bool
|
The provider supplied an input count, including zero |
completion_reported |
bool
|
The provider supplied an output count, including zero |
total_reported |
bool
|
The provider supplied a total; inferred totals remain unreported |
session |
TokenUsage | None
|
Cumulative token usage across the entire session/run |
Source code in src/nagents/events/types.py
has_usage()
¶
Check if this usage has any actual token counts.
Source code in src/nagents/events/types.py
nagents.TokenUsage
dataclass
¶
Token counts for a generation or session.
Source code in src/nagents/events/types.py
nagents.CompactionStartedEvent
dataclass
¶
Bases: Event
Event emitted when compaction begins.
Attributes:
| Name | Type | Description |
|---|---|---|
trigger |
str | None
|
Optional strategy trigger description |
message_count |
int
|
Number of messages before compaction |
estimated_tokens |
int
|
Estimated token count before compaction |
session_id |
str
|
Original session ID |
compaction_session_id |
str
|
Session ID used for compaction |
Source code in src/nagents/events/types.py
nagents.CompactionDoneEvent
dataclass
¶
Bases: Event
Event emitted when compaction completes.
Attributes:
| Name | Type | Description |
|---|---|---|
original_message_count |
int
|
Number of messages before compaction |
original_token_count |
int
|
Estimated tokens before compaction |
new_message_count |
int
|
Number of messages after compaction |
summary_tokens |
int
|
Estimated tokens in the summary |
summary_text |
str
|
Full summary text |
trigger |
str | None
|
The trigger that caused compaction |
compactor_used |
str
|
Strategy name used for compaction |
session_id |
str
|
Original session ID |
compaction_session_id |
str
|
Session ID used for compaction |