fix(openai): parse raw API responses and add flag to skip tracing them - #1740
Merged
Conversation
Calls made via the OpenAI SDK's `.with_raw_response` API return a `LegacyAPIResponse` instead of the parsed model, so the wrapper exported generations without output and usage. Since libraries like LiteLLM call the OpenAI SDK exclusively through `.with_raw_response` (to read rate limit headers), any LiteLLM call in a process that imports `langfuse.openai` produced these broken generations. - Parse raw responses before data extraction so output, usage (incl. cached token details), and model are captured. `.parse()` caches its result on the response object, so callers parsing later are unaffected. - Pass raw streaming calls (`stream=True` or `.with_streaming_response`) through untraced, as instrumenting them would require consuming the caller's stream or raw body. - Add `LANGFUSE_OPENAI_SKIP_RAW_RESPONSES` env flag to exclude all raw-response calls from tracing. This avoids duplicate observations when another instrumented library (e.g. LiteLLM with the `langfuse_otel` callback) calls the OpenAI SDK internally. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
|
@claude review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f8b0e6ec31
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Calls made via the OpenAI SDK's
.with_raw_responseAPI return aLegacyAPIResponseinstead of the parsed model. The wrapper's data extraction found nochoices/usageon it and silently exported generations without output and usage, causing the server to fall back to tokenizer-based estimation (input-only, no cached-token details, wrong cost).This matters beyond direct raw-response users: LiteLLM calls the OpenAI SDK exclusively through
.with_raw_response(unconditionally, to read rate-limit headers for its router). Any process that importslangfuse.openaiand also uses LiteLLM gets one of these brokenOpenAI-generationobservations for every LiteLLM call — on top of the observation produced by LiteLLM's ownlangfuse_otelcallback, double-counting observations and cost.Changes
LegacyAPIResponse/APIResponseresults are unwrapped via.parse()so output, usage (incl.prompt_tokens_details.cached_tokens) and model are captured..parse()caches its result on the response object, so callers that parse later (e.g. LiteLLM) are unaffected — verified against LiteLLM 1.83.7.stream=Truevia.with_raw_response, or.with_streaming_response): instrumenting them would require consuming the caller's stream or raw body. These previously produced broken input-only generations.LANGFUSE_OPENAI_SKIP_RAW_RESPONSES(defaultFalse): when set, all raw-response calls are passed through untraced. This is the supported way to combine thelangfuse.openaiwrapper (for direct OpenAI calls) with another instrumented library that calls the OpenAI SDK internally via raw responses (e.g. LiteLLM +langfuse_otelcallback) without duplicate observations per LLM call.Testing
httpx.MockTransportso the SDK's real raw-response machinery runs end-to-end: sync + async raw calls capture output/usage incl. cached tokens; skip flag bypasses instrumentation while normal calls stay traced; raw streaming passes through with the stream contract intact.tests/unit, 607 passed; pre-existingtest_prompt.pyfixture errors also occur onmain).langfuse_otelcallback:OpenAI-generationnow carries output and full usage incl.cached_tokensOpenAI-generationspans for LiteLLM-internal calls; direct calls unaffected🤖 Generated with Claude Code
Greptile Summary
This PR fixes a silent data-loss bug in the OpenAI wrapper where calls made via
.with_raw_response(used unconditionally by LiteLLM) returned aLegacyAPIResponse/APIResponseobject rather than the parsed model, causing output, usage, and cost to be missing from exported generations. It also addsLANGFUSE_OPENAI_SKIP_RAW_RESPONSESas an opt-in env flag to bypass instrumentation of raw-response calls entirely._unwrap_raw_response): calls.parse()on raw response objects before data extraction;.parse()caches its result so downstream callers (e.g. LiteLLM) that parse later are unaffected.LANGFUSE_OPENAI_SKIP_RAW_RESPONSESflag: when set, all raw-response calls skip the wrapper; four new unit tests usinghttpx.MockTransportcover the sync/async capture, the skip flag, and streaming pass-through.Confidence Score: 4/5
The core fix is sound and well-tested; the only issue is a style rule violation that does not affect runtime correctness.
The fix correctly unwraps raw API responses before data extraction, preserves the original response object for the caller, and guards streaming cases that cannot be instrumented. The inline imports inside
_unwrap_raw_responseare the only concern — they run on every non-streaming call and swallow import errors inside a broad except, but have no functional impact.langfuse/openai.py — the inline imports inside
_unwrap_raw_responseshould be moved to module level alongside the existing RAW_RESPONSE_HEADER guard.Prompt To Fix All With AI
Reviews (1): Last reviewed commit: "fix(openai): parse raw API responses and..." | Re-trigger Greptile
Context used:
Learned From
langfuse/langfuse-python#1387