Repository navigation
feat(otel): stamp gen_ai.response.time_to_first_chunk on streaming LLM spans - #32236
Conversation
|
|
Greptile SummaryThis PR stamps
Confidence Score: 4/5Safe to merge; the change is additive (new optional span attribute) and the refactor in the metrics path is a clean delegation with equivalent behavior. The implementation is well-structured and the tests are thorough. The one gap is that the computed TTFT value is not clamped to non-negative, so rare clock-skew or stale-timestamp scenarios could produce a negative latency value on both the span attribute and the histogram — the pre-existing metric path had the same gap, but it now applies to spans too. litellm/integrations/otel/model/metadata.py — the
|
| Filename | Overview |
|---|---|
| litellm/integrations/otel/model/metadata.py | Adds time_to_first_chunk_seconds field to LLMCallEvent and a module-level helper function that computes TTFT from api_call_start_time / completion_start_time, guarded by optional_params["stream"]; no guard against a negative result. |
| litellm/integrations/otel/model/payloads.py | Adds `time_to_first_chunk_seconds: float |
| litellm/integrations/otel/mappers/genai.py | Adds RESPONSE_TIME_TO_FIRST_CHUNK extractor to _LLM_CALL_ATTRS; None values are dropped by the existing collect/drop_none machinery, so non-streaming spans correctly omit the attribute. |
| litellm/integrations/otel/model/semconv.py | Adds RESPONSE_TIME_TO_FIRST_CHUNK = "gen_ai.response.time_to_first_chunk" constant aligned with the OTel GenAI semantic conventions spec. |
| litellm/integrations/otel/plumbing/metrics.py | Refactors _record_time_to_first_token to delegate to the shared time_to_first_chunk_seconds helper, eliminating inline duplication and ensuring span attribute and histogram always agree. |
| litellm/integrations/otel/logger.py | Passes call.time_to_first_chunk_seconds from the close-time LLMCallEvent into LLMCallSpanData.from_standard_logging_payload; change is minimal and correct. |
| tests/test_litellm/integrations/otel/test_otel_v2_logger.py | Adds three new tests covering streaming TTFT present, non-streaming TTFT absent, and missing-timing omission; all mock-based with no network calls, in compliance with repo test rules. |
Reviews (1): Last reviewed commit: "feat(otel): stamp gen_ai.response.time_t..." | Re-trigger Greptile
| if api_call_start is None or completion_start is None: | ||
| return None | ||
| return completion_start - api_call_start |
There was a problem hiding this comment.
The computed difference is returned without clamping, so if
completion_start_time is somehow earlier than api_call_start_time (clock skew, retried calls where a previously-cached timestamp leaks in, or malformed logging state) the span attribute and the gen_ai.client.response.time_to_first_token histogram will carry a negative latency value. The existing metric path had the same gap, but stamping negative latency on a span attribute makes it visibly wrong in trace UIs. A simple max(0.0, ...) guard keeps the value non-negative without hiding the mismatch.
| if api_call_start is None or completion_start is None: | |
| return None | |
| return completion_start - api_call_start | |
| if api_call_start is None or completion_start is None: | |
| return None | |
| return max(0.0, completion_start - api_call_start) |
Greptile SummaryThis PR stamps
Confidence Score: 5/5The change is purely additive — it adds a new optional span attribute on the streaming path and eliminates inline TTFT duplication in the metrics recorder. No existing span attributes, callback signatures, or public APIs are altered. The TTFT computation is safely guarded at two levels: the stream flag check returns None immediately for non-streaming calls, and the missing-timestamp guard returns None when timing data is absent. The collect/drop_none pipeline then correctly omits a None attribute, so the attribute never appears on non-streaming or timing-less spans. The metrics refactor is a straightforward delegation with identical semantics to the previous inline code. No files require special attention.
|
| Filename | Overview |
|---|---|
| litellm/integrations/otel/model/metadata.py | Adds time_to_first_chunk_seconds field to LLMCallEvent and a new module-level function with the same name that computes TTFT from kwargs; guards correctly on both stream flag and timestamp availability. |
| litellm/integrations/otel/model/payloads.py | Adds `time_to_first_chunk_seconds: float |
| litellm/integrations/otel/model/semconv.py | Adds RESPONSE_TIME_TO_FIRST_CHUNK = "gen_ai.response.time_to_first_chunk" constant to GenAI; matches the OTel GenAI semantic conventions spec. |
| litellm/integrations/otel/mappers/genai.py | Adds a mapper entry for RESPONSE_TIME_TO_FIRST_CHUNK; relies on collect/drop_none to omit the attribute when the value is None, which correctly handles non-streaming spans. |
| litellm/integrations/otel/logger.py | Passes call.time_to_first_chunk_seconds (already computed on the LLMCallEvent) into LLMCallSpanData.from_standard_logging_payload; no behavioural changes to the span lifecycle itself. |
| litellm/integrations/otel/plumbing/metrics.py | Refactors _record_time_to_first_token to delegate to the shared time_to_first_chunk_seconds helper, eliminating the previous inline re-implementation and keeping the histogram and span attribute in sync. |
| tests/test_litellm/integrations/otel/test_otel_v2_logger.py | Adds three focused unit tests covering the streaming, non-streaming, and missing-timing cases; all use in-memory spans and no real network calls. |
Reviews (2): Last reviewed commit: "feat(otel): stamp gen_ai.response.time_t..." | Re-trigger Greptile
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…M spans (BerriAI#32236) (cherry picked from commit 3116ed2)
Relevant issues
Linear ticket
Resolves LIT-4196
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewScreenshots / Proof of Fix
Ran a live proxy with the OTel v2 integration and the console span exporter, hitting the real OpenAI API:
export LITELLM_OTEL_V2=true OTEL_EXPORTER=console python litellm/proxy/proxy_cli.py --config otel_ttft_config.yaml --port 14196config:
Streaming and non-streaming requests:
Before this change, the streaming LLM-call span exported to the console carried no first-chunk timing at all:
After this change, the streaming span carries the attribute and the non-streaming span correctly omits it:
Devin e2e run
Independent screen-recorded run on this branch with
LITELLM_OTEL_V2=trueandOTEL_EXPORTER=console(no OTLP endpoint set), driving theopenai/gpt-5.4deployment against a local OpenAI-compatible backend since no live OpenAI key was available. The video shows the proxy starting up, one streaming and one non-streaming chat completion over curl, and the console span output: the streamingchat gpt-5.4span carriesgen_ai.response.time_to_first_chunkof about 0.81 s against a span duration of about 3.07 s, while the non-streaming span omits the attribute entirelyType
🆕 New Feature
Changes
The OTel integration exposed time to first token only as an opt-in metrics histogram (
LITELLM_OTEL_INTEGRATION_ENABLE_METRICS=true), so anyone consuming traces had no TTFT signal on spans. The current OpenTelemetry GenAI semantic conventions definegen_ai.response.time_to_first_chunkas a span attribute, recommended for streaming requests and measured from when the client issues the generation request to when the first chunk arrives (https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-spans.md). OpenInference defines no TTFT convention, so only the canonical GenAI mapper stamps itThis PR computes first-chunk latency once, in
model/metadata.py(time_to_first_chunk_seconds,completion_start_time - api_call_start_time, streaming only since litellm backfillscompletion_start_timewith the end time for non-streaming calls), threads it throughLLMCallEventandLLMCallSpanData, and stamps it via the GenAI mapper under the newGenAI.RESPONSE_TIME_TO_FIRST_CHUNKconstant. The metrics recorder's_record_time_to_first_tokennow reuses the same helper, so the span attribute and the existinggen_ai.client.response.time_to_first_tokenhistogram can never disagreeTests:
test_streaming_span_carries_time_to_first_chunk,test_non_streaming_span_has_no_time_to_first_chunk, andtest_streaming_span_without_timing_omits_time_to_first_chunkintests/test_litellm/integrations/otel/test_otel_v2_logger.py; all three fail on the previous code. The existingtest_time_to_first_token_is_streaming_onlycovers the metric-path refactorLink to Devin session: https://app.devin.ai/sessions/d387ea9f7410456b9eaf63a2f9c28bd7