Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion sentry_sdk/integrations/openai_agents/patches/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ def wrapped_get_model(cls, agent, run_config):
# type: (agents.Runner, agents.Agent, agents.RunConfig) -> agents.Model

model = original_get_model(agent, run_config)
original_get_response = model.get_response

# check if we have already patched this model
if getattr(model, "_sentry_wrapped_get_model", False):
return model
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Stale agent reference captured in closure when model reused

When a model instance is shared across multiple agents, the early return on line 37-38 prevents re-patching but causes wrapped_fetch_response and wrapped_get_response to use a stale agent reference from their closures. The closures capture the agent from the first call to wrapped_get_model, so subsequent calls with different agents will incorrectly write/read _sentry_raw_response_model on the wrong agent and create spans associated with the wrong agent. The wrapper functions need access to the current agent being used, not the one captured at patch time.

Additional Locations (2)

Fix in Cursor Fix in Web

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this looks like a valid concern @constantinius


# Wrap _fetch_response if it exists (for OpenAI models) to capture raw response model
if hasattr(model, "_fetch_response"):
Expand All @@ -48,6 +51,8 @@ async def wrapped_fetch_response(*args, **kwargs):

model._fetch_response = wrapped_fetch_response

original_get_response = model.get_response

@wraps(original_get_response)
async def wrapped_get_response(*args, **kwargs):
# type: (*Any, **Any) -> Any
Expand All @@ -70,6 +75,9 @@ async def wrapped_get_response(*args, **kwargs):

model.get_response = wrapped_get_response

# set marker that we have already patched this model
model._sentry_wrapped_get_model = True

return model

return wrapped_get_model