AG-UI Protocol Adapter¶
AG-UI is an open protocol, by CopilotKit, for streaming agent events to a frontend. langgraph_events.agui maps an EventGraph stream to AG-UI SSE events.
RunAgentInput -> SeedFactory -> EventGraph.astream_events -> [Mapper Chain] -> SSE
^
ResumeFactory -> astream_resume (if resuming)
RunAgentInput -> AGUIAdapter.connect/reconnect -> RunStarted + checkpoint snapshots + interrupts + RunFinished
RunAgentInput -> AGUIAdapter.snapshot -> RunStarted + checkpoint snapshots + RunFinished
AGUIAdapter streams LLM tokens and custom events. AGUIAdapter(...) raises ValueError unless the graph registers message_reducer(). That reducer is the authoritative message channel.
Install¶
pip install "langgraph-events[agui]"
The HTTP layer also needs starlette or fastapi.
Quick Start¶
from fastapi import FastAPI, Request
from ag_ui.core import RunAgentInput
from langgraph.checkpoint.memory import MemorySaver
from langgraph_events import Event, EventGraph, IntegrationEvent, MessageEvent, message_reducer, on
from langgraph_events.agui import AGUIAdapter, create_starlette_response
from langchain_core.messages import HumanMessage, AIMessage
class UserMessageReceived(IntegrationEvent, MessageEvent):
message: HumanMessage
class AssistantReplied(IntegrationEvent, MessageEvent):
message: AIMessage
@on(UserMessageReceived)
async def reply(event: UserMessageReceived) -> AssistantReplied:
return AssistantReplied(message=AIMessage(content="Hello from the agent!"))
graph = EventGraph([reply], checkpointer=MemorySaver(), reducers=[message_reducer()])
def seed_factory(input_data: RunAgentInput) -> list[Event]:
last_msg = input_data.messages[-1]
return [UserMessageReceived(message=HumanMessage(content=last_msg.content))]
adapter = AGUIAdapter(graph, seed_factory=seed_factory)
app = FastAPI()
@app.post("/api/copilotkit")
async def run(request: Request):
input_data = RunAgentInput.model_validate_json(await request.body())
return create_starlette_response(adapter.stream(input_data))
A seed factory that reads only the input is an InputSeedFactory. A seed factory that also takes checkpoint_state is a SeedFactory. seed_factory= accepts both.
Pass error_message="Something went wrong." to AGUIAdapter(...) so that exception details do not reach the client. To send the client a specific error code from a factory, see Async Factories and Refusals.
Built-in Mapper Chain¶
Mappers claim events in priority order. The first non-None return wins. An unclaimed event falls through.
| Priority | Mapper | Handles | AG-UI Events Produced |
|---|---|---|---|
| 1 | SkipInternalMapper |
Resumed, Dismissed, SystemPromptSet, FrontendStateMutated |
(suppressed) |
| 2 | FrontendToolCallRequestedMapper |
FrontendToolCallRequested |
ToolCallStart / ToolCallArgs / ToolCallEnd |
| 3 | InterruptedMapper |
Interrupted subclasses |
CustomEvent (name="interrupted") |
| 4 | (user mappers) | (your custom logic) | (any AG-UI event) |
| 5 | FallbackMapper |
Unclaimed AGUISerializable events |
CustomEvent (name=agui_event_name if implemented else class name, value=agui_dict()) |
An event without agui_dict() is skipped with a one-time warning.
Unmapped-event policy¶
An internal event, for example a Command or a routing DomainEvent, has no AG-UI representation. AGUIAdapter(..., on_unmapped=...) controls what happens to it:
| value | behavior |
|---|---|
"warn" (default) |
Once-per-class UserWarning, then drop. |
"ignore" |
Drop silently. Recommended for an app whose events are mostly internal. |
"raise" |
Raise UnmappedEventError, a TypeError subclass, that names the class. Use it as a CI gate. |
The policy applies to FallbackMapper and to the non-serializable branch of InterruptedMapper. A serializable event, and an InterruptedWithPayload, still emits.
Outside the chain, the adapter also emits:
StateSnapshot/MessagesSnapshotfromStreamFramereducer data.MessagesSnapshotreads themessage_reducer()channel. Redundant snapshots are skipped whenchanged_reducersis available.StateSnapshotFrame→StateSnapshot.CustomEventFrame→CustomEvent(name/value passthrough).InterruptFrame→ itsvaluethrough the mapper chain. The run yields one frame for each interrupt that it leaves pending.- Lifecycle:
RunStarted,RunFinished,RunErroron exception. A handler that raisesRunRefusedErrorgets the genericRunError, see Async Factories and Refusals. TheoutcomeofRunFinishedtells a paused run and a stopped run from a completed run, see Run outcomes.
Shaping client-facing state¶
AGUIAdapter(include_reducers=...) controls what reducer state reaches the client:
| Value | Behaviour |
|---|---|
True (default) |
Each user reducer and each Derived, in registration order |
list[str] |
Allow-list only (e.g. ["focus", "scene"]). A list can name a Derived |
False |
No user reducers (MessagesSnapshot is still sent) |
The value applies to outbound state and to the inbound RunAgentInput.state echo, so a client cannot inject a key you keep internal. Every framework channel, and the messages key, is stripped first, whatever include_reducers holds. The allow-list also gates which reducers EventGraph computes during streaming. A Derived value is computed on the server, so the adapter drops a Derived key from the inbound client state. Each selected value reads the empty default of its reducer while its channel is unset. On a thread with no checkpoint, connect() and snapshot() send these defaults, and each Derived computed from them. The fn of a selected Derived must accept these defaults. If it raises, the replay ends with RUN_ERROR. For redaction or value transformation, write a custom EventMapper.
Messages reach the client on two paths at the same time. The authoritative path is MessagesSnapshot from the message_reducer() channel. The real-time path is the TextMessageStart / Content / End tokens. An AG-UI client reconciles them by message id.
Message field mapping¶
MessagesSnapshot converts each LangChain BaseMessage to its AG-UI counterpart:
| LangChain | AG-UI | Direction | Notes |
|---|---|---|---|
id, content |
id, content |
both | AG-UI declares both as text. AssistantMessage.content is None for block content, and SystemMessage degrades it to "". A UserMessage or ToolMessage carries block content as content parts. See the content blocks row below. |
name |
name |
both | UserMessage, AssistantMessage and SystemMessage only. The AG-UI ToolMessage declares no name. |
AIMessage.tool_calls |
AssistantMessage.tool_calls |
both | args are JSON-encoded into function.arguments. |
ToolMessage.status |
ToolMessage.error |
both | status="error" sends the content as error, or the literal "error" when the content is empty, because a falsy error reads as a success. A truthy inbound error sets status="error". The error text does not come back: LangChain's ToolMessage has no field for it. |
| (none) | encrypted_value |
neither | Declared on AG-UI BaseMessage, ToolMessage and ToolCall. The adapter never reads it inbound and never sets it outbound, so a value the client sent is dropped. |
content blocks |
content parts |
both | On a UserMessage or ToolMessage, each part maps to the LangChain standard block of the same modality. A document part maps to a file block. A data source maps to base64 with mime_type, and a url source maps to url. A part id is kept. Outbound, LangChain first translates each block to a standard block, so an image_url block also maps, and a file_id maps to a file source. Outbound, a block with no AG-UI part, such as a base64 block without mime_type, is dropped with a WARNING that names the message. Inbound, a part with a file source is held, not sent to the model. See Parts the model does not receive. Inbound, the metadata of a kept part is dropped with a WARNING, because a LangChain block has no field for it. |
additional_kwargs[AGUI_EXTRAS_KEY]["metadata"] |
metadata |
both | AG-UI 1.0 declares metadata as an open mapping of extra data. Before 1.0 it was an extra field, so it stays in the extras slot. AGUI_EXTRAS_OPEN_FIELDS lists each such field. A non-mapping value is dropped outbound, with a WARNING. |
| (none) | subagent_run_id |
neither | Declared on AG-UI 1.0 messages. The adapter never reads it inbound and never sets it outbound. |
additional_kwargs[AGUI_EXTRAS_KEY] |
(extra fields) | both | Passthrough. See below. |
additional_kwargs[AGUI_HELD_PARTS_KEY] |
content parts with a file source |
both | Held. See Parts the model does not receive. |
Passing extra data on a message¶
An AG-UI message allows extra fields that the protocol does not declare, for example a retry hint on a failure notice. Put a mapping under the reserved additional_kwargs key AGUI_EXTRAS_KEY, the literal string "langgraph_events.agui". Each entry becomes a top-level field on the AG-UI message. Use the constant, not the literal.
from langchain_core.messages import SystemMessage
from langgraph_events.agui import AGUI_EXTRAS_KEY
SystemMessage(
content="The step failed.",
additional_kwargs={AGUI_EXTRAS_KEY: {"failure": {"retryable": True}}},
)
# -> AG-UI SystemMessage(id=..., role="system", content="The step failed.",
# failure={"retryable": True})
Nothing else in additional_kwargs is forwarded. Inbound, agui_messages_to_langchain and detect_new_tool_results both collect the extra fields of an AG-UI message back into additional_kwargs[AGUI_EXTRAS_KEY].
WARNING: Inbound extras arrive verbatim. They flow through add_messages into the checkpoint. They return on the next MessagesSnapshot to every client on that thread. The adapter neither filters the keys nor inspects the values. Do not treat a value read from the slot as trusted input. If more than one person can reach a thread, strip or scope the slot yourself. AGUI_EXTRAS_MAX_BYTES (8 KiB of JSON per message) bounds how much a client can add. Extras over the cap, or extras that do not encode as JSON, are dropped with a WARNING naming the message. The message itself still converts.
MessagesSnapshot is rebuilt from the checkpointed message list on every connect(). If that build raises, the client gets a RunError on every connect(), and the thread stays broken until someone edits the checkpoint. So nothing in the extras path raises. Four cases drop something and warn once per message class:
| Case | Dropped |
|---|---|
| The reserved key holds a non-mapping | The whole value |
| An entry key is not a string | That entry |
An entry in AGUI_EXTRAS_OPEN_FIELDS holds a non-mapping |
That entry |
An entry addresses another declared AG-UI field (content, toolCallId, …) |
That entry. Otherwise it rewrites protocol data. |
Rename the entry, or set the field through the LangChain message.
Parts the model does not receive¶
A user or tool message can carry a media part with a file source, for example a DocumentPart. AG-UI defines that source as a handle that a provider issued. The server would send the handle with its own credentials, so a client could read a file that it does not own. The model must not receive such a part.
Inbound, agui_messages_to_langchain and detect_new_tool_results hold the part, with its metadata and its position, under the reserved additional_kwargs key AGUI_HELD_PARTS_KEY. Outbound, MessagesSnapshot puts each held part back at its position, on stream() and on connect(). A host that issues its own file handles reads them with held_parts().
from ag_ui.core import DocumentPart, FileSource, TextPart, UserMessage
from langgraph_events.agui import agui_messages_to_langchain, held_parts
doc = DocumentPart(source=FileSource(value="doc-42", provider="host"))
[message] = agui_messages_to_langchain(
[UserMessage(id="u1", content=[TextPart(text="Read this."), doc])]
)
message.content # -> [{"type": "text", "text": "Read this."}] (the model sees only this)
held_parts(message) # -> [doc]
# The next MessagesSnapshot sends content=[TextPart(text="Read this."), doc].
content stays a list of standard blocks. If the only part of a message is held, content is []. Some providers refuse a message with empty content. If a client sends only held parts, give the model a text of your own.
Each entry of the slot is {"position": i, "part": p}. i is the position of the part in the AG-UI content list.
held_parts(message) returns the held parts in their original order and never raises, because it reads checkpointed data. It skips an entry that does not validate, with a WARNING that names the message and the key. The snapshot drops a bad entry the same way. If a handler made the content shorter, a position past the end puts the part at the end, with a WARNING that names the message and the key.
A host can merge messages, for example with LangChain's merge_message_runs. The merged message keeps every held entry, but each position still counts in its own original message. So the snapshot can restore a part at a shifted position.
WARNING: A held part is client input. The trust note of the extras slot applies to it.
Each reserved slot has its own size cap, measured as JSON per message:
| Slot | Cap | Over the cap |
|---|---|---|
AGUI_EXTRAS_KEY |
AGUI_EXTRAS_MAX_BYTES, 8 KiB |
The extras are dropped with a WARNING. The message still converts. |
AGUI_HELD_PARTS_KEY |
AGUI_EXTRAS_MAX_BYTES, 8 KiB, counted apart from the extras |
The held parts are dropped with a WARNING. The model still does not receive them, and the message still converts. |
So one message can store up to 16 KiB in the two slots.
Connect / Reconnect¶
connect(), alias reconnect(), runs no handler. It emits RunStarted, then StateSnapshot and MessagesSnapshot from the checkpoint, then each pending Interrupted event, then RunFinished. On a thread paused on an interrupt, RunFinished carries the interrupt outcome, see Run outcomes. If the replay raises, RunError ends the stream instead of RunFinished. One exception applies: with on_unmapped="raise", an UnmappedEventError propagates to the caller and does not become RunError. The stream then ends without a terminal event, the same as in stream(). An AG-UI client refuses a stream that does not start with RunStarted, so do not strip these events. Call connect on page load or refresh. Call stream only to start or resume execution. Serve it like the Quick Start route: create_starlette_response(adapter.connect(input_data)).
Snapshot while a run holds the thread¶
snapshot() emits the events of connect() without the pending interrupts: RunStarted, StateSnapshot, MessagesSnapshot, then RunFinished with no outcome. It takes the same config=. Use it when a live run holds the thread, for example after a page refresh during a resume. The live run raises its own interrupts, so connect() would show each interrupt two times.
Replay the state with snapshot(), then forward the stream of the live run. snapshot() ends with RunFinished, so the forwarded stream must start with the RunStarted of the live run. The run_id of the snapshot run must differ from the run_id of the live run.
Only the caller knows that a run holds the thread
The adapter cannot detect a live run from the checkpoint. While the first step of a resume runs, the checkpoint still lists the answered interrupt. The resume value stays a pending write until that step commits.
Custom Mappers¶
Implement EventMapper.map(): return None (pass), [] (suppress), or AG-UI events.
...
from ag_ui.core import BaseEvent, CustomEvent, EventType
from langgraph_events.agui import AGUIAdapter, EventMapper, MapperContext
class PlanningStarted(IntegrationEvent):
goal: str
class PlanMapper:
def map(self, event: Event, ctx: MapperContext) -> list[BaseEvent] | None:
if not isinstance(event, PlanningStarted):
return None # pass to next mapper
return [
CustomEvent(type=EventType.CUSTOM, name="step_started", value={"goal": event.goal}),
]
adapter = AGUIAdapter(graph, seed_factory=seed_factory, mappers=[PlanMapper()])
Resume Support¶
Implement resume_factory(input_data, checkpoint_state). Return an Event to trigger astream_resume(). Return None for a fresh run via seed_factory. On a thread paused on an Interrupted, None instead replays the checkpoint. The adapter emits StateSnapshot, MessagesSnapshot and each pending Interrupted, then RunFinished with the interrupt outcome. It does not call seed_factory. checkpoint_state is optional. A one-argument factory still works. A resume_factory can be async and can refuse the run, see Async Factories and Refusals.
...
from typing import Any
class ApprovalSubmitted(IntegrationEvent):
approved: bool
def resume_factory(
input_data: RunAgentInput,
checkpoint_state: dict[str, Any] | None,
) -> Event | None:
# checkpoint_state: CheckpointState TypedDict with reducers, events,
# messages, pending_interrupts, is_interrupted, snapshot. Each reducer
# value is a shallow copy, so a change to it does not reach the run.
state = input_data.state or {}
if "approved" in state:
return ApprovalSubmitted(approved=state["approved"])
return None # fresh run
adapter = AGUIAdapter(graph, seed_factory=seed_factory, resume_factory=resume_factory)
When RunAgentInput.state is populated alongside a resume:
- The state dict is projected via
include_reducers. Every framework channel and themessageskey are stripped. - A
FrontendStateMutated(state=projected)event is built. It rides in the answer of the resume, so the paused handler stores it, with the share of each reducer that subscribes to it, before the answer. The handlers of the answer then see the updated value. The event appears in the stream and the audit log. - The client state reaches the handlers when the paused handler finishes. A handler that pauses again in the resume stores the client state of each resume when it finishes. The re-run of the paused handler does not see it.
- A stop that cuts the resume stores no client state.
- When the thread is not paused, the adapter drops the answer and applies the client state as on a fresh run. A thread with a pending run but no open interrupt refuses the client state with
RUN_ERRORcodepending_run_takes_no_client_state. See Run outcomes. - When each answered handler names
langgraph.types.interruptin its code, the run is refused before the graph runs, withRUN_ERRORcoderaw_interrupt_takes_no_client_state. A call in a helper function that the handler calls is not seen, see Stop on a signal. Such a call cannot take client state. The thread keeps its questions. Resume withoutstate, or return theInterruptedfrom the handler. - A domain-driven reducer wins for a shared key. A backend channel stays intact, whatever the client echoes.
- An
@on(FrontendStateMutated)handler fires on resume, once, as on a fresh run.
A reducer can subscribe to FrontendStateMutated to project a selected client-state key on the server. A module-level reducer must set name=: ScalarReducer[FrontendStateMutated, str](name="focus", event_type=FrontendStateMutated, fn=lambda e: e.state.get("focus", SKIP)).
Async Factories and Refusals¶
A seed_factory or a resume_factory can be async. The adapter awaits the result. A sync factory still works. The optional checkpoint_state argument works the same way for both kinds.
A factory can refuse the run. Raise RunRefusedError(code, message). The adapter then sends RUN_STARTED, then one RUN_ERROR with that code and that message, and nothing after. The graph does not start, so the run stores nothing in the checkpoint. The error_message of the adapter does not replace the message of a refusal. The adapter logs the code of a refusal at WARNING, without the message and without a traceback.
The example builds on the Quick Start. KNOWN_FILE_IDS stands in for your own upload store.
...
from ag_ui.core import RunAgentInput
from langchain_core.messages import HumanMessage
from langgraph_events import Event
from langgraph_events.agui import AGUIAdapter, RunRefusedError
KNOWN_FILE_IDS: set[str] = set()
async def file_exists(file_id: str) -> bool:
return file_id in KNOWN_FILE_IDS
async def seed_factory(input_data: RunAgentInput) -> list[Event]:
last_msg = input_data.messages[-1]
if not await file_exists(last_msg.id):
raise RunRefusedError("unknown_file", "The attached file does not exist.")
return [UserMessageReceived(message=HumanMessage(content=last_msg.content))]
adapter = AGUIAdapter(graph, seed_factory=seed_factory)
A client reads two fields of RUN_ERROR: code and message. A refusal always sets code. A generic error has no code. A client branches on the presence of code.
connect() calls no factory, so a refusal cannot occur there.
The adapter catches RunRefusedError only from the two factories. A handler that raises RunRefusedError gets the same treatment as any other exception: a generic RUN_ERROR without a code. This path logs at ERROR with a traceback, and the traceback includes the message of the refusal. The graph has run by then, so the run can have stored events.
Frontend Tools¶
The AG-UI spec positions tool calls as "inherently frontend-executed" and as the mechanism for human-in-the-loop (HITL) interaction. The adapter wires all three parts to an EventGraph:
- Tool definitions in. The
useFrontendToolregistrations of the page arrive asRunAgentInput.tools.build_langchain_tools(...)converts them to OpenAI-format dicts forllm.bind_tools(...). - Tool calls out. Two paths, both map to
ToolCallStart/ToolCallArgs/ToolCallEnd:- LLM-initiated. Bound LLM
tool_call_chunkstranslate to the streaming triple when the call name is inRunAgentInput.tools. A call to a backend tool emits noToolCall*event, is logged once atDEBUG, and the text tokens of the same LLM run still stream. TheMessagesSnapshothistory still holds every tool call, because the spec scopesRunAgentInput.toolsto execution. If you list a backend tool, the client executes it. Do not list a backend tool to show it in the UI. EmitToolCallStart,ToolCallArgs,ToolCallEndandToolCallResultfrom a customEventMapperinstead. - Handler-initiated. Return
FrontendToolCallRequested(Interrupted)from a handler. See Handler-initiated frontend tools.
- LLM-initiated. Bound LLM
- Tool results back. The return value of the frontend handler comes back as a
role: "tool"message.detect_new_tool_results(input_data, checkpoint_state)returns the newToolMessages. Wrap them in aMessageEventand return it fromresume_factory.
... # ToolsRegistered, ToolsExecuted, LLMResponded as in examples/conversation.py
from langgraph_events import on
from langgraph_events.agui import build_langchain_tools, detect_new_tool_results
def seed_factory(input_data, checkpoint_state=None):
return [
ToolsRegistered(tools=tuple(input_data.tools or [])),
UserMessageReceived(message=HumanMessage(content=input_data.messages[-1].content)),
]
def resume_factory(input_data, checkpoint_state=None):
results = detect_new_tool_results(input_data, checkpoint_state)
return ToolsExecuted(messages=tuple(results)) if results else None
@on(UserMessageReceived, ToolsExecuted)
async def call_llm(event, messages, log):
registered = log.latest(ToolsRegistered)
tools = build_langchain_tools(list(registered.tools)) if registered else []
llm = ChatOpenAI(model="gpt-4o-mini").bind_tools(tools) if tools else ChatOpenAI(model="gpt-4o-mini")
return LLMResponded(message=await llm.ainvoke(messages))
Handler-initiated frontend tools¶
For a backend-initiated tool call, for example a confirm dialog, a file picker or a deterministic prompt, return FrontendToolCallRequested(Interrupted) from a handler. The frontend result becomes a typed event on resume. ApprovalRequired(Interrupted) in examples/expense_approval.py uses the same machinery.
import json
from langgraph_events import IntegrationEvent, MessageEvent, on
from langgraph_events.agui import FrontendToolCallRequested, detect_new_tool_results
class OrderRequested(IntegrationEvent):
total: float
class OrderConfirmed(IntegrationEvent, MessageEvent):
messages: tuple = ()
class OrderPlaced(IntegrationEvent):
approved: bool
@on(OrderRequested)
def request_confirmation(event: OrderRequested) -> FrontendToolCallRequested:
return FrontendToolCallRequested(
name="confirm", # must match a useFrontendTool({ name: "confirm", ... }) registration
args={"prompt": f"Place an order for {event.total}?"},
)
def resume_factory(input_data, checkpoint_state=None):
results = detect_new_tool_results(input_data, checkpoint_state)
if not results:
return None
return OrderConfirmed(messages=tuple(results))
@on(OrderConfirmed)
def place(event: OrderConfirmed) -> OrderPlaced:
approved = bool(json.loads(event.messages[0].content).get("approved"))
return OrderPlaced(approved=approved)
- CopilotKit v1 (
useCopilotAction) usesMessagesSnapshot. v2 (useFrontendTool) needs the streamingToolCallStart/Args/End. Both coexist. CopilotKit reconciles bytool_call_id. - For an LLM-initiated tool call,
ToolCallStartEvent.parent_message_idcan differ from the finalMessagesSnapshotid. LangChain does not expose the finalAIMessage.iduntil the stream ends. - If a page refresh calls
connect()while the graph is paused onFrontendToolCallRequested, the adapter replays the triple with the storedtool_call_id. CopilotKituseFrontendToolis idempotent bytool_call_id. - Malformed tool-call traffic raises
ValueErrorat the source. The cases are an empty or whitespace-onlyFrontendToolCallRequested.name, an LLMtool_call_chunkwithoutindex, a first chunk of a streaming call without bothidandname, and an inboundrole: "tool"message without a non-emptytool_call_id. A continuation chunk can omitidandname.FrontendToolCallRequested.argsis JSON-serialized at emit time, so a non-serializable value raisesTypeError. A streaming-path error reaches the frontend as aRUN_ERRORevent with the diagnostic message.
Resume Helpers¶
detect_new_tool_results covers the frontend-tool-result path of resume. A result the client marks with error becomes a LangChain ToolMessage with status="error". In the other path, the frontend sends Command(resume=…) plus new chat messages. Three helpers cover that path:
extract_resume_input(input_data): decodeRunAgentInput.forwarded_props["command"]["resume"]. AG-UI 1.0 does not define this field. It stays for the clients that already send it. An AG-UI 1.0 client sendsRunAgentInput.resume, which the adapter answers itself, see Resume list. Every falsy value (0,"",[],{},False) means "no resume". For a "deny" signal, send{"approved": false}, not barefalse.agui_messages_to_langchain(messages, *, drop_invalid_tool_calls=False): convert AG-UI messages (UserMessage,AssistantMessage,SystemMessage,ToolMessage, multimodal content included, see Message field mapping) to LangChainBaseMessage.ReasoningMessageandDeveloperMessageare skipped atDEBUG.ActivityMessageand an unknown role raiseValueError. Withdrop_invalid_tool_calls=True, a tool call with unparseable JSON args is dropped with aWARNING. AToolMessage.errorbecomesstatus="error", and extra fields land underadditional_kwargs[AGUI_EXTRAS_KEY]. A content part with afilesource lands underadditional_kwargs[AGUI_HELD_PARTS_KEY]. Use it directly for custom merging, for example inseed_factory.detect_new_frontend_messages(input_data, checkpoint_state, *, reducer_name="messages", drop_invalid_tool_calls=True): read the stored messages fromcheckpoint_state["reducers"][reducer_name], then convert only the inbound messages whose id is not stored. Returns a tuple of the new messages only. A stored message wins over an inbound message with the same id, because AG-UI definesMessagesSnapshotas the messages that the server owns. If two inbound messages have the same id, the result holds the last copy, at the position of the first copy.
... # ToolsExecuted as in examples/conversation.py
from langgraph_events import IntegrationEvent, MessageEvent
from langgraph_events.agui import (
detect_new_frontend_messages,
detect_new_tool_results,
extract_resume_input,
)
# Define the resume event alongside your other events.
class UserResumed(IntegrationEvent, MessageEvent):
response: object # resume payload, any shape
messages: tuple = ()
def resume_factory(input_data, checkpoint_state=None):
tool_results = detect_new_tool_results(input_data, checkpoint_state)
if tool_results:
return ToolsExecuted(messages=tuple(tool_results)) # tool-result arm, as above
resume_input = extract_resume_input(input_data)
if resume_input is None:
return None
new_messages = detect_new_frontend_messages(input_data, checkpoint_state)
return UserResumed(response=resume_input, messages=new_messages)
WARNING: A stored resume event must carry only the new messages. The checkpoint stores each resume event twice, once as the event and once in Resumed.value, and each checkpoint load revives every stored event. A resume event that carries the full history grows the checkpoint by the number of resumes times the number of messages, and each turn loads more slowly. The message reducer already holds the full history. To read it in a resume_factory, read checkpoint_state["reducers"]["messages"]. A handler that reads event.messages as the whole conversation sends only the newest messages, for example to an LLM, with no error. Such a handler must inject the messages reducer instead, with a messages: list[BaseMessage] parameter. See message_reducer.
Typed Interrupt Payloads¶
InterruptedWithPayload[PayloadT] builds on Interrupted. InterruptedMapper emits the result of interrupt_payload() as CustomEvent(name="interrupted", value=...). No agui_dict() override is needed.
from typing import Literal, TypedDict
from langgraph_events import IntegrationEvent, on
from langgraph_events.agui import InterruptedWithPayload
class DraftWritten(IntegrationEvent):
draft: str
revision: int
class ReviewPayload(TypedDict):
kind: Literal["review"]
draft: str
revision: int
class ReviewInterrupted(InterruptedWithPayload[ReviewPayload]):
draft: str
revision: int
def interrupt_payload(self) -> ReviewPayload:
return {"kind": "review", "draft": self.draft, "revision": self.revision}
@on(DraftWritten)
def request_review(event: DraftWritten) -> ReviewInterrupted:
return ReviewInterrupted(draft=event.draft, revision=event.revision)
Plain Interrupted, with no payload, remains the right choice for a paused thread without a frontend.
Run config¶
The client is not trusted. Without a boundary, a client could set any run config key that the server did not set, such as recursion_limit or a test-only configurable key. The server config is the only source of run config. Pass it to stream() with config=, a LangGraph RunnableConfig. It can set configurable, recursion_limit, metadata, tags and run_name. A handler reads it from its RunnableConfig. The example builds on the Quick Start:
...
from langchain_core.runnables import RunnableConfig
@on(UserMessageReceived)
async def reply(event: UserMessageReceived, config: RunnableConfig) -> AssistantReplied:
locale = config["configurable"]["locale"]
return AssistantReplied(message=AIMessage(content=f"Reply in {locale}."))
graph = EventGraph([reply], checkpointer=MemorySaver(), reducers=[message_reducer()])
adapter = AGUIAdapter(graph, seed_factory=seed_factory)
@app.post("/api/copilotkit")
async def run(request: Request):
input_data = RunAgentInput.model_validate_json(await request.body())
stream = adapter.stream(
input_data,
config={"configurable": {"locale": "fr"}, "recursion_limit": 50},
)
return create_starlette_response(stream)
The adapter ignores the client run config in RunAgentInput.forwarded_props. This covers the keys langgraph_config and config, and a config at the top level of forwarded_props. Every part is ignored, for example configurable, recursion_limit, metadata, tags and run_name.
To accept a client configurable key, name it in client_configurable=. The adapter reads only the named keys from the client. It ignores every other part of the client run config:
stream = adapter.stream(
input_data,
config={"configurable": {"locale": "fr"}},
client_configurable={"theme"},
)
The adapter builds configurable in this order. A later source wins over an earlier source for the same key.
| Order | Source | Keys |
|---|---|---|
| 1 | Client forwarded_props config |
Only the keys that client_configurable= names |
| 2 | Server config= |
Every key |
| 3 | RunAgentInput.thread_id |
thread_id |
An empty RunAgentInput.thread_id raises ValueError when stream(), connect() or snapshot() is called. An empty run_id gets a new id, because a run id names no checkpoint.
A server configurable key thread_id, or a key with the prefix __lge_, raises ValueError when stream() is called. The same names in client_configurable= raise the same error. A client cannot choose a checkpoint, so checkpoint_id and checkpoint_ns in client_configurable= also raise ValueError. The server config= can set them. A str in client_configurable= raises TypeError, because the adapter would read each character as a key name.
A seed_factory or a resume_factory receives input_data, not the run config. A handler reads the run config from its RunnableConfig.
stream() also takes context=, the typed run context of a graph with EventGraph(context_schema=...). The adapter passes it to the run on a start and on a resume. A client cannot set it, and it is not checkpointed. Use it for a per-run server fact, such as the run language, in place of a configurable key. When the graph has a context schema, stream() without context= raises TypeError when it is called. See Run context.
stream = adapter.stream(input_data, context=RunFacts(language="fr"))
connect() also takes config=, because the checkpointer reads the checkpoint with the run config. For example, a checkpointer can route on a tenant key in configurable. Pass the same server config to stream() and to connect(). Without config=, connect() reads the checkpoint with RunAgentInput.thread_id only. It always ignores the client run config. The reserved keys raise ValueError when connect() is called.
Deadline and signal pauses¶
stream() accepts deadline=, an absolute time.monotonic() reference, and pause_on=, an object with is_set() such as an asyncio.Event. The router emits a RunPausedOnDeadline or a RunPausedOnSignal, both RunPaused subclasses, and the run finalises through the same RunFinishedEvent path as a normal completion. See Control Flow → Deadline pause and Control Flow → Pause on a signal for the semantics and the resume rule.
stream() also accepts stop_on=, an object with is_set(). When it is set, the run cancels its running async handler, stores CancelledOnSignal and ends the stream with RUN_FINISHED. That RUN_FINISHED carries the outcome RunFinishedCancelledOutcome. CancelledOnSignal still goes through the mapper chain, so an EventMapper can put it on the wire. Its default mapping emits no event, so on_unmapped= never warns or raises for it. When a sibling handler interrupts in the same round, the run stores no CancelledOnSignal, and RUN_FINISHED carries the interrupt outcome. A resume turn that a stop cuts before it applies its answers ends with RUN_FINISHED and the cancelled outcome, and the thread stays paused. This covers a stop already set at the call and a stop set during the replay of a paused handler. A resume stores a HandlerCutOnSignal for each handler that the stop cut before the interrupt. The stream does not yield it, so no mapper sees it. For the cleanup grace period, see Control Flow → Stop on a signal.
RunPaused does not implement AGUISerializable, so FallbackMapper skips it with a one-time warning. An app that wants to send a pause signal to the client registers its own mapper:
...
from langgraph_events import RunPaused
class PauseMapper:
def map(self, event: Event, ctx: MapperContext) -> list[BaseEvent] | None:
if not isinstance(event, RunPaused):
return None
return [
CustomEvent(
type=EventType.CUSTOM,
name="run.paused",
value={"elapsed_seconds": event.elapsed_seconds},
)
]
adapter = AGUIAdapter(graph, seed_factory=..., mappers=[PauseMapper()])
Run outcomes¶
AG-UI 1.0 reads the outcome of RUN_FINISHED. An absent outcome means that the run completed. The adapter sets the outcome as follows:
| The run ends | RUN_FINISHED.outcome |
|---|---|
| Completed | Absent |
| Paused on one or more interrupts | RunFinishedInterruptOutcome |
Paused on a FrontendToolCallRequested only |
Absent |
Stopped by stop_on= |
RunFinishedCancelledOutcome |
| A resume turn that a stop cuts before it applies its answers | RunFinishedCancelledOutcome |
The interrupt outcome holds one Interrupt for each open interrupt of the thread, in checkpoint task order:
Interrupt field |
Value |
|---|---|
id |
The LangGraph id of the interrupt. LangGraph derives it from the paused handler step. So a handler that pauses two times sends the same id for its second question. |
reason |
The class name of the interrupt value, for example ApprovalRequested |
metadata |
{"payload": ...}, with the value of the interrupted custom event. It is absent when the value has no AG-UI mapping. |
The adapter also sends the interrupted custom event, as before. A client that reads the custom event keeps working. A 1.0 client reads the outcome.
A FrontendToolCallRequested is a frontend tool call, not an interrupt. AG-UI 1.0 ends such a run as a success. The client answers the call with a tool message in the next input, and it finds the open call in the TOOL_CALL_START events. So the outcome does not name it. When a real interrupt is also open, the outcome names only the real interrupt.
A run on a paused thread with no answer runs no handler. It ends with the interrupt outcome again, so the client gets another chance to answer. A cancelled run waits for nothing, so a 1.0 client clears its pending interrupts. The next run then sends no answer and gets the interrupt outcome again.
A run can answer a thread that is not paused. A thread is paused while its checkpoint has a scheduled node or an open interrupt, as for astream_resume(). Examples are a double submit of one answer, two views that answer the same question, and a thread that abandon() closed. The rule is the same for a resume list and for the resume_factory:
- The adapter drops the answer with a
WARNINGthat names the thread. No handler gets the answer. - The adapter does not call the
seed_factory. - The client state of the run applies as on a fresh run. With no client state, the adapter replays the checkpoint and runs no handler.
- The run ends with
RUN_FINISHEDand no outcome.
The adapter does not call astream_resume() for such a run, so EventGraph(on_unresumable=...) does not apply to it. A paused handler that was renamed without previously= also leaves the thread not paused, so its answers are dropped in the same way.
A thread can have a scheduled node but no open interrupt, for example after a handler failed. The adapter resumes such a thread, as astream_resume() does. Client state cannot ride in that resume, so a run with client state ends with RUN_ERROR code pending_run_takes_no_client_state, and the thread keeps its pending run.
Resume list¶
An AG-UI 1.0 client answers in RunAgentInput.resume, one ResumeEntry for each interrupt, named by interrupt_id. When the list is not empty, the adapter answers from the list, and it does not call the resume_factory:
| Entry | Answer of the interrupt that the entry names |
|---|---|
status="resolved" |
The result of agui_answer(payload) on the interrupt value |
status="cancelled" |
Dismissed(interrupted=<the interrupt value>) |
An interrupt_id that names no open interrupt |
None. The adapter drops the entry with a WARNING. |
The adapter resumes every answered interrupt in one run. An open interrupt that no entry names stays open, and the run ends with the interrupt outcome for it. The answer to a covered interrupt is stored at once. Its handlers run in the run that answers the last open interrupt of the same round.
Before the graph runs, the adapter refuses the list with RUN_ERROR in two cases. The thread then keeps every question.
| Case | RUN_ERROR.code |
|---|---|
| Two entries name the same interrupt | duplicate_resume_entry |
A resolved entry names an interrupt without agui_answer(), or an entry names an interrupt that is not an Interrupted |
unanswerable_interrupt |
The resume_factory returns an event, and not exactly one FrontendToolCallRequested is open without an entry |
unanswerable_interrupt |
AG-UI 1.0 answers a frontend tool call with a tool message, not with a resume entry. So, beside a resume list, the adapter still calls the resume_factory. An event that it returns, for example from detect_new_tool_results, answers the one open FrontendToolCallRequested. A None adds no answer.
A raw langgraph.types.interrupt(value) with a value that is not an Interrupted is in the interrupt outcome, because it is open. A 1.0 client cannot answer it or dismiss it: each entry for it ends with unanswerable_interrupt. Pause with an Interrupted subclass for a question that a 1.0 client answers.
An interrupt reads its own answer. Implement agui_answer(), the AGUIAnswerable protocol, on each Interrupted subclass that a 1.0 client answers:
...
from typing import Any
from langgraph_events import IntegrationEvent, Interrupted
class ApprovalGiven(IntegrationEvent):
approved: bool
class ApprovalRequested(Interrupted):
draft: str
def agui_dict(self) -> dict[str, Any]:
return {"draft": self.draft}
def agui_answer(self, payload: Any) -> ApprovalGiven:
return ApprovalGiven(approved=bool(payload["approved"]))
AG-UI 1.0 lets a client dismiss an interrupt without an answer. What that means for the work is the choice of the app. Subscribe to Dismissed to decide it per question, for example @on(Dismissed, interrupted=ApprovalRequested). Without such a handler, the dismissal only closes the question. See Answers by interrupt id.
A stop_on= signal set during the replay of a paused handler cuts that replay. The cut question stays open with the same id, and its answer is not stored. A question whose replay ended before the stop keeps its answer. The RunAgentInput.state of the stopped turn is not stored. See Stop on a signal.
AG-UI 1.0 says that the run after a cancelled run is an ordinary run. On a thread that is still paused, the adapter runs no handler for such a run: it sends the interrupt outcome again, and the new input has no effect. The client must answer the open questions first. This deviates from the spec, because the thread keeps its questions.
AG-UI Spec Coverage¶
The adapter emits 12 of the 31 AG-UI event types. The other 19 need a custom mapper.
| Category | Count | Event Types |
|---|---|---|
| Built-in | 12 | RunStarted, RunFinished, RunError, TextMessageStart/Content/End, ToolCallStart/Args/End, StateSnapshot, MessagesSnapshot, Custom |
| Custom mapper | 19 | TextMessageChunk, ToolCallChunk, ToolCallResult, StepStarted/Finished, StateDelta, ActivitySnapshot/Delta, Raw, ReasoningStart/End, ReasoningEncryptedValue, ReasoningMessageStart/Content/End/Chunk, SubagentStarted/Finished/Error |