Let tool functions yield custom events

Closed
DO
5mo ago
+1479-580

Example based on https://ai.pydantic.dev/ag-ui/#events, using ag_ui.core.CustomEvent and ToolReturn:

@agent.tool_plain
async def yield_custom() -> AsyncIterator[CustomEvent | Return[str]]:
    yield CustomEvent(
        type=EventType.CUSTOM,
        name='custom_event1',
        value={'key1': 'value1'},
    )
    yield CustomEvent(
        type=EventType.CUSTOM,
        name='custom_event2',
        value={'key2': 'value2'},
    )
    yield Return('Done')

If the yielded item is a pydantic_ai.messages.CustomEvent, it'll show up in the event streams as-is. If it's ToolReturn, it's the tool return value. If it's Anything else, it'll be wrapped in a pydantic_ai.messages.CustomEvent.

AG-UI integration automatically forwards ag_ui.core.CustomEvent payloads to the frontend.


To do:

  • Vercel AI data-* custom chunk type https://github.com/pydantic/pydantic-ai/pull/2923
  • Handle exceptions
  • Tag custom events with tool call ID.
  • Output function? Like when used for agent handoff, would want to be able to stream events
    • Native, prompted output mode
  • Some cleanup (see todo comments)
  • Generic CustomEventDataT param on Agent etc. Should default be Never or object?
  • Require stream=True argument on tool decorator
  • Temporal
    • Get it to work
    • Make OTel span hierarchy nice again
  • DBOS
  • Prefect
  • Docs