Skip to content

AnyIO worker exception due to sync history processor function in TemporalAgent #3607

@M0dEx

Description

@M0dEx

Initial Checks

Description

When a sync history processor function is used in conjunction with a TemporalAgent instance, the function is executed within an AnyIO loop used by PydanticAI, which causes issues due to the event loop being overridden by Temporal (the history processor is executed within the workflow).

This results in an exception being thrown from the worker thread, due to the Temporal SDK not implementing is_closed:

<redacted>  | Exception in thread AnyIO worker thread:
<redacted>  | Traceback (most recent call last):
<redacted>  |   File "/<redacted>/cpython-3.13.9-linux-aarch64-gnu/lib/python3.13/threading.py", line 1043, in _bootstrap_inner
<redacted>  |     self.run()
<redacted>  |     ~~~~~~~~^^
<redacted>  |   File "/<redacted>/site-packages/anyio/_backends/_asyncio.py", line 973, in run
<redacted>  |     if not self.loop.is_closed():
<redacted>  |            ~~~~~~~~~~~~~~~~~~~^^
<redacted>  |   File "/<redacted>/cpython-3.13.9-linux-aarch64-gnu/lib/python3.13/asyncio/events.py", line 251, in is_closed
<redacted>  |     raise NotImplementedError
<redacted>  | NotImplementedError

The workaround is to make the history processor async, which makes it be executed within the workflow, but that can potentially cause issue if the history processor did any non-deterministic actions, as Temporal might raise an error then.

Example Code

def dummy_history_processor(messages: list[ModelMessage]) -> list[ModelMessage]:
    return messages[1:] # some dummy processing


MY_AGENT = TemporalAgent(
    Agent(
        ...
        history_processors=[dummy_history_processor],
    )
)

Python, Pydantic AI & LLM client version

Python: CPython 3.13.9
Pydantic: 1.23.0
LLM client: `anthropic 0.72.0`

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions