GitHub

API reference for ag_ui.

Converts between pyfect.ai values and the Agent User Interaction (AG-UI) protocol (Effect's AgUi).

An AG-UI run starts from a RunAgentInput and answers with a stream of events. to_prompt turns the input's conversation into a Prompt, from_stream_parts turns the parts language_model.stream_text streams into AG-UI events, and with_run_lifecycle wraps an event stream in the run lifecycle AG-UI clients expect. It performs no I/O; ag_ui_server serves runs over HTTP::

def run(input: ag_ui_schema.RunAgentInput):
    return (
        language_model.stream_text(ag_ui.to_prompt(input))
        .pipe(ag_ui.from_stream_parts)
        .pipe(ag_ui.with_run_lifecycle(input))
    )

Classes

Functions

to_prompt

to_prompt(input, *, trust_client_instructions=False) -> P.Prompt

The conversation of an AG-UI run input as a Prompt.

  • User and assistant messages keep their text. Assistant tool calls become tool-call parts with their JSON arguments parsed.
  • Each tool message becomes a tool message with one tool-result part, named after the latest preceding assistant tool call with its id, since providers may reuse call ids across turns. Content that is valid JSON is parsed. A message with an error is a failed result carrying the error text, as is one carrying the failure metadata from_stream_parts emits (with its content).
  • User image, audio, video and document parts with inline data or a valid URL become file parts.
  • Activity and reasoning messages, provider file handles and tool messages that answer no preceding tool call are dropped.

The whole conversation comes from the client, so system and developer messages and the input's context are dropped by default: a browser cannot replace the server's instructions. With trust_client_instructions they are kept: system and developer messages become system messages in place, and context a leading system message.

ParameterTypeDescription
inputRunAgentInput
trust_client_instructionsbool = False

Returns P.Prompt

def to_prompt(input: RunAgentInput, *, trust_client_instructions: bool = False) -> P.Prompt:
    """The conversation of an AG-UI run input as a ``Prompt``.

    - User and assistant messages keep their text. Assistant tool calls become tool-call
      parts with their JSON arguments parsed.
    - Each tool message becomes a tool message with one tool-result part, named after the
      latest preceding assistant tool call with its id, since providers may reuse call ids
      across turns. Content that is valid JSON is parsed. A message with an ``error`` is a
      failed result carrying the error text, as is one carrying the failure metadata
      ``from_stream_parts`` emits (with its content).
    - User image, audio, video and document parts with inline data or a valid URL become
      file parts.
    - Activity and reasoning messages, provider file handles and tool messages that answer
      no preceding tool call are dropped.

    The whole conversation comes from the client, so ``system`` and ``developer`` messages
    and the input's ``context`` are dropped by default: a browser cannot replace the
    server's instructions. With ``trust_client_instructions`` they are kept: ``system`` and
    ``developer`` messages become system messages in place, and ``context`` a leading
    system message."""
    # Filled as messages are consumed, so each result is named after the latest preceding
    # call with its id.
    tool_names: dict[str, str] = {}
    messages: list[Mapping[str, object]] = []
    contexts = input["context"]
    if trust_client_instructions and contexts:
        text = "\n\n".join(f"{context['description']}:\n{context['value']}" for context in contexts)
        messages.append({"role": "system", "content": text})
    for message in input["messages"]:
        match message["role"]:
            case "system" | "developer":
                if trust_client_instructions:
                    messages.append({"role": "system", "content": message["content"]})
            case "user":
                content = message["content"]
                messages.append(
                    {
                        "role": "user",
                        "content": content if isinstance(content, str) else _user_parts(content),
                    }
                )
            case "assistant":
                parts: list[Mapping[str, object]] = []
                text = message.get("content")
                if text:
                    parts.append({"type": "text", "text": text})
                for call in message.get("toolCalls", []):
                    function = call["function"]
                    tool_names[call["id"]] = function["name"]
                    parts.append(
                        {
                            "type": "tool-call",
                            "id": call["id"],
                            "name": function["name"],
                            "params": _parse_json(function["arguments"]),
                        }
                    )
                if parts:
                    messages.append({"role": "assistant", "content": parts})
            case "tool":
                name = tool_names.get(message["toolCallId"])
                if name is None:
                    continue
                error = message.get("error")
                content = message["content"]
                result: object = (
                    error
                    if error is not None
                    else _parse_json(content)
                    if isinstance(content, str)
                    else content
                )
                failed = error is not None or _has_failure_marker(message.get("metadata"))
                part = {
                    "type": "tool-result",
                    "id": message["toolCallId"],
                    "name": name,
                    "isFailure": failed,
                    "result": result,
                }
                messages.append({"role": "tool", "content": [part]})
            case "activity" | "reasoning":
                pass
    return P.make(messages)

from_stream_parts

from_stream_parts[E, RR](self) -> Stream[Event, E, RR | IdGenerator]

The parts language_model.stream_text streams as AG-UI events.

  • Each model round becomes a step named step-1, step-2 and so on; the round's finish part closes the step.
  • Text parts become TEXT_MESSAGE_* events from the assistant role, and reasoning parts a reasoning span holding one reasoning message.
  • Streamed tool parameters become TOOL_CALL_START, TOOL_CALL_ARGS and TOOL_CALL_END. A tool call that arrives without streamed parameters becomes the same sequence with its parameters as one JSON fragment. Tool calls name the step's latest text message as their parent.
  • Final tool results become TOOL_CALL_RESULT events with a fresh message id from IdGenerator; failed ones carry {"effect/ai": {"isFailure": True}} as metadata.
  • An error part is logged and becomes a RUN_ERROR with a generic message.
  • Preliminary tool results, approval requests, files, sources and response metadata are dropped.

Failures of the input stream are kept: with_run_lifecycle opens and closes the run and reports failures to the client.

ParameterTypeDescription
selfStream[R.AnyPart, E, RR]

Returns Stream[Event, E, RR | IdGenerator]

def from_stream_parts[E, RR](
    self: Stream[R.AnyPart, E, RR],
) -> Stream[Event, E, RR | IdGenerator]:
    """The parts ``language_model.stream_text`` streams as AG-UI events.

    - Each model round becomes a step named ``step-1``, ``step-2`` and so on; the round's
      ``finish`` part closes the step.
    - Text parts become ``TEXT_MESSAGE_*`` events from the ``assistant`` role, and
      reasoning parts a reasoning span holding one reasoning message.
    - Streamed tool parameters become ``TOOL_CALL_START``, ``TOOL_CALL_ARGS`` and
      ``TOOL_CALL_END``. A tool call that arrives without streamed parameters becomes the
      same sequence with its parameters as one JSON fragment. Tool calls name the step's
      latest text message as their parent.
    - Final tool results become ``TOOL_CALL_RESULT`` events with a fresh message id from
      ``IdGenerator``; failed ones carry ``{"effect/ai": {"isFailure": True}}`` as
      metadata.
    - An ``error`` part is logged and becomes a ``RUN_ERROR`` with a generic message.
    - Preliminary tool results, approval requests, files, sources and response metadata
      are dropped.

    Failures of the input stream are kept: ``with_run_lifecycle`` opens and closes the
    run and reports failures to the client."""

    def convert(ids: IdService) -> Stream[Event, E, RR]:
        state = _PartsToEvents(ids)
        return self.map_effect(state.events).flatten_iterable()

    return StreamC.unwrap(IdGenerator().map(convert))

with_run_lifecycle

with_run_lifecycle(run) -> _WithRunLifecycle

Wraps a stream of AG-UI events in the lifecycle of one run (.pipe it), so clients always see a well-formed run, with from_stream_parts or any hand-written event stream.

  • RUN_STARTED comes first, with the run's ids and the protocol version; RUN_STARTED events from the input stream are dropped.
  • When the input stream ends, any text message, tool call, reasoning span, step or subagent it left open is closed, most recently opened first, and RUN_FINISHED follows. Closing events keep the subagentRunId of the event they close, steps are matched by name within each subagent, and a subagent left running ends with a SUBAGENT_ERROR.
  • A RUN_FINISHED from the input stream ends the run, after closing anything left open, so a stream can report its own outcome. A RUN_ERROR from it also ends the run.
  • When the input stream fails, the cause is logged and reported, and the run ends with a RUN_ERROR whose message carries no error details. Interruptions are not converted.

To send a specific error to the client, emit a RUN_ERROR from the input stream instead of failing it.

ParameterTypeDescription
runRunIds

Returns _WithRunLifecycle

def with_run_lifecycle(run: RunIds) -> _WithRunLifecycle:
    """Wraps a stream of AG-UI events in the lifecycle of one run (``.pipe`` it), so
    clients always see a well-formed run, with ``from_stream_parts`` or any hand-written
    event stream.

    - ``RUN_STARTED`` comes first, with the run's ids and the protocol version;
      ``RUN_STARTED`` events from the input stream are dropped.
    - When the input stream ends, any text message, tool call, reasoning span, step or
      subagent it left open is closed, most recently opened first, and ``RUN_FINISHED``
      follows. Closing events keep the ``subagentRunId`` of the event they close, steps
      are matched by name within each subagent, and a subagent left running ends with a
      ``SUBAGENT_ERROR``.
    - A ``RUN_FINISHED`` from the input stream ends the run, after closing anything left
      open, so a stream can report its own outcome. A ``RUN_ERROR`` from it also ends the
      run.
    - When the input stream fails, the cause is logged and reported, and the run ends
      with a ``RUN_ERROR`` whose message carries no error details. Interruptions are not
      converted.

    To send a specific error to the client, emit a ``RUN_ERROR`` from the input stream
    instead of failing it."""
    return _WithRunLifecycle(run["threadId"], run["runId"])