Skip to content

Commit c7b7ae7

Browse files
committed
fix: reshuffling where the _invoke_agent_span_stack context variable is set
1 parent 0224373 commit c7b7ae7

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

sentry_sdk/integrations/pydantic_ai/patches/agent_run.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,14 @@ async def __aenter__(self):
4343

4444
# Create invoke_agent span (will be closed in __aexit__)
4545
self._span = invoke_agent_span(
46-
self.user_prompt, self.agent, self.model, self.model_settings
46+
self.user_prompt,
47+
self.agent,
48+
self.model,
49+
self.model_settings,
50+
self.is_streaming,
4751
)
4852
self._span.__enter__()
4953

50-
# Push span and agent to contextvar stack
51-
push_invoke_agent_span(self._span, self.agent, self.is_streaming)
52-
5354
# Enter the original context manager
5455
result = await self.original_ctx_manager.__aenter__()
5556
self._result = result
@@ -103,9 +104,9 @@ async def wrapper(self, *args, **kwargs):
103104
model_settings = kwargs.get("model_settings")
104105

105106
# Create invoke_agent span
106-
with invoke_agent_span(user_prompt, self, model, model_settings) as span:
107-
# Push span and agent to contextvar stack
108-
push_invoke_agent_span(span, self, is_streaming)
107+
with invoke_agent_span(
108+
user_prompt, self, model, model_settings, is_streaming
109+
) as span:
109110
try:
110111
result = await original_func(self, *args, **kwargs)
111112

sentry_sdk/integrations/pydantic_ai/spans/invoke_agent.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
_set_available_tools,
99
_set_model_data,
1010
_should_send_prompts,
11+
push_invoke_agent_span,
1112
)
1213

1314
from typing import TYPE_CHECKING
@@ -16,8 +17,8 @@
1617
from typing import Any
1718

1819

19-
def invoke_agent_span(user_prompt, agent, model, model_settings):
20-
# type: (Any, Any, Any, Any) -> sentry_sdk.tracing.Span
20+
def invoke_agent_span(user_prompt, agent, model, model_settings, is_streaming=False):
21+
# type: (Any, Any, Any, Any, bool) -> sentry_sdk.tracing.Span
2122
"""Create a span for invoking the agent."""
2223
# Determine agent name for span
2324
name = "agent"
@@ -32,6 +33,10 @@ def invoke_agent_span(user_prompt, agent, model, model_settings):
3233

3334
span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, "invoke_agent")
3435

36+
# Push span and 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_invoke_agent_span(span, agent, is_streaming)
39+
3540
_set_agent_data(span, agent)
3641
_set_model_data(span, model, model_settings)
3742
_set_available_tools(span, agent)

0 commit comments

Comments
 (0)