Skip to content

Commit e5d5c52

Browse files
add except block
1 parent dd3063b commit e5d5c52

File tree

1 file changed

+28
-14
lines changed
  • sentry_sdk/integrations/openai_agents/patches

1 file changed

+28
-14
lines changed

sentry_sdk/integrations/openai_agents/patches/runner.py

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
from functools import wraps
22

33
import sentry_sdk
4+
from sentry_sdk.integrations import DidNotEnable
45

5-
from ..spans import agent_workflow_span
6-
from ..utils import _capture_exception
6+
from ..spans import agent_workflow_span, end_invoke_agent_span
7+
from ..utils import _capture_exception, _record_exception_on_span
8+
9+
try:
10+
from agents.exceptions import AgentsException
11+
except ImportError:
12+
raise DidNotEnable("OpenAI Agents not installed")
713

814
from typing import TYPE_CHECKING
915

@@ -28,18 +34,26 @@ async def wrapper(*args, **kwargs):
2834
with sentry_sdk.isolation_scope():
2935
agent = args[0]
3036
with agent_workflow_span(agent):
31-
run_result = await original_func(*args, **kwargs)
32-
33-
invoke_agent_span = getattr(
34-
run_result.context_wrapper, "_sentry_agent_span", None
35-
)
36-
37-
if (
38-
invoke_agent_span is not None
39-
and invoke_agent_span.timestamp is None
40-
):
41-
invoke_agent_span.__exit__(None, None, None)
42-
37+
try:
38+
run_result = await original_func(*args, **kwargs)
39+
except AgentsException as exc:
40+
context_wrapper = getattr(exc.run_data, "context_wrapper", None)
41+
if context_wrapper is not None:
42+
invoke_agent_span = getattr(
43+
context_wrapper, "_sentry_agent_span", None
44+
)
45+
46+
if (
47+
invoke_agent_span is not None
48+
and invoke_agent_span.timestamp is None
49+
):
50+
_record_exception_on_span(invoke_agent_span, exc)
51+
end_invoke_agent_span(context_wrapper, agent)
52+
53+
_capture_exception(exc)
54+
raise exc from None
55+
56+
end_invoke_agent_span(run_result.context_wrapper, agent)
4357
return run_result
4458

4559
return wrapper

0 commit comments

Comments
 (0)