Add `event_stream_topic` to `TemporalDurability` to stream agent events via Workflow Streams
- Closes #6619
Under Temporal, an agent's events are produced in three different places — model events inside the model-request activity, tool events in workflow code, the result at the end of the run — and none of them can reach a process outside the workflow. Streaming a durable run to a frontend has therefore meant standing up a message queue alongside Temporal and wiring all three paths into it by hand.
Temporal 1.27 added Workflow Streams: a durable, offset-addressed channel that the workflow itself serves. This PR makes that the transport, so a durable run streams with no extra infrastructure:
from temporalio import workflow
with workflow.unsafe.imports_passed_through():
from pydantic_ai import Agent
from pydantic_ai.durable_exec.temporal import AgentEventStream, TemporalDurability
durability = TemporalDurability(event_stream_topic='agent-events')
agent = Agent('openai:gpt-5.6-sol', name='assistant', capabilities=[durability])
@workflow.defn
class AssistantWorkflow:
@workflow.init
def __init__(self, prompt: str) -> None:
self.events = AgentEventStream()
@workflow.run
async def run(self, prompt: str) -> str:
async with self.events:
result = await agent.run(prompt)
return result.output
A consumer holding only a workflow handle then watches the run as it happens:
handle = await client.start_workflow(
AssistantWorkflow.run, prompt, id=f'assistant-{uuid4()}', task_queue='my-task-queue'
)
async for event in durability.stream_agent_events(client, handle, output_type=str):
... # forward to the frontend over SSE
return await handle.result()
This is a durable run_stream_events() across the workflow boundary: the same AgentStreamEvents, in order, ending with the AgentRunResultEvent that carries the run's result. The async for ends on its own when the run does, so no separate "are we finished?" signal is needed.
The async with is what makes that possible rather than bookkeeping: a Workflow Stream is served by the workflow, so once the workflow returns its stream can no longer be read and anything unpolled is gone. The block holds the workflow open until a subscriber acknowledges the terminal event — sent automatically from inside stream_agent_events(), and bounded by drain_timeout (30s) so a run nobody is watching still finishes.
Driving a UI protocol
Because the stream ends the way run_stream_events() does, it is exactly what a UIAdapter consumes, on_complete included. An HTTP handler can serve a UI protocol straight off the topic, with the adapter's two jobs split across the boundary — the handler turns the request into a protocol stream, the workflow rebuilds the run arguments from the same body:
@workflow.defn
class ChatWorkflow:
@workflow.init
def __init__(self, body: bytes) -> None:
self.events = AgentEventStream()
@workflow.run
async def run(self, body: bytes) -> str:
adapter = VercelAIAdapter(agent=agent, run_input=VercelAIAdapter.build_run_input(body))
async with self.events:
result = await agent.run(
message_history=adapter.messages,
deferred_tool_results=adapter.deferred_tool_results,
conversation_id=adapter.conversation_id,
)
return result.output
async def handle_chat(request: Request) -> Response:
body = await request.body()
handle = await client.start_workflow(ChatWorkflow.run, body, id=..., task_queue='my-task-queue')
adapter = VercelAIAdapter(agent=agent, run_input=VercelAIAdapter.build_run_input(body))
events = durability.stream_agent_events(client, handle)
return adapter.streaming_response(adapter.transform_stream(events))
The workflow is the queue: starting it hands the run to a Temporal worker, and the HTTP request is only a subscriber to what that worker produces. It can go away without touching the run. Store the workflow ID with the conversation and a second endpoint reattaches a reconnecting client to a run it did not start:
async def get_chat(request: Request) -> Response:
# A Temporal handle carries no authorization of its own, so resolve the run
# through the conversation the caller owns rather than off the path.
chat = await load_chat(request.path_params['chat_id'], user=request.state.user)
handle = client.get_workflow_handle(chat.workflow_id)
adapter = VercelAIAdapter(agent=agent, run_input=chat.run_input)
events = durability.stream_agent_events(client, handle, output_type=str)
return adapter.streaming_response(adapter.transform_stream(events))
Subscribing from the default from_offset=0 replays every event the run has published so far and then continues live, so a refreshed tab rebuilds the whole message rather than picking up mid-sentence; a client that still holds what it received passes from_offset=offset + 1 and takes the rest as a continuation. The window is bounded by the AgentEventStream's drain_timeout: a run whose terminal event nobody acknowledges finishes after it, and its stream goes with it.
Choosing what to publish
Every published event stays in the workflow's state for the life of the run, and a model stream emits a PartDeltaEvent per token. Pass a WorkflowStreamTopic instead of a bare name to filter, or to tune how often the activity-side publisher flushes:
TemporalDurability(
event_stream_topic=WorkflowStreamTopic(
'agent-events',
events=lambda event: not isinstance(event, PartDeltaEvent), # skip per-token deltas
batch_interval=timedelta(milliseconds=100),
)
)
The terminal AgentRunResultEvent is always published, as it's what ends a subscription.
New public API
All in pydantic_ai.durable_exec.temporal, all opt-in:
TemporalDurability(event_stream_topic=...) | str | WorkflowStreamTopic | None, default None. Setting it enables streaming on its own, and is orthogonal to event_stream_handler: when both are set, the handler still sees every event. |
TemporalDurability.stream_agent_events(client, handle, *, output_type=Any, topic=None, from_offset=0, poll_cooldown=100ms) | Subscribe to the capability's own topic. Returns DurableAgentRunEvents. |
AgentEventStream(stream=None, *, prior_state=None, drain_timeout=30s) | Hosts the stream in the workflow. Async context manager; exposes stream (the underlying WorkflowStream, for your own topics or for continue_as_new()) and close(). |
WorkflowStreamTopic(name, events=None, batch_interval=100ms) | A topic plus what to publish to it. |
DurableAgentRunEvents | AsyncIterator[AgentStreamEvent | AgentRunResultEvent] with offset, result, aclose(); also an async context manager. |
workflow_stream_event_handler(topic, *, handler=None) | The activity-side publisher as a plain EventStreamHandler, for composing by hand. event_stream_topic is the preferred route — it also publishes the workflow-side events and the terminal event, which a handler alone cannot. |
stream_agent_events(client, handle, topic, *, output_type=Any, from_offset=0, poll_cooldown=100ms) | The module-level consumer, for a process that doesn't hold the capability. |
docs/api/durable_exec.md renders the module, so all of it is on the API reference automatically. The UI event streams overview also gains a "Running the agent elsewhere" section covering the remote-execution split in general terms and pointing here for the worked example.
What changes for existing users
The temporal extra now requires temporalio>=1.27.0 (up from >=1.24.0), the release that added Workflow Streams. Nothing else in the integration needs it; the floor is the price of the feature. The lowest CI legs install exactly 1.27.0 and pass.
Temporal users who don't set event_stream_topic see no change. Every publishing path is guarded on the topic being set, and there's a test asserting that a topic-only agent schedules no activities beyond the run's own.
One change lands outside the Temporal package, and it is a type-level split rather than a behavior change. BaseDurabilityCapability.for_agent() now returns AbstractCapability instead of Self, with the binding body moved to _bind_for_agent():
def for_agent(self, agent: AbstractAgent[AgentDepsT, Any]) -> AbstractCapability[AgentDepsT]:
return self._bind_for_agent(agent)
That is what lets TemporalDurability.for_agent() return itself paired with an internal companion capability. DBOS and Prefect return exactly what they returned before.
The companion exists because the terminal event is a promise — the run finished, here is its result — and TemporalDurability cannot keep it from its own after_run. Durability is the innermost capability and after_run runs innermost-first, so publishing there publishes a result that a capability registered alongside it may still rewrite; a subscriber's on_complete would render an answer the workflow never returns. So for_agent pairs the durability with a leaf in the outermost tier that does nothing but publish:
return CombinedCapability([_TerminalEventPublisher(bound), bound])
CombinedCapability flattens the pair into one ordering pass, so both halves stay leaves and find_capability(TemporalDurability) keeps resolving — the same split used elsewhere for a capability that must wrap outermost. Two regression tests cover it: one asserts the published result carries a later after_run's transformation (it fails if the companion is pinned innermost), the other that an after_run failure publishes no terminal event at all.
What this deliberately does not close. Two things still run after the companion, and neither is reachable from inside a capability: another outermost capability registered earlier, and the run lifecycle's own finalization — the pending-cancellation re-check and the run's finalizers. A run cancelled at that last step publishes a terminal event and then fails. That is the ordinary middleware caveat — somebody has to be the outer shell — so it is documented on stream_agent_events() and in the docs caveats rather than closed with new core surface: the workflow's return value stays the authoritative outcome.
Also private and behavior-preserving: BaseDurabilityCapability._model_stream_event_handler(), a seam separating "the handler that consumes the live model stream inside a model-request unit" from the run's event stream handler, so Temporal can wrap the former without wrapping the latter. It returns the latter for DBOS and Prefect, exactly as before.
Verification
24 tests in tests/durable_exec/temporal/test_workflow_streams.py, against a real Temporal dev server. Every workflow runs a model that calls a tool before answering, so both delivery paths — model events out of the activity, tool events from workflow code — are exercised in every test rather than only the text path.
- Publishing, fan-out, and the terminal event: the full event sequence pinned, a late consumer still getting the whole run, an unwatched run finishing anyway, a failed run ending without a result, the terminal event carrying the finalized result, and a topic-only agent scheduling no extra activities.
- Filtering across both paths, repeated runs on one stream with idempotent acknowledgments, offset resume, and replay safety through the
Replayer. - Guards and validation: a missing
AgentEventStream, a topic outside a workflow, a standalone activity, and the topic/cooldown validation. - The events drive a
VercelAIAdapterend to end over the workflow boundary, running the code the docs show:build_run_input(body)inside the workflow, the adapter's run arguments, and a reattaching consumer that holds only a workflow ID and the stored body. A frontend that drops two chunks in reconnects and gets those same chunks back, then the rest of the run andon_complete.
_event_stream.py, _durability.py and _base.py stay at 100% line and branch coverage.
Checklist
- Any AI generated code has been reviewed line-by-line by the human PR author, who stands by it.
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
- PR title is fit for the release changelog.