Skip to content

Commit 09b45de

Browse files
Merge branch 'webb/anthropic/streaming-reasoning' of github.com:getsentry/sentry-python into webb/anthropic/streaming-reasoning
2 parents 08af830 + 510b381 commit 09b45de

1 file changed

Lines changed: 13 additions & 15 deletions

File tree

‎sentry_sdk/integrations/anthropic.py‎

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@
5757
MessageDeltaEvent,
5858
MessageStartEvent,
5959
MessageStopEvent,
60+
TextBlock,
61+
ToolUseBlock,
6062
)
6163

6264
if TYPE_CHECKING:
@@ -65,10 +67,10 @@
6567
raise DidNotEnable("Anthropic not installed")
6668

6769
try:
68-
from anthropic.types import ThinkingBlock
70+
from anthropic.types import ThinkingBlock, ThinkingDelta
6971
except ImportError:
7072
ThinkingBlock = None # type: ignore[assignment,misc]
71-
73+
ThinkingDelta = None # type: ignore[assignment,misc]
7274

7375
if TYPE_CHECKING:
7476
from typing import (
@@ -385,18 +387,16 @@ def _collect_ai_data(
385387
event.content_block, ThinkingBlock
386388
):
387389
content_blocks.append({"type": "thinking", "thinking": ""})
388-
else:
390+
elif isinstance(event.content_block, (TextBlock, ToolUseBlock)):
389391
content_blocks.append({"type": "text", "text": ""})
390392
elif event.type == "content_block_delta" and content_blocks:
391-
block = content_blocks[-1]
392-
if block["type"] == "thinking":
393-
block["thinking"] += event.delta.thinking
394-
else:
395-
chunk = getattr(event.delta, "text", None) or getattr(
396-
event.delta, "partial_json", None
397-
)
398-
if chunk:
399-
block["text"] += chunk
393+
delta = event.delta
394+
if ThinkingDelta is not None and isinstance(delta, ThinkingDelta):
395+
content_blocks[-1]["thinking"] += delta.thinking
396+
elif hasattr(event.delta, "text"):
397+
content_blocks[-1]["text"] += event.delta.text
398+
elif hasattr(event.delta, "partial_json"):
399+
content_blocks[-1]["text"] += event.delta.partial_json
400400
elif event.type == "content_block_stop":
401401
pass
402402

@@ -754,9 +754,7 @@ def _set_output_data(
754754
if output["type"] == "text":
755755
parts.append({"type": "text", "content": output["text"]})
756756
elif output["type"] == "thinking":
757-
parts.append(
758-
{"type": "reasoning", "content": output.get("thinking", "")}
759-
)
757+
parts.append({"type": "reasoning", "content": output.get("thinking")})
760758
elif output["type"] == "tool_use":
761759
tool_calls.append(output)
762760

0 commit comments

Comments
 (0)