diff --git a/docs/agents.md b/docs/agents.md index e3fd626443..0b454155be 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -675,7 +675,7 @@ example below uses detached application context and stages its save after the ru ```python @server.a2a_session(endpoint="support", description="Airline support.") -async def support(ctx: A2ASessionContext) -> RunResult[Refund]: +async def support(ctx: A2ASessionContext) -> AsyncIterator[str]: app = await make_airline_context(ctx) await ctx.store.load_context(app) @@ -684,19 +684,20 @@ async def support(ctx: A2ASessionContext) -> RunResult[Refund]: message_history=ctx.message_history, context=app, ) as stream: - await ctx.stream(stream.stream_text(delta=True)) - result = await stream.result() + async for delta in stream.stream_text(delta=True): + yield delta await ctx.store.save_context(app) - return result ``` `run_stream` hands delivery to its consumer. It does not also automatically -forward those same text occurrences through the managed endpoint. In this -example, `ctx.stream(...)` performs incremental delivery. Returning the full -result finalizes the existing answer artifact or input-required status; it does -not send the streamed text a second time. A direct `agent.run()` can retain the -managed endpoint's automatic forwarding behavior. +forward those same text occurrences through the managed endpoint. Here each +yielded delta is delivered incrementally, and the run's `RunResult` is the +outcome: it finalizes the existing answer artifact or input-required status +without sending the streamed text a second time. The lower-level form forwards +with `await ctx.stream(stream.stream_text(delta=True))` and returns +`await stream.result()` ([handler contract](server.md)). A direct `agent.run()` +can retain the managed endpoint's automatic forwarding behavior. A failed or cancelled run can leave already delivered text visible; that text is not an accepted typed result. Stream delivery does not change the selected diff --git a/docs/server.md b/docs/server.md index 50311128e0..64dbe8f7f1 100644 --- a/docs/server.md +++ b/docs/server.md @@ -39,14 +39,35 @@ no artifact. The handler saves application fields explicitly before returning either result. Called once per turn with the agent's partition already loaded; a batched burst -is one call. The return value is the answer; the framework commits the partition -and delivers it. A handler that raises ends the task `failed`. +is one call. The return value is the answer, or the handler is an async generator +that streams it (below); the framework commits the partition and delivers it. A handler that raises ends the task `failed`. -For explicit streaming, consume `agent.run_stream(...)`, forward text through -`ctx.stream(...)`, and return its complete `RunResult` after saving context. -The returned result finalizes the same answer rather than delivering the text -again. See [managed streaming endpoints](agents.md#managed-endpoints-and-persistence) -for the complete entrypoint and cancellation contract. +A handler that streams its answer is an async generator (`AsyncIterator[str]`) +yielding the text as it is produced: + +```python +@server.a2a_session(endpoint="travel-desk", description="Plans trips.") +async def chat(ctx: A2ASessionContext) -> AsyncIterator[str]: + trip = Trip(airline=AirlineClient()) + await ctx.store.load_context(trip) + async with travel_desk_agent.run_stream( + ctx.message, context=trip, message_history=ctx.message_history, + ) as s: + async for delta in s.stream_text(delta=True): + yield delta + await ctx.store.save_context(trip) +``` + +- Each yielded `str` is delivered as `ctx.stream(...)` delivers it; a non-`str` fails the + task with a `TypeError`. +- The outcome is the `RunResult` of the last `run_stream` the handler opened for this + request (completed with its typed output, or input-required); it finalizes the streamed + answer without sending the text again. A run that fails raises in the handler. +- A generator that opened no `run_stream` completes with the joined yielded text. + +`ctx.stream(source)` is the lower-level form: forward the run's text through it and return +`await s.result()`. See [managed streaming endpoints](agents.md#managed-endpoints-and-persistence) +for the persistence and cancellation contract. A handler using `await agent.run(...)` can use automatic managed forwarding. `run_stream(...)` instead gives its consumer control of delivery, so the same diff --git a/examples/web-chat/agent.py b/examples/web-chat/agent.py index 2764d4e18b..d527de4665 100644 --- a/examples/web-chat/agent.py +++ b/examples/web-chat/agent.py @@ -1,6 +1,8 @@ +from collections.abc import AsyncIterator + from dotenv import load_dotenv -from livekit.agents import Agent, AgentServer, RunResult, cli, inference +from livekit.agents import Agent, AgentServer, cli, inference from livekit.agents.a2a import A2ASessionContext from livekit.agents.storage import AgentDBStorage @@ -16,13 +18,12 @@ server = AgentServer(storage=AgentDBStorage(), agent_name="web-chat") # the text door: one turn per message, with the thread's history; the answer's text streams -# to the caller as the model writes it, and the returned result finalizes it +# to the caller as the model writes it, and the run's result finalizes it @server.a2a_session(endpoint="chat", description="A general chat assistant.") -async def chat(ctx: A2ASessionContext) -> RunResult[str]: +async def chat(ctx: A2ASessionContext) -> AsyncIterator[str]: async with assistant.run_stream(ctx.message, message_history=ctx.message_history) as stream: - await ctx.stream(stream.stream_text(delta=True)) - result = await stream.result() - return result + async for delta in stream.stream_text(delta=True): + yield delta if __name__ == "__main__": diff --git a/examples/web-chat/web.py b/examples/web-chat/web.py index b7baf3d00e..2408e7dbba 100644 --- a/examples/web-chat/web.py +++ b/examples/web-chat/web.py @@ -73,7 +73,8 @@ async def thread_messages(request: Request) -> Response: scope, thread = scope_of(request), request.path_params["thread"] if scope is None or not await owns(scope, thread): return Response(status_code=403) - messages, after = [], None + messages: list[dict[str, str]] = [] + after: str | None = None while after != "": page = await Thread(storage, thread).list_items(after=after) for entry in page.items: diff --git a/python/livekit-agents/livekit/agents/storage/session.py b/python/livekit-agents/livekit/agents/storage/session.py index c3143ea3f0..d857b2c73e 100644 --- a/python/livekit-agents/livekit/agents/storage/session.py +++ b/python/livekit-agents/livekit/agents/storage/session.py @@ -1,6 +1,8 @@ from __future__ import annotations -from collections.abc import AsyncIterable, Awaitable, Callable +import inspect +from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable +from contextlib import aclosing from typing import cast from .. import _core @@ -14,7 +16,7 @@ from ..voice.agent_run import RunHooks, reset_run_hooks, set_run_hooks from . import StorageError, Thread from .context import ContextStore -_Handler = Callable[["A2ASessionContext"], Awaitable[object]] +_Handler = Callable[["A2ASessionContext"], Awaitable[object] | AsyncIterator[str]] class A2ASessionContext: @@ -112,7 +114,14 @@ class _TurnHost: token = set_run_hooks(hooks) try: - output = await self._handler(context) + call = self._handler(context) + if inspect.isasyncgen(call): + async with aclosing(call): + text = await context.stream(_texts(call)) + # the outcome is the last run the handler streamed, else the text it yielded + output: object = results[-1] if results else text + else: + output = await cast(Awaitable[object], call) except StorageError: raise except Exception as e: @@ -163,6 +172,15 @@ class _TurnHost: ) +async def _texts(handler: AsyncIterator[object]) -> AsyncIterator[str]: + async for chunk in handler: + if not isinstance(chunk, str): + raise TypeError( + f"an a2a_session handler yields the answer's text as str, not {type(chunk).__name__}" + ) + yield chunk + + __all__ = [ "A2ASessionContext", ] diff --git a/tests/host/test_callbacks.py b/tests/host/test_callbacks.py index 62f26daa13..f05674ce0d 100644 --- a/tests/host/test_callbacks.py +++ b/tests/host/test_callbacks.py @@ -5,7 +5,7 @@ from __future__ import annotations import asyncio import json -from collections.abc import AsyncIterable, Callable +from collections.abc import AsyncIterable, AsyncIterator, Callable from contextlib import AbstractAsyncContextManager from dataclasses import dataclass from typing import Annotated @@ -372,6 +372,120 @@ async def test_a_handlers_typed_output_is_the_tasks_data_artifact( assert task["artifacts"][0]["parts"][0]["data"] == {"reservation": "R42"} +async def stream_turn(door: httpx.AsyncClient, text: str) -> list[dict[str, object]]: + """The events of an A2A ``message/stream`` of ``text``.""" + body = message_send(text) | {"method": "message/stream"} + async with door.stream("POST", "/v1", json=body) as response: + return [ + json.loads(line.removeprefix("data:"))["result"] + async for line in response.aiter_lines() + if line.startswith("data:") + ] + + +def streamed_text(events: list[dict[str, object]]) -> list[str]: + """Every text part the task's artifact updates carried, in order.""" + return [ + part["text"] + for event in events + if "artifactUpdate" in event + for part in event["artifactUpdate"]["artifact"]["parts"] # type: ignore[index] + if "text" in part + ] + + +def final_status(events: list[dict[str, object]]) -> dict[str, object]: + return events[-1]["statusUpdate"]["status"] # type: ignore[index, no-any-return] + + +async def test_a_generator_handler_streams_its_run_and_completes_with_its_typed_output( + a2a_door: Callable[[A2AHandler], AbstractAsyncContextManager[httpx.AsyncClient]], +) -> None: + """Each yielded delta reaches the client as it is produced, once, and the run the handler + streamed is the outcome: its typed output is the task's data artifact.""" + + class Booking(BaseModel): + nights: int + + model = FakeLLM([["Booking ", "two nights.", tool_call("final_result", nights=2)]]) + agent = Agent(instructions="Help.", llm=model, output_type=Booking) + + async def handler(ctx: A2ASessionContext) -> AsyncIterator[str]: + async with agent.run_stream(ctx.message) as stream: + async for delta in stream.stream_text(delta=True): + yield delta + + async with a2a_door(handler) as door: + events = await stream_turn(door, "book") + + assert streamed_text(events) == ["Booking ", "two nights."] + assert final_status(events)["state"] == "TASK_STATE_COMPLETED" + data = [ + part["data"] + for event in events + if "artifactUpdate" in event + for part in event["artifactUpdate"]["artifact"]["parts"] # type: ignore[index] + if "data" in part + ] + assert data == [{"nights": 2}] + + +async def test_a_generator_handlers_run_asking_for_input_leaves_the_task_input_required( + a2a_door: Callable[[A2AHandler], AbstractAsyncContextManager[httpx.AsyncClient]], +) -> None: + """A run the handler streamed that asks a question ends the task input-required with it.""" + agent = Agent(instructions="Help.", llm=FakeLLM([tool_call("book")])) + + @agent.tool + async def book(ctx: RunContext) -> InputRequired: + """Book.""" + return InputRequired("Which date?", verbatim=True) + + async def handler(ctx: A2ASessionContext) -> AsyncIterator[str]: + async with agent.run_stream(ctx.message) as stream: + async for delta in stream.stream_text(delta=True): + yield delta + + async with a2a_door(handler) as door: + events = await stream_turn(door, "book") + + status = final_status(events) + assert status["state"] == "TASK_STATE_INPUT_REQUIRED" + assert status["message"]["parts"] == [{"text": "Which date?"}] # type: ignore[index] + + +async def test_a_generator_handler_without_a_run_completes_with_the_text_it_yielded( + a2a_door: Callable[[A2AHandler], AbstractAsyncContextManager[httpx.AsyncClient]], +) -> None: + """With no run to settle it, the answer is the yielded text, streamed once and joined.""" + + async def handler(ctx: A2ASessionContext) -> AsyncIterator[str]: + yield "Open " + yield "until 9." + + async with a2a_door(handler) as door: + events = await stream_turn(door, "hours?") + + assert streamed_text(events) == ["Open ", "until 9."] + status = final_status(events) + assert status["state"] == "TASK_STATE_COMPLETED" + assert status["message"]["parts"] == [{"text": "Open until 9."}] # type: ignore[index] + + +async def test_a_generator_handler_yielding_a_non_str_fails_the_task( + a2a_door: Callable[[A2AHandler], AbstractAsyncContextManager[httpx.AsyncClient]], +) -> None: + """A yielded value that is not text fails the task, naming the type.""" + + async def handler(ctx: A2ASessionContext) -> AsyncIterator[object]: + yield {"hours": 9} + + async with a2a_door(handler) as door: # type: ignore[arg-type] + events = await stream_turn(door, "hours?") + + assert final_status(events)["state"] == "TASK_STATE_FAILED" + + # -- a call's hooks, nodes and speech callbacks