Open
Description
When using the agent.run_stream functionality and attempting to catch with an incorrect exception type during validation with validate_structured_result, the code doesn’t handle the error correctly.
Instead, it fails with a context detachment issue.
The exception doesn’t get caught, and fail.
I’m unsure whether this issue falls under PydanticAI’s responsibility or if it’s expected to be handled by the developer.
👉 However, I’m reporting it in case it can help identify a solution for the next developer.
(You can close this issue if needed.)
Here is a minimal example to reproduce the issue:
async with agent.run_stream(...):
async for message, last in result.stream_structured():
try:
profile = await result.validate_structured_result(
message,
allow_partial=not last,
)
except ValidationError: # <<< The error isn't caught here as expected (incorrect exception type)
continue
# Nothing more
The above code fails to handle errors properly and throws the following traceback:
Failed to detach context
Traceback (most recent call last):
File "..../pydantic_ai/result.py", line 302, in stream_structured
yield msg, False
GeneratorExit
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "..../opentelemetry/context/__init__.py", line 152, in detach
_RUNTIME_CONTEXT.detach(token)
File "..../opentelemetry/context/contextvars_context.py", line 50, in detach
self._current_context.reset(token) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: <Token var=<ContextVar name='current_context' default={} at xxx> at xxx> was created in a different Context