Skip to content

Commit 5408b86

Browse files
committed
fix: update agent context management in invoke_agent spans
1 parent 741e16f commit 5408b86

File tree

2 files changed

+9
-6
lines changed

2 files changed

+9
-6
lines changed

sentry_sdk/integrations/pydantic_ai/patches/agent_run.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import sentry_sdk
44

55
from ..spans import invoke_agent_span, update_invoke_agent_span
6-
from ..utils import _capture_exception, pop_agent
6+
from ..utils import _capture_exception, pop_agent, push_agent
77

88
from typing import TYPE_CHECKING
99
from pydantic_ai.agent import Agent # type: ignore
@@ -51,6 +51,10 @@ async def __aenter__(self):
5151
)
5252
self._span.__enter__()
5353

54+
# Push agent to contextvar stack after span is successfully created and entered
55+
# This ensures proper pairing with pop_agent() in __aexit__ even if exceptions occur
56+
push_agent(self.agent, self.is_streaming)
57+
5458
# Enter the original context manager
5559
result = await self.original_ctx_manager.__aenter__()
5660
self._result = result
@@ -107,6 +111,10 @@ async def wrapper(self, *args, **kwargs):
107111
with invoke_agent_span(
108112
user_prompt, self, model, model_settings, is_streaming
109113
) as span:
114+
# Push agent to contextvar stack after span is successfully created and entered
115+
# This ensures proper pairing with pop_agent() in finally even if exceptions occur
116+
push_agent(self, is_streaming)
117+
110118
try:
111119
result = await original_func(self, *args, **kwargs)
112120

sentry_sdk/integrations/pydantic_ai/spans/invoke_agent.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
_set_available_tools,
99
_set_model_data,
1010
_should_send_prompts,
11-
push_agent,
1211
)
1312

1413
from typing import TYPE_CHECKING
@@ -33,10 +32,6 @@ def invoke_agent_span(user_prompt, agent, model, model_settings, is_streaming=Fa
3332

3433
span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, "invoke_agent")
3534

36-
# Push agent to contextvar stack immediately after span creation
37-
# This ensures the agent is available in get_current_agent() before _set_model_data is called
38-
push_agent(agent, is_streaming)
39-
4035
_set_agent_data(span, agent)
4136
_set_model_data(span, model, model_settings)
4237
_set_available_tools(span, agent)

0 commit comments

Comments
 (0)