← Back to Pull requests

chore(llmobs): dispatch stream.created from the Anthropic and OpenAI SDK streams #22128

Open
unknown opened this pull request with 481 lines diff across 6 files
View on GitHub
unknown unknown commented on Nov 26, 2026 15:31 UTC
Author

Description

Jira: APPSEC-71908

The Anthropic and OpenAI SDKs build every streamed response as a Stream or AsyncStream. Every consumer reads its events from that object's event iterator (_iterator): the caller of create(stream=True), the SDK message accumulators (MessageStream, ChatCompletionStream, with their snapshots and final messages), the tool runners, and the streams returned by .parse() of with_raw_response and with_streaming_response.

This PR adds a product-neutral core event on that event source, so that a product can see or replace the events before any SDK consumer reads them:

  • ddtrace/contrib/internal/_sdk_streams.py: traced_stream_init wraps Stream.__init__ / AsyncStream.__init__ and dispatches anthropic.stream.created or openai.stream.created with a StreamEvents carrier. The carrier holds the httpx response of the stream (whose request is the one the SDK sent), the event iterator, and whether the stream is async. The contrib installs the iterator that a listener leaves on the carrier.

  • - Older SDKs set _iterator in the constructor. Newer ones make it on first use as a cached property, from a copy of the stream (anthropic 2.x). For those, the carrier holds a lazy iterator that makes the SDK one on the first read, after every subclass constructor has run. For example, BedrockStream sets its AWS decoder after super().__init__(). The lazy iterator refers to the stream through a weak reference, so the replaced iterator does not keep the stream alive.
    - When no product listens, the hook only calls core.has_listeners.
  • The Anthropic and OpenAI patch() functions wrap and unwrap the two constructors.
  • Nothing listens to these events yet. #22020 uses them to move AI Guard's stream evaluation below the SDK accumulators.

    Testing

  • tests/contrib/anthropic/test_anthropic_stream_hook.py, with a mocked transport:

  • - a listener that replaces the events is seen by create(stream=True) and by the sync and async messages.stream() accumulators;
    - streams are unchanged without a listener;
    - a Stream subclass that sets attributes after super().__init__() keeps them.
  • tests/contrib/openai/test_openai_stream_hook.py: the same for sync and async Chat Completions streams and with_streaming_response(...).parse(), plus streams unchanged without a listener.

  • The patch tests check that the two constructors are wrapped once and unwrapped.

  • Local runs:

  • - anthropic 0.28, <1, 1.x and 2.x;
    - openai 1.0.0, <2, 3.26 and latest.
  • ddtrace/contrib/internal/_sdk_streams.py is added to the llmobs suitespec component, so changes to it select the Anthropic and OpenAI suites.
  • Risks

  • The hook relies on the SDK _iterator attribute of Stream / AsyncStream: an instance attribute in older SDKs, and a cached property in newer ones. It skips a stream that has neither.

  • Every Anthropic and OpenAI stream now goes through the wrapped constructor; with no listener, the cost is one core.has_listeners lookup per stream.
  • Additional Notes

  • No release note: nothing listens to the new events in this PR, so there is no customer-visible change.

  • Benchmarks: no scenario in benchmarks/ covers the Anthropic or OpenAI SDKs, so this path has no benchmark coverage. Measured directly instead, with timeit on Stream(...) construction and no listener: about +0.6-0.75 µs per streamed response (anthropic 2.8.0 on Python 3.15: ~450 ns to ~1040-1200 ns; anthropic 0.28.0 on Python 3.9: ~750 ns to ~1300-1470 ns). The cost is once per stream, not per chunk.
  • 🤖 Generated with Claude Code

    [APPSEC-71908]: https://datadoghq.atlassian.net/browse/APPSEC-71908?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

    Diff: 481 lines (+360 / -121) across 6 files Reviewer: avara1986 Review duration: 6702m
    All Vouch review confidence checks passed
    Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 481 lines diff across 6 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.370
    Shallow Review Depth shallow_review_depth
    0.344
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    1 comments
    "Review active on #22128"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52.3% (MEDIUM) · Higher = larger blast radius
    52.3%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 27.9% · Safe to merge
    27.9%