Serialization
Serialization in AG-UI provides a standard way to persist and restore the event stream that drives an agent–UI session. With a serialized stream you can:- Restore chat history and UI state after reloads or reconnects
- Attach to running agents and continue receiving events
- Create branches (time travel) from any prior run
- Compact stored history to reduce size without losing meaning
Core Concepts
- Stream serialization – Convert the full event history to and from a portable representation (e.g., JSON) for storage in databases, files, or logs.
- Event compaction – Reduce verbose streams to snapshots while preserving semantics (e.g., merge content chunks, collapse deltas into snapshots).
- Run lineage – Track branches of conversation using a
parentRunId, forming a git‑like append‑only log that enables time travel and alternative paths.
Updated Event Fields
TheRunStarted event includes additional optional fields:
Event Compaction
Compaction reduces noise in an event stream while keeping the same observable outcome. A typical implementation provides a utility:- Message streams – Combine
TEXT_MESSAGE_*sequences into a single message snapshot; concatenate adjacentTEXT_MESSAGE_CONTENTfor the same message. - Tool calls – Collapse tool call start/content/end into a compact record.
- State – Merge consecutive
STATE_DELTAevents into a single finalSTATE_SNAPSHOTand discard superseded updates. - Run input normalization – Remove from
RunStarted.input.messagesany messages already present earlier in the stream.
Branching and Time Travel
SettingparentRunId on a RunStarted event creates a git‑like lineage. The
stream becomes an immutable append‑only log where each run can branch from any
previous run.
Benefits:
- Multiple branches in the same serialized log
- Immutable history (append‑only)
- Deterministic time travel to any point
Examples
Basic Serialization
Event Compaction
Before:Branching With parentRunId
Normalized Input
Implementation Notes
- Provide SDK helpers for compaction and (de)serialization.
- Store streams append‑only; prefer incremental writes when possible.
- Consider compression when persisting long histories.
- Add indexes by
threadId,runId, and timestamps for fast retrieval.
See Also
- Concepts: Events, State Management
- SDKs: TypeScript encoder and core event types