Serves Agent User Interaction (AG-UI) runs over HTTP (Effect's AgUiServer).
AG-UI clients POST a RunAgentInput as JSON and read the run's events as Server-Sent
Events, one JSON event per data: line. endpoint declares that binding as an
HttpApiEndpoint, so it can join an existing HttpApi, and layer_http mounts a
single run on the HttpRouter. agent serves the current LanguageModel with
server tools, frontend tools and several model rounds::
AgentRoute = ag_ui_server.layer_http(
path="/agent",
agent=ag_ui_server.agent(toolkit=Tools, system="Be brief", max_steps=5),
)Types#
| Type | Definition | Description |
|---|---|---|
Response | type Response = api_schema.WithHeadersValue[Stream[Event, Never], _CacheControl] | What an AG-UI endpoint's handler answers: the run's events, not cached. |
Request | type Request = HttpApiRequest[Any, Any, RunAgentInput, Any] |
Classes#
Functions#
endpoint#
endpoint(name, path) -> HttpApiEndpoint[None, None, RunAgentInput, Any, None, Response, Any, BadRequest]The POST endpoint declaration of AG-UI runs, to add to an existing HttpApi
and implement with handler or agent_handler.
The payload is a JSON RunAgentInput, so an invalid body is rejected with 400 before
the event stream opens, as is input an agent rejects. The success response is a
text/event-stream of AG-UI events sent as data: lines, with
Cache-Control: no-cache and a keepalive comment every 15 seconds.
| Parameter | Type | Description |
|---|---|---|
name | str | |
path | str |
Returns HttpApiEndpoint[None, None, RunAgentInput, Any, None, Response, Any, BadRequest]
def endpoint(
name: str, path: str
) -> HttpApiEndpoint[None, None, RunAgentInput, Any, None, Response, Any, BadRequest]:
"""The ``POST`` endpoint declaration of AG-UI runs, to add to an existing ``HttpApi``
and implement with ``handler`` or ``agent_handler``.
The payload is a JSON ``RunAgentInput``, so an invalid body is rejected with 400 before
the event stream opens, as is input an ``agent`` rejects. The success response is a
``text/event-stream`` of AG-UI events sent as ``data:`` lines, with
``Cache-Control: no-cache`` and a keepalive comment every 15 seconds."""
success = api_schema.WithHeaders(
api_schema.StreamSse(data=EVENT, keep_alive="15 seconds"), S.Struct(_CacheControl)
)
return cast(
"Any", ep.post(name, path, payload=RUN_AGENT_INPUT, success=success, error=BadRequest)
)handler#
handler[E, RR](run) -> Callable[[Request], Effect[Response, Never, RR]]An HttpApiBuilder handler for an endpoint from a function streaming the
events of one run.
The stream is wrapped with ag_ui.with_run_lifecycle, so the client receives
RUN_STARTED first and exactly one RUN_FINISHED or RUN_ERROR last. Failures
of the stream, events that cannot be encoded as JSON included, are logged and
reported, and reach the client as a RUN_ERROR without error details. The stream
runs with the services available to the handler.
| Parameter | Type | Description |
|---|---|---|
run | Callable[[RunAgentInput], Stream[Event, E, RR]] |
Returns Callable[[Request], Effect[Response, Never, RR]]
def handler[E, RR](
run: Callable[[RunAgentInput], Stream[Event, E, RR]],
) -> Callable[[Request], Effect[Response, Never, RR]]:
"""An ``HttpApiBuilder`` handler for an ``endpoint`` from a function streaming the
events of one run.
The stream is wrapped with ``ag_ui.with_run_lifecycle``, so the client receives
``RUN_STARTED`` first and exactly one ``RUN_FINISHED`` or ``RUN_ERROR`` last. Failures
of the stream, events that cannot be encoded as JSON included, are logged and
reported, and reach the client as a ``RUN_ERROR`` without error details. The stream
runs with the services available to the handler."""
def handle(request: Request) -> Effect[Response, Never, RR]:
payload = request.payload
return fx.context().map(
lambda context: _respond(payload, run(payload), cast("Context[RR]", context))
)
return handleagent_handler#
agent_handler[RR](agent) -> Effect[Callable[[Request], Effect[Response, BadRequest]], Never, RR]An HttpApiBuilder handler for an endpoint that serves agent; yield it
while building the builder.group implementing the endpoint.
The services the agent needs are captured when the handler is made. Each request
first runs the agent's validation, so a rejected input is answered with 400 before the
event stream opens; the events are then served as handler describes.
| Parameter | Type | Description |
|---|---|---|
agent | Agent[RR] |
Returns Effect[Callable[[Request], Effect[Response, BadRequest]], Never, RR]
def agent_handler[RR](
agent: Agent[RR],
) -> Effect[Callable[[Request], Effect[Response, BadRequest]], Never, RR]:
"""An ``HttpApiBuilder`` handler for an ``endpoint`` that serves ``agent``; yield it
while building the ``builder.group`` implementing the endpoint.
The services the agent needs are captured when the handler is made. Each request
first runs the agent's validation, so a rejected input is answered with 400 before the
event stream opens; the events are then served as ``handler`` describes."""
def make(context: Context[Any]) -> Callable[[Request], Effect[Response, BadRequest]]:
def handle(request: Request) -> Effect[Response, BadRequest]:
payload = request.payload
return agent.run(payload).map(lambda events: _respond(payload, events, context))
return handle
return fx.context().map(make)layer_http#
layer_http[RR](*, path: str, agent: Agent[RR], run: None = None) -> Layer[Never, Never, HttpRouter | RR]
layer_http[E, RR](*, path: str, run: Callable[[RunAgentInput], Stream[Event, E, RR]], agent: None = None) -> Layer[Never, Never, HttpRouter | RR]Serves AG-UI runs at path of the current HttpRouter, answering each with
agent or the events run streams (see handler).
Every field of the input comes from the client: convert it with ag_ui.to_prompt,
which drops client-supplied instructions by default.
| Parameter | Type | Description |
|---|---|---|
path | ||
agent | = None | |
run | = None |
@overload
def layer_http[RR](
*, path: str, agent: Agent[RR], run: None = None
) -> Layer[Never, Never, HttpRouter | RR]: ...
@overload
def layer_http[E, RR](
*, path: str, run: Callable[[RunAgentInput], Stream[Event, E, RR]], agent: None = None
) -> Layer[Never, Never, HttpRouter | RR]: ...
def layer_http(
*,
path: str,
agent: Agent[Any] | None = None,
run: Callable[[RunAgentInput], Stream[Event, Any, Any]] | None = None,
) -> Layer[Never, Never, Any]:
"""Serves AG-UI runs at ``path`` of the current ``HttpRouter``, answering each with
``agent`` or the events ``run`` streams (see ``handler``).
Every field of the input comes from the client: convert it with ``ag_ui.to_prompt``,
which drops client-supplied instructions by default."""
if agent is None and run is None:
raise TypeError("ag_ui_server.layer_http needs an agent or a run function")
group = HttpApiGroup.make("agUi").add(endpoint("run", path))
api = HttpApi.make("effect/ai/AgUiServer").add(group)
served = agent if agent is not None else _from_run(cast("Any", run))
run_endpoint = group.endpoints["run"]
handlers = builder.group(
api,
group,
lambda empty: agent_handler(served).map(empty.handle(run_endpoint)),
)
return cast("Any", builder.layer(api)).pipe(L.provide(handlers))agent#
agent[N: LiteralString, RP, HE](*, toolkit: K.Toolkit[N, RP, HE, Never], system: str | None = None, max_steps: int = 1) -> Agent[lm.LanguageModel | K.Handlers[N]]
agent[N: LiteralString, RP, HE, RR = Never](*, toolkit: K.Toolkit[N, RP, HE, RunInput | RR], system: str | None = None, max_steps: int = 1) -> Agent[lm.LanguageModel | K.Handlers[N] | RR]An AG-UI agent answering each run with the current LanguageModel and
toolkit.
- The prompt is
system, if given, then the run's conversation asag_ui.to_promptconverts it, which drops client-supplied instructions. - The model is offered the server toolkit and each of the run's tools as a client-executed tool. A run whose tools reuse a server tool's name is rejected with 400.
- Rounds follow
Chat.stream_textwithmax_steps, so server tool results go back to the model until a round needs no tools,max_stepsrounds have run, or a tool call is left for the application. - The run finishes with the token usage summed over every round. Frontend tool calls
left for the application are listed as
pendingToolCallIds, and the application answers them with tool messages in its next run. - Server tool handlers can read the run's input from
RunInput.
| Parameter | Type | Description |
|---|---|---|
toolkit | ||
system | = None | |
max_steps | = 1 |
@overload
def agent[N: LiteralString, RP, HE](
*,
toolkit: K.Toolkit[N, RP, HE, Never],
system: str | None = None,
max_steps: int = 1,
) -> Agent[lm.LanguageModel | K.Handlers[N]]: ...
@overload
def agent[N: LiteralString, RP, HE, RR = Never](
*,
toolkit: K.Toolkit[N, RP, HE, RunInput | RR],
system: str | None = None,
max_steps: int = 1,
) -> Agent[lm.LanguageModel | K.Handlers[N] | RR]: ...
def agent(
*,
toolkit: K.Toolkit[Any, Any, Any, Any],
system: str | None = None,
max_steps: int = 1,
) -> Agent[Any]:
"""An AG-UI agent answering each run with the current ``LanguageModel`` and
``toolkit``.
- The prompt is ``system``, if given, then the run's conversation as
``ag_ui.to_prompt`` converts it, which drops client-supplied instructions.
- The model is offered the server toolkit and each of the run's tools as a
client-executed tool. A run whose tools reuse a server tool's name is rejected with
400.
- Rounds follow ``Chat.stream_text`` with ``max_steps``, so server tool results go back
to the model until a round needs no tools, ``max_steps`` rounds have run, or a tool
call is left for the application.
- The run finishes with the token usage summed over every round. Frontend tool calls
left for the application are listed as ``pendingToolCallIds``, and the application
answers them with tool messages in its next run.
- Server tool handlers can read the run's input from ``RunInput``."""
server_tools = toolkit.tools
def run(input: RunAgentInput) -> Effect[Stream[Event, object, Any], BadRequest]:
if any(tool["name"] in server_tools for tool in input["tools"]):
return fx.fail(BadRequest())
frontend = [
T.dynamic(
cast("Any", tool["name"]),
description=tool["description"],
parameters=cast(
"JsonSchema", tool.get("parameters", {"type": "object", "properties": {}})
),
execution="client",
)
for tool in input["tools"]
]
merged = K.merge(toolkit, K.make(*frontend))
conversation = ag_ui.to_prompt(input)
prompt = conversation if system is None else conversation.prepend_system(system)
summary = _RunSummary(input, merged.tools)
def events(chat: C.Service) -> Stream[Event, object, Any]:
parts = cast(
"Stream[R.AnyPart, object, Any]",
chat.stream_text(prompt, toolkit=merged, max_steps=max_steps),
)
ids = fx.service_option(IdGenerator).map(
lambda found: found.value if found is not None else default_id_generator
)
return (
parts.tap(lambda part: fx.sync(lambda: summary.observe(part)))
.pipe(ag_ui.from_stream_parts)
.concat(StreamC.sync(summary.finished))
.pipe(StreamContext.provide_service(RunInput, input))
.pipe(StreamContext.provide_service_effect(IdGenerator, ids))
)
return C.empty.map(events)
return Agent(run)