Skip to content

fix(openlit): map LLM spans from openlit 1.37+ and their cache and reasoning token counts - #4200

Open
sohom-cs wants to merge 3 commits into
Arize-ai:mainfrom
sohom-cs:fix/openlit-provider-name-token-details
Open

sohom-cs wants to merge 3 commits into
Arize-ai:mainfrom
sohom-cs:fix/openlit-provider-name-token-details

Conversation

@sohom-cs

@sohom-cs sohom-cs commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Closes #4199

openlit 1.37.0 and later write gen_ai.provider.name where older versions wrote gen_ai.system, and the span processor only looked for gen_ai.system, so LLM spans from current openlit got no OpenInference attributes. These versions also write the conversation as gen_ai.input.messages and gen_ai.output.messages attributes instead of the gen_ai.prompt and gen_ai.completion values the processor reads, and the processor never mapped openlit's cache and reasoning token counts.

Changes

  • Read gen_ai.provider.name when gen_ai.system is absent, in _is_llm_span, _is_chain_span and for llm.system. gen_ai.system wins when both are present, so spans from openlit 1.36 and older map as before.
  • When a span carries gen_ai.input.messages or gen_ai.output.messages (OTel GenAI JSON), build the messages from their parts: text becomes the content, tool_call the tool calls, and each tool_call_response a tool message. input.value and output.value come from the same messages. Spans without these attributes keep the event path.
  • Map the token-count details, skipping zeros like the existing counts, since openlit can write 0 for a count the provider left out:
openlit attribute OpenInference attribute
gen_ai.usage.cache_read.input_tokens llm.token_count.prompt_details.cache_read
gen_ai.usage.cache_creation.input_tokens llm.token_count.prompt_details.cache_write
gen_ai.usage.reasoning_tokens, else gen_ai.usage.completion_tokens_details.reasoning_tokens llm.token_count.completion_details.reasoning

An OpenAI chat span from openlit 1.44.0 now gets:

llm.input_messages.0.message.role: user
llm.input_messages.0.message.content: hello
llm.output_messages.0.message.role: assistant
llm.output_messages.0.message.content: hi
input.value: {"messages": [{"role": "user", "content": "hello"}], "model": "gpt-4o-mini", "temperature": 1.0, "top_p": 1.0}
output.value: {"id": "chatcmpl-1", "messages": [{"role": "assistant", "content": "hi"}]}

Not changed

  • The Anthropic prompt count is not folded: openlit's Anthropic module writes Anthropic's input_tokens, which leaves out the cache, but its LangChain module writes the same provider name with a count that includes it (streamed ChatAnthropic), and the span can't tell them apart. The README says so.
  • openlit's OpenAI and Anthropic modules don't write gen_ai.usage.total_tokens, so llm.token_count.total stays unset.
  • Modules that write plain text into the message attributes, such as Together, get no messages.

Tests

test_token_counts.py drives openlit's own OpenAI and Anthropic modules against httpx.MockTransport responses. It checks every OpenInference attribute on an OpenAI chat span and a cached Anthropic span, the token counts of four calls, and an Anthropic request with a tool call and its result. Smaller cases set attributes directly. Most of the test code is canned responses and expected attributes, hence its size.

tox -e py313-ci-openlit, py313-ci-openlit-latest (openlit 1.45.0), py310-ci-openlit and py310-ci-openlit-latest pass, with ruff and mypy clean. Not tested: real API calls, streaming, and openlit's other provider modules.

Checklist:

  • Follows OpenInference configuration to hide sensitive info (N/A: the span processor has no TraceConfig; openlit's capture_message_content=False keeps message content off the span)
  • Spans properly inherit from context attributes (N/A: no span creation changes)
  • Properly respects suppress tracing context (N/A: span processor, no new spans)

…asoning token counts

openlit 1.37.0 and later write gen_ai.provider.name instead of
gen_ai.system, and the span processor only looked for gen_ai.system, so
LLM spans from current openlit got no OpenInference attributes. Read
gen_ai.provider.name when gen_ai.system is absent.

Also map gen_ai.usage.cache_read.input_tokens,
gen_ai.usage.cache_creation.input_tokens and the reasoning token counts
to llm.token_count.prompt_details.cache_read, .cache_write and
llm.token_count.completion_details.reasoning. Zero counts are skipped,
like the existing prompt, completion and total counts.
@sohom-cs
sohom-cs requested a review from a team as a code owner October 30, 2026 22:10
@mikeldking mikeldking added the factory-review to be reviewed by the software factory label Oct 30, 2026
@openinference-factory

Copy link
Copy Markdown
Contributor

The factory started a review of 255a3ea (session sesn_015q3zLmngGXHCK4eAeH2caJ). It reports back here when the session ends.

@openinference-factory openinference-factory Bot left a comment

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.

Factory review of 255a3ea: Request changes

Tests is Fail: the _is_chain_span change alters how spans are classified, and no test covers it.

Criterion Result Notes
Fit Pass does what it claims
Checks Pass ci-openlit, ci-openlit-latest
Tests Fail 8 new tests fail without the change; the _is_chain_span and key-precedence changes are untested
Blocking findings 1 untested no-address classification change _span_processor.py:78
Non-blocking findings 2 spot-check assertions test_token_counts.py:184; Anthropic cache exceeds prompt _span_processor.py:283
Risk Low side effects: 1.37+ spans now get attributes, same mapping as for 1.36 spans
Review depth Focused one processor file and a new test, Risk Low, checks ran
Details

Intent: Map openlit 1.37+ LLM spans, which write gen_ai.provider.name instead of gen_ai.system, to OpenInference. Also map openlit's cache-read, cache-write and reasoning token counts to llm.token_count.prompt_details.cache_read/cache_write and llm.token_count.completion_details.reasoning (closes #4199).
Fit: _is_llm_span, _is_chain_span and llm.system extraction now fall back to gen_ai.provider.name, with gen_ai.system taking precedence. The three token-detail attributes are mapped, skipping zeros. Nothing extra changes. As the PR body says, llm.provider and llm.token_count.total stay unset for 1.37+ spans; both gaps predate this PR.
Verified: tox run -e ci-openlit (openlit 1.44.0) and ci-openlit-latest (openlit 1.45.0) on Python 3.11 both pass: ruff format, ruff check and mypy clean; 19 passed, 1 skipped. Without the PR's source change, all 8 new tests fail (span kind None, missing reasoning/cache counts). The suite also passes serially in both file orders.
Mutations run in the tox env:

  • reverting _is_chain_span (line 78) to read only gen_ai.system: still passes;
  • swapping the key precedence in _get_gen_ai_system: still passes.
    PromptDetails and LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING exist at the declared floors (openinference-instrumentation 0.1.71, semconv 0.1.42).
    Not verified:
  • Python 3.10/3.13, which CI runs; the sandbox has 3.11.
  • openlit 1.37–1.43.
  • openlit's provider modules other than OpenAI and Anthropic.
  • Streaming paths.
  • The PR's LangChain cache numbers.
    Findings without a diff line: none
    Risk: side effects low, performance none, backwards compatibility low. gen_ai.system spans classify and map as before, which the reviewer checked by comparing classifications on main and HEAD.

Graded against the review criteria.

False: LLM span.
"""
sys_name = str(attrs.get("gen_ai.system", "")).lower()
sys_name = str(_get_gen_ai_system(attrs, "")).lower()

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.

Blocking. This line changes how spans are classified, and no test covers it. Take a span with gen_ai.provider.name set to an LLM provider and no server.address/server.port (e.g. {"gen_ai.provider.name": "openai", "gen_ai.operation.name": "chat"}). On main _is_chain_span returns True (CHAIN); here it returns False (LLM). openlit's LangChain handler leaves server.address unset when it can't resolve a host for the provider, so this path is real.

Evidence: I reverted this line to attrs.get("gen_ai.system", "") and the full suite still passes (19 passed, 1 skipped). Every new test span carries server.address and server.port. The same goes for the precedence in _get_gen_ai_system (line 103): swapping it so gen_ai.provider.name wins also passes everything, because no case sets both keys. REVIEW.md § Always Check says tests MUST fail when the behavior they cover is removed.

Fix: add two cases to test_reasoning_tokens_and_both_system_keys:

  • one without server.address/server.port that asserts openinference.span.kind == LLM;
  • one that sets both keys to different known values (e.g. gen_ai.system: openai, gen_ai.provider.name: anthropic) and asserts llm.system == openai.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Covered in 23eb391; I answered the same finding in the 10-31 thread on this line.

Comment on lines +184 to +190
assert "gen_ai.system" not in attributes
assert (
attributes.get(SpanAttributes.OPENINFERENCE_SPAN_KIND)
== OpenInferenceSpanKindValues.LLM.value
)
assert attributes.get(SpanAttributes.LLM_SYSTEM) == system
assert _token_counts(attributes) == expected

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.

Non-blocking. This PR is what first gives openlit 1.37+ spans their OpenInference attributes, but the real-SDK test only checks span kind, llm.system and the token counts. Nothing asserts llm.model_name, llm.input_messages/llm.output_messages, input.value/output.value, llm.invocation_parameters or llm.finish_reason. A regression in any of those would pass.

Rule: REVIEW.md § Style says Python instrumentor tests SHOULD assert exhaustively (python-code-reviewer skill § 2.3).

Fix: pop each expected OpenInference key (openinference.*, llm.*, input.*, output.*) from a copy of attributes, asserting each value. Then assert that no OpenInference-owned key remains.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Answered in the 10-31 thread on this line: test_openlit_llm_span_attributes (23eb391) checks every OpenInference key.

Comment on lines +283 to +289
prompt_details = oi.PromptDetails()
if cache_read := _int_safe(attrs.get("gen_ai.usage.cache_read.input_tokens")):
prompt_details["cache_read"] = cache_read
if cache_write := _int_safe(attrs.get("gen_ai.usage.cache_creation.input_tokens")):
prompt_details["cache_write"] = cache_write
if prompt_details:
token_count["prompt_details"] = prompt_details

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.

Non-blocking. For openlit's Anthropic module, this emits cache details larger than the prompt count. The anthropic-cache-read-and-write test (test_token_counts.py:156-162) pins prompt: 50 next to cache_read: 1000 and cache_write: 150.

That goes against spec/semantic_conventions.md:253-257: prompt_details.* are sub-counts of llm.token_count.prompt, which "is expected to be greater than or equal to their sum". For Anthropic, instrumentations "should fold" cache tokens back into prompt. Downstream code that subtracts cache counts from prompt would see a negative uncached count; that is inferred, not tested.

The PR body's double-counting concern for the LangChain path is real, so a blanket fold on provider == "anthropic" is not the fix. Folding only when cache_read + cache_write > prompt is not reliable either.

Fix, either of:

  • fold only when the span carries a marker that it came from openlit's direct Anthropic module, if one exists;
  • or keep the pass-through, add a comment here saying why, and record the deviation in the package README.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same point as the 10-31 thread at line 288, answered there: the pass-through stays, with the reason documented in 23eb391.

@openinference-factory

Copy link
Copy Markdown
Contributor

The factory recommends Request changes for 255a3ea. Read the review.

@openinference-factory openinference-factory Bot removed the factory-review to be reviewed by the software factory label Oct 30, 2026
@mikeldking mikeldking added the factory-review to be reviewed by the software factory label Oct 31, 2026 — with Claude
@openinference-factory

Copy link
Copy Markdown
Contributor

The factory started a review of 255a3ea (session sesn_01GhKHP9h8e7umCXgzLgV9So). It reports back here when the session ends.

@openinference-factory openinference-factory Bot left a comment

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.

Factory review of 255a3ea: Request changes

Tests is Fail: the _is_chain_span change and the key-precedence rule change behavior, and no test fails if either is reverted.

Criterion Result Notes
Fit Pass does what it claims
Checks Pass ci-openlit, ci-openlit-latest
Tests Fail 8 new tests fail on main; chain-classification and precedence mutations still pass
Blocking findings 1 untested chain classification and precedence _span_processor.py:78
Non-blocking findings 3 Anthropic cache exceeds prompt _span_processor.py:284; fixture never restores global state test_token_counts.py:30; spot-check assertions test_token_counts.py:190
Risk Medium side effects: 1.37+ framework spans with an LLM provider become LLM, as 1.36 spans already did
Review depth Deep Risk Medium
Details

Intent: Map spans from openlit 1.37+, which write gen_ai.provider.name instead of gen_ai.system, to OpenInference attributes, with gen_ai.system winning when both are present (closes #4199).
The PR also maps openlit's cache-read, cache-write and reasoning token counts to llm.token_count.prompt_details.cache_read/cache_write and llm.token_count.completion_details.reasoning, skipping zeros.
Fit: _is_llm_span, _is_chain_span and the llm.system extraction all fall back to gen_ai.provider.name, and the three token-detail attributes are mapped as described.
Nothing changes that the PR doesn't claim. The gaps the PR body admits are both pre-existing: no llm.token_count.total on the openlit OpenAI and Anthropic spans, and Anthropic cache not folded into prompt.
Verified: tox run -e ci-openlit (openlit 1.44.0) and ci-openlit-latest (openlit 1.45.0) on Python 3.11: ruff format, ruff check and mypy clean; 19 passed, 1 skipped (the pre-existing test_openlit_instrumentor skip).
With main's _span_processor.py swapped into the tox env, all 8 new tests fail.
Mutation runs against the full package suite:

  • reverting _is_chain_span (line 78) to read only gen_ai.system: 19 passed;
  • swapping the precedence in _get_gen_ai_system: 19 passed;
  • dropping the completion_tokens_details.reasoning_tokens fallback: 2 failed.
    In openlit 1.36.8, the openai_agents root span carries gen_ai.system plus api.openai.com:443. On main it is already labelled LLM, so the PR's classification for 1.37+ spans matches what 1.36 spans already get.
    Not verified:
  • Python 3.10 and 3.13, which CI runs; the sandbox has 3.11.
  • openlit 1.37 to 1.43.
  • openlit provider modules other than OpenAI and Anthropic.
  • Streaming paths.
  • The PR's LangChain cache numbers.
    Findings without a diff line: none
    Risk: side effects medium, performance none, backwards compatibility low, from the Python reviewer.
    Spans from openlit 1.36 and older map as before. On 1.37+, every span with an LLM provider name now goes through the existing heuristic, which is unchanged. That includes framework and agent spans such as the openai_agents workflow root (provider openai plus api.openai.com:443): they were untouched before and are now labelled LLM, with an empty assistant message. The same heuristic already did this for 1.36 spans.

Graded against the review criteria.

if total_tokens:
token_count["total"] = total_tokens
prompt_details = oi.PromptDetails()
if cache_read := _int_safe(attrs.get("gen_ai.usage.cache_read.input_tokens")):

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.

Non-blocking. On direct Anthropic spans, the cache details are now larger than llm.token_count.prompt.

  • Evidence: the anthropic-cache-read-and-write test pins prompt=50, cache_read=1000, cache_write=150. spec/semantic_conventions.md § Token Count Details says prompt "is expected to be greater than or equal to" the sum of the prompt_details values, and that exclusive counts like Anthropic's should be folded in. openlit's anthropic/utils.py documents input_tokens as excluding cache, so this breaks that rule on every cached direct call.
  • Your reasoning holds: LangChain writes the same gen_ai.provider.name: anthropic with an inclusive count, so folding unconditionally would double-count.
  • Fix: fold cache_read + cache_write into prompt (and into total, when present) only when prompt < cache_read + cache_write. An inclusive count can never meet that condition, so the LangChain path is never double-counted, and every span that breaks the invariant today gets fixed. If you'd rather not, add a comment here explaining why the count is not folded.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I kept the pass-through and added a comment here plus a "Token counts" section in the package README (23eb391). I didn't use the prompt < cache_read + cache_write rule because it gives direct Anthropic spans two meanings: a call with 2,000 uncached and 1,000 cached tokens keeps the exclusive count, one with 50 and 1,150 gets folded, and nothing on the span says which happened. If you'd still rather have the fold, it's a few lines and I can add it.

@openinference-factory

Copy link
Copy Markdown
Contributor

The factory recommends Request changes for 255a3ea. Read the review.

@openinference-factory openinference-factory Bot removed the factory-review to be reviewed by the software factory label Oct 31, 2026
@mikeldking mikeldking added the factory-request-changes The factory review recommends requesting changes label Oct 31, 2026
Add cases for a span with gen_ai.provider.name and no server.address
(LLM now, CHAIN on main) and for gen_ai.system winning over
gen_ai.provider.name; reverting either change now fails a test. Assert
every OpenInference attribute on the OpenAI chat and Anthropic spans
from real openlit, and stop the module fixture if another tracer
provider is already global. Say in a comment and in the README why the
Anthropic cache counts are not folded into the prompt count.
@sohom-cs

sohom-cs commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

@mikeldking I addressed the factory review in 23eb391 and answered each thread above. Could you re-run the factory review when you have a moment?

@mikeldking mikeldking added the factory-review to be reviewed by the software factory label Nov 5, 2026
@openinference-factory openinference-factory Bot removed the factory-request-changes The factory review recommends requesting changes label Nov 5, 2026
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

The factory hit an error before it could report; see the workflow run.

@github-actions github-actions Bot removed the factory-review to be reviewed by the software factory label Nov 5, 2026
@mikeldking mikeldking added the factory-review to be reviewed by the software factory label Nov 5, 2026
@openinference-factory

Copy link
Copy Markdown
Contributor

The factory started a review of 23eb391 (session sesn_01L2h86hcijma2rMmX9SLBty). It reports back here when the session ends.

@openinference-factory openinference-factory Bot left a comment

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.

Factory review of 23eb391: Approve

All criteria pass and nothing blocks: the new tests fail without the change and catch the classification and precedence mutations the earlier reviews flagged.

Criterion Result Notes
Fit Pass does what it claims
Checks Pass ci-openlit, ci-openlit-latest
Tests Pass 11 of 13 new tests fail on main's processor; chain and precedence mutations each fail one
Blocking findings 0
Non-blocking findings 2 1.37+ framework/embedding spans labelled LLM _span_processor.py:98; cache-exclusive prompt also affects Bedrock _span_processor.py:283
Risk Low backwards compatibility: 1.37+ framework and embedding spans go from no attributes to LLM
Review depth Focused one processor file, a new test and a README section; checks ran
Details

Intent: Map openlit 1.37+ LLM spans to OpenInference: they write gen_ai.provider.name instead of gen_ai.system, and gen_ai.system wins when both are present. Also map openlit's cache-read, cache-write and reasoning token counts to llm.token_count.prompt_details.cache_read/cache_write and llm.token_count.completion_details.reasoning, skipping zeros (closes #4199).
Fit: _is_llm_span, _is_chain_span and the llm.system extraction fall back to gen_ai.provider.name, and the three token-detail attributes are mapped as described.
The second commit answers the earlier review: it adds key-precedence and no-address tests, a full-attribute test, a fixture guard, and a README note on the cache-exclusive prompt count.
Nothing changes that the PR doesn't claim. The gaps the PR body admits are both pre-existing and out of scope: messages from gen_ai.input/output.messages, and llm.token_count.total.
Verified:

  • tox run -e ci-openlit (openlit 1.44.0) and ci-openlit-latest (openlit 1.45.0) on Python 3.11 both pass. ruff format, ruff check and mypy are clean; 24 passed, 1 skipped (the pre-existing test_openlit_instrumentor skip).
  • With main's _span_processor.py swapped into the tox env, the suite gives 11 failed, 13 passed, 1 skipped, which matches the PR body.
  • The Python reviewer applied mutations to an installed copy:
    • reverting line 78 fails llm-provider-name-without-server-address;
    • swapping the precedence in _get_gen_ai_system fails gen-ai-system-wins-over-provider-name;
    • dropping cache_creation or either reasoning key fails 2-3 tests.
  • The suite passes with no network (unshare -rn), so the local pricing_json keeps openlit offline.
  • It passes in both file orders.
  • I reproduced the framework/embedding relabelling by running spans through the processor.
    Not verified:
  • Python 3.10 and 3.13, which CI runs; the sandbox has 3.11.
  • openlit 1.37 to 1.43.
  • Streaming paths.
  • openlit provider modules other than OpenAI and Anthropic.
  • The PR's LangChain cache numbers.
  • Whether Bedrock's inputTokens excludes cache.
    Findings without a diff line: none
    Risk: side effects low, performance none, backwards compatibility low, from the Python reviewer. Spans from openlit 1.36 and older map as before. On 1.37+, spans that carry an LLM provider name and a server address are labelled LLM, as 1.36 spans already were; that includes framework and embedding spans.

Graded against the review criteria.


def _is_llm_span(attrs: dict[str, Any]) -> bool:
return "gen_ai.system" in attrs
return "gen_ai.system" in attrs or "gen_ai.provider.name" in attrs

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.

Non-blocking. On openlit 1.37+, framework and embedding spans that carry gen_ai.provider.name plus a server address now get openinference.span.kind = LLM. On main they got no OpenInference attributes.

  • Evidence: openlit's common_framework_span_attributes (openlit/__helpers.py:1679-1704, 1.44.0) writes gen_ai.provider.name and, when it has them, server.address/server.port. The openai_agents module always passes api.openai.com:443 (openai_agents/utils.py:28,152). I ran two spans through this branch's processor:
    • {provider.name: openai, operation.name: invoke_workflow, server.address: api.openai.com, server.port: 443} gives kind=LLM, llm.system=openai;
    • the same with operation.name: embeddings also gives kind=LLM.
      Because openai is in _LLM_PROVIDERS, _is_chain_span returns False, and these spans get an empty assistant message.
  • Context: the heuristic did the same to 1.36 spans through gen_ai.system, so this matches the old classification and isn't a new design. It still means a workflow root or embedding call shows up in Phoenix as an LLM call.
  • Fix: 1.37+ always writes gen_ai.operation.name, so use it to decide. Treat chat/text_completion/generate_content as LLM and invoke_workflow/invoke_agent/framework as CHAIN, and leave embeddings to a later change. Or record the limitation in the README and leave it as it is.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Left as it is: this is the heuristic openlit 1.36 spans already go through via gen_ai.system, and classifying by gen_ai.operation.name would change the kind of spans from every openlit version, which is a separate change from this PR.

Comment on lines +283 to +286
# The cache counts are not folded into the prompt count. openlit's Anthropic module
# writes Anthropic's input_tokens, which leaves the cache out, but its LangChain module
# writes the same gen_ai.provider.name with a count that includes it (streamed
# ChatAnthropic), and nothing on the span tells the two apart. See the README.

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.

Non-blocking. Keeping the pass-through is documented now, but it goes against spec/semantic_conventions.md § Token Count Details (lines 253-257). The spec says llm.token_count.prompt should be at least the sum of prompt_details, and that cache tokens should be folded in when the provider excludes them. The sibling Anthropic instrumentor folds them (openinference-instrumentation-anthropic/.../_utils.py). Your reason for not folding unconditionally, the inclusive LangChain path, holds, so whether to accept the deviation is the maintainer's call.

The README undersells the scope. openlit's Bedrock module (openlit/instrumentation/bedrock/utils.py:374-377, 1.44.0) writes inputTokens next to cacheReadInputTokens/cacheWriteInputTokens, and amazon_bedrock is in _LLM_PROVIDERS. If Bedrock's inputTokens excludes cache the way Anthropic's does (inferred; I did not check AWS docs), Bedrock spans have the same prompt < cache problem. The README's "Token counts" section names only Anthropic.

Fix: either fold, or have the README "Token counts" section name Bedrock alongside Anthropic so users know which providers' prompt counts are cache-exclusive.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed that Bedrock is in the same position: openlit 1.45.0's Bedrock module writes Bedrock's inputTokens, which its own comment says excludes cache reads and writes, and its LangChain module writes the same aws.bedrock provider name for ChatBedrock. I left the README naming only Anthropic since the PR is approved; it is a one-sentence change if a maintainer wants it here.

@openinference-factory

Copy link
Copy Markdown
Contributor

The factory recommends Approve for 23eb391 and labeled this pull request factory-approved. Read the review.

@openinference-factory openinference-factory Bot added factory-approved The factory review recommends approving and removed factory-review to be reviewed by the software factory labels Nov 5, 2026
@caroger
caroger requested a review from axiomofjoy November 5, 2026 19:03
@sohom-cs

Copy link
Copy Markdown
Contributor Author

@axiomofjoy the factory approved this on 11-05 and it merges cleanly; could you review it when you have time? I left its two non-blocking notes as they are and can change either if you'd like.

@mikeldking mikeldking removed the factory-approved The factory review recommends approving label Nov 17, 2026
@mikeldking mikeldking added factory Sends a bug to the issue-to-PR factory. Applying it triggers factory-dispatch factory-review to be reviewed by the software factory and removed factory Sends a bug to the issue-to-PR factory. Applying it triggers factory-dispatch labels Nov 17, 2026
@openinference-factory

openinference-factory Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

The factory recommends ❌ Request changes for 23eb391 and labeled this pull request factory-request-changes. Read the review · session sesn_01DV6tcB9k9vwAu7k478Sr1t

cc @mikeldking

@openinference-factory openinference-factory Bot left a comment

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.

❌ Factory review of 23eb391: Request changes

One blocking finding: on openlit 1.37+ the diff makes every LLM span record an empty input and an empty assistant reply, and the new tests pin that output.

Fit Checks Tests Blocking Non-blocking Risk Depth
✅ Pass ✅ Pass ✅ Pass ❌ 1 ⚠️ 1 ⚠️ Low ✅ Focused

Needs attention

  • ❌ Blocking: 1.37+ LLM spans get empty messages python/instrumentation/openinference-instrumentation-openlit/src/openinference/instrumentation/openlit/_span_processor.py:98
  • ⚠️ Non-blocking: zero-count skipping untested python/instrumentation/openinference-instrumentation-openlit/src/openinference/instrumentation/openlit/_span_processor.py:288
  • ⚠️ Risk (Low): side effects: openlit 1.37+ spans go from no OpenInference attributes to LLM attributes, including the empty messages above
Details

Intent: openlit 1.37+ writes gen_ai.provider.name instead of gen_ai.system. The PR maps those spans the way it maps gen_ai.system spans, in span kind, chain detection and llm.system, with gen_ai.system winning when both keys are present. It also maps openlit's cache-read, cache-write and reasoning token counts to the OpenInference detail attributes, skipping zeros (closes #4199).
Fit: _is_llm_span, _is_chain_span and _extract_llm_provider_and_system fall back to gen_ai.provider.name, and the three token-detail attributes are mapped as described. The Anthropic prompt count is passed through unfolded, which is documented in the README and a code comment. The diff changes nothing the PR doesn't claim. Issue #4199 also lists messages as missing; the PR body scopes message mapping out and says so.
Verified: tox run -e ci-openlit (openlit 1.44.0) and ci-openlit-latest (openlit 1.45.0) pass on Python 3.11: ruff format, ruff check and mypy clean; 24 passed, 1 skipped (the pre-existing test_openlit_instrumentor skip).
With main's _span_processor.py swapped into the env, the suite gives 11 failed, 13 passed, 1 skipped, as the PR body says.
ci-openlit also passes on a merge of this commit into current main (e03fde3), which brings openinference-instrumentation 0.1.79 and semconv 0.1.46; the merge is clean.
The Python reviewer ran mutations on a copy:

  • each changed behavior fails at least one test when removed: line 78, key precedence, _is_llm_span, llm.system extraction, cache read and write, and both reasoning keys;
  • zero-skipping is the exception: no test fails when it is removed.
    I reproduced the empty-message output on a real openlit OpenAI call.
    Not verified: Python 3.10 and 3.13, which CI runs (the sandbox has 3.11); openlit 1.37 to 1.43; streaming paths; openlit provider modules other than OpenAI and Anthropic, including LangChain and Bedrock; the PR's LangChain cache numbers.
    Findings without a diff line: none
    Risk: side effects low, performance none, backwards compatibility low, from the Python reviewer. Spans from openlit 1.36 and older map as before.
    The framework/embedding relabelling and the unfolded Anthropic prompt count were raised in earlier rounds; the author answered them, and they are not repeated here.
    The 11-05 review of this commit approved it. This round adds the empty-message finding, which is the deciding difference.

Graded against the review criteria.


def _is_llm_span(attrs: dict[str, Any]) -> bool:
return "gen_ai.system" in attrs
return "gen_ai.system" in attrs or "gen_ai.provider.name" in attrs

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.

Blocking. This line sends every openlit 1.37+ LLM span into _get_llm_attributes. There, parse_messages (line 202) reads only the gen_ai.content.prompt/gen_ai.content.completion span events. openlit 1.37+ doesn't emit those events: it writes gen_ai.input.messages/gen_ai.output.messages attributes instead. As a result, every such span now records an empty conversation, where on main it recorded no OpenInference attributes at all.

  • Evidence: I ran a real OpenAI().chat.completions.create through openlit 1.44.0 at this commit, with a canned "hi" reply. The span has no events, and gen_ai.output.messages holds [{"role": "assistant", "parts": [{"type": "text", "content": "hi"}], ...}]. The processor still writes llm.output_messages.0.message.content = "", input.value = {"messages": [], ...} and output.value = {"id": "c1", "messages": [{"role": "assistant", "content": ""}]}. Phoenix will therefore show the model replying with nothing.
  • Tests pin the wrong data: test_token_counts.py:235,242,259,266 assert the empty input messages and the "" content.
  • Fix, either of:
    • read gen_ai.input.messages/gen_ai.output.messages in parse_messages when the events are absent, and assert "hello"/"hi" in test_openlit_llm_span_attributes;
    • or, if message mapping stays in a follow-up, skip llm.input_messages/llm.output_messages and the messages in input.value/output.value when no content source exists, and assert that those keys are absent rather than empty.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, the 1.37+ spans came out with an empty conversation. In 05540d7 the processor reads gen_ai.input.messages and gen_ai.output.messages when either is on the span: text parts become the message content, tool_call parts the tool calls and each tool_call_response part a tool message, and input.value/output.value are built from the same messages. test_openlit_llm_span_attributes now asserts "hello" and "hi", and test_openlit_message_parts checks a tool call and its result going through openlit's Anthropic module.

# writes the same gen_ai.provider.name with a count that includes it (streamed
# ChatAnthropic), and nothing on the span tells the two apart. See the README.
prompt_details = oi.PromptDetails()
if cache_read := _int_safe(attrs.get("gen_ai.usage.cache_read.input_tokens")):

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.

Non-blocking. The PR says zero counts are skipped, and openlit does write zeros. But no test fails if the skip is removed.

  • Evidence: openlit 1.44.0's OpenAI module writes gen_ai.usage.cache_read.input_tokens = 0 for a chat completion with prompt_tokens_details.cached_tokens: 0. I confirmed this on a real SDK call: the span carries the 0, and this line correctly drops it.
  • Mutation: the Python reviewer changed this check, line 290 and line 314 to is not None, and all 13 new tests still pass. The anthropic-no-cache case doesn't cover it: the Anthropic SDK leaves the cache fields as None, which _int_safe drops anyway.
  • Rule: REVIEW.md § Always Check says tests MUST fail when the behavior they cover is removed.
  • Fix: add an openai-chat parameter to test_openlit_llm_span_token_counts with cached_tokens: 0 that expects only {PROMPT, COMPLETION}. Also add a reasoning_key: 0 case to test_reasoning_tokens_and_both_system_keys.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right, no test depended on the skip. In 05540d7 the anthropic-no-cache response reports 0 for both cache counts, which openlit writes to the span, and test_reasoning_tokens_and_both_system_keys has a 0 case for both reasoning keys, so changing any one of the three checks to is not None fails a test. I used the Anthropic case rather than a second OpenAI chat case because it covers the cache-write check too.

@openinference-factory openinference-factory Bot added factory-request-changes The factory review recommends requesting changes and removed factory-review to be reviewed by the software factory labels Nov 17, 2026
@sohom-cs

Copy link
Copy Markdown
Contributor Author

@MoraVigoMalusardi could you review this, since the factory approved it on 11-05 and on main spans from openlit 1.37 and later still get no OpenInference attributes?

openlit 1.37.0 and later write the conversation as the
gen_ai.input.messages and gen_ai.output.messages attributes, JSON lists
of OTel GenAI messages with a role and parts, and no longer write the
gen_ai.prompt and gen_ai.completion values the processor reads. Their
LLM spans got an empty input and an empty assistant reply.

When either attribute is on the span, build the messages from it: text
parts become the content, tool_call parts the tool calls, and each
tool_call_response part a tool message with its tool_call_id. A value
that is not a JSON list of messages gives none instead of raising.
Spans from openlit 1.36 and older carry neither attribute and keep the
event path.

The attribute test now checks the real messages, and new cases cover a
tool call and its result, plain-text message attributes, and zero
cache and reasoning counts.
@sohom-cs
sohom-cs requested a review from a team as a code owner November 25, 2026 19:15
@sohom-cs

Copy link
Copy Markdown
Contributor Author

Correction to my earlier comment: the factory's latest review (11-17) requested changes, because spans from openlit 1.37+ had empty messages. 05540d7 now maps the gen_ai.input.messages and gen_ai.output.messages attributes.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

factory-request-changes The factory review recommends requesting changes

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

[bug] openlit: LLM spans from openlit 1.37+ get no OpenInference attributes, and cache and reasoning token counts are dropped

3 participants