Skip to content

feat(otel): stamp gen_ai.response.time_to_first_chunk on streaming LLM spans - #32236

Merged
yassin-berriai merged 1 commit into
litellm_internal_stagingfrom
litellm_otel_ttft_span_attribute
Jul 7, 2026
Merged

yassin-berriai merged 1 commit into
litellm_internal_stagingfrom
litellm_otel_ttft_span_attribute

Conversation

@yassin-berriai

@yassin-berriai yassin-berriai commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Linear ticket

Resolves LIT-4196

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

Screenshots / 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 14196

config:

model_list:
  - model_name: gpt-5.4
    litellm_params:
      model: openai/gpt-5.4
      api_key: os.environ/OPENAI_API_KEY

litellm_settings:
  callbacks: ["otel"]

general_settings:
  master_key: sk-litfix-4196

Streaming and non-streaming requests:

curl -s http://localhost:14196/v1/chat/completions \
  -H "Authorization: Bearer sk-litfix-4196" -H "Content-Type: application/json" \
  -d '{"model": "gpt-5.4", "messages": [{"role": "user", "content": "Say hi in one word"}], "stream": true}'

curl -s http://localhost:14196/v1/chat/completions \
  -H "Authorization: Bearer sk-litfix-4196" -H "Content-Type: application/json" \
  -d '{"model": "gpt-5.4", "messages": [{"role": "user", "content": "Say bye in one word"}]}'

Before this change, the streaming LLM-call span exported to the console carried no first-chunk timing at all:

span: chat gpt-5.4  streaming=True
  gen_ai.response.time_to_first_chunk = <absent>
  gen_ai.response.id = chatcmpl-DyZXg3NuIR42NBUU1UUBRbv82Ec9w

After this change, the streaming span carries the attribute and the non-streaming span correctly omits it:

span: chat gpt-5.4  streaming=True
  gen_ai.response.time_to_first_chunk = 0.9179120063781738
  gen_ai.response.id = chatcmpl-DyZYUnCBcLbA6U33hru5kSCn1uofr
span: chat gpt-5.4  streaming=None
  gen_ai.response.time_to_first_chunk = <absent>
  gen_ai.response.id = chatcmpl-DyZYViV1UYH2ooKYoJZOGiwvCdkLY

Devin e2e run

Devin e2e run of the OTel TTFT span attribute

Independent screen-recorded run on this branch with LITELLM_OTEL_V2=true and OTEL_EXPORTER=console (no OTLP endpoint set), driving the openai/gpt-5.4 deployment 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 streaming chat gpt-5.4 span carries gen_ai.response.time_to_first_chunk of about 0.81 s against a span duration of about 3.07 s, while the non-streaming span omits the attribute entirely

Type

🆕 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 define gen_ai.response.time_to_first_chunk as 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 it

This 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 backfills completion_start_time with the end time for non-streaming calls), threads it through LLMCallEvent and LLMCallSpanData, and stamps it via the GenAI mapper under the new GenAI.RESPONSE_TIME_TO_FIRST_CHUNK constant. The metrics recorder's _record_time_to_first_token now reuses the same helper, so the span attribute and the existing gen_ai.client.response.time_to_first_token histogram can never disagree

Tests: test_streaming_span_carries_time_to_first_chunk, test_non_streaming_span_has_no_time_to_first_chunk, and test_streaming_span_without_timing_omits_time_to_first_chunk in tests/test_litellm/integrations/otel/test_otel_v2_logger.py; all three fail on the previous code. The existing test_time_to_first_token_is_streaming_only covers the metric-path refactor

Link to Devin session: https://app.devin.ai/sessions/d387ea9f7410456b9eaf63a2f9c28bd7

@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR stamps gen_ai.response.time_to_first_chunk as a span attribute on streaming LLM-call spans in the OTel v2 integration, using a new shared helper (time_to_first_chunk_seconds) that is now also reused by the existing metrics histogram path, keeping the two signals in sync.

  • A module-level helper in metadata.py computes TTFT from api_call_start_time and completion_start_time, returning None for non-streaming calls (where completion_start_time is backfilled with the end time). The value is threaded through LLMCallEvent → LLMCallSpanData → GenAIMapper, where None is dropped by the existing collect/drop_none machinery so non-streaming spans correctly omit the attribute.
  • The refactor of _record_time_to_first_token in metrics.py removes inline duplication and guarantees the span attribute and the gen_ai.client.response.time_to_first_token histogram can never disagree. Three new mock-only tests cover streaming with timing, non-streaming, and streaming without timing.

Confidence Score: 4/5

Safe 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 time_to_first_chunk_seconds helper has no guard against a negative result.

Important Files Changed

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

Comment on lines +232 to +234
if api_call_start is None or completion_start is None:
return None
return completion_start - api_call_start

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Suggested change
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-apps

greptile-apps Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR stamps gen_ai.response.time_to_first_chunk on streaming LLM-call spans in the OTel v2 integration, filling a gap where TTFT was only available as an opt-in metrics histogram but absent from traces entirely.

  • Adds a time_to_first_chunk_seconds helper in metadata.py that computes completion_start_time − api_call_start_time for streaming calls only (non-streaming returns None immediately), threads the value through LLMCallEvent → LLMCallSpanData → GenAIMapper, and relies on the existing collect/drop_none pipeline to omit the attribute when it is None.
  • Refactors _record_time_to_first_token in metrics.py to delegate to the same helper, ensuring the histogram and the new span attribute can never disagree.
  • Adds three new unit tests covering the streaming, non-streaming, and missing-timing cases, all using in-memory spans with no real network calls.

Confidence Score: 5/5

The 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.

Important Files Changed

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

codecov Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@yassin-berriai
yassin-berriai enabled auto-merge (squash) July 6, 2026 09:32
@yassin-berriai
yassin-berriai merged commit 3116ed2 into litellm_internal_staging Jul 7, 2026
75 checks passed
@yassin-berriai
yassin-berriai deleted the litellm_otel_ttft_span_attribute branch July 7, 2026 16:15
yuneng-berri added a commit that referenced this pull request Jul 8, 2026
stvnksslr pushed a commit to stvnksslr/litellm that referenced this pull request Jul 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants