Skip to content

feat(openrouter): record upstream provider in hidden params and logging payload - #46232

Closed
BeWayllar wants to merge 8 commits into
BerriAI:mainfrom
BeWayllar:feat/openrouter-upstream-provider
Closed

BeWayllar wants to merge 8 commits into
BerriAI:mainfrom
BeWayllar:feat/openrouter-upstream-provider

Conversation

@BeWayllar

@BeWayllar BeWayllar commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

How it solves it:

  • Records it as the upstream_provider hidden param on every response
  • Non-streaming: read next to the existing usage.cost read
  • Streaming: each chunk keeps it; the assembled response takes it from any chunk
  • StandardLoggingHiddenParams gains upstream_provider, so every logging callback receives it
  • Fields only, no judgment: nothing is computed from the value

User Flow

Before: a developer logging spend per request through OpenRouter gets a provider-reported cost in every payload, but nothing says which provider produced it, so cost variation across calls has no explanation in their own logs

  1. They send POST https://litellm-domain/v1/chat/completions with "model": "openrouter/z-ai/glm-5.3-flash", once plain and once with "stream": true
  2. Their logging callback receives a payload per call with response_cost set from OpenRouter's reported cost
  3. The payload's hidden_params carry model_id, api_base, response_cost and the usage object, and no field naming the provider that served the call
  4. To learn which provider it was, they open https://openrouter.ai/activity and match requests by hand

After: the same payloads name the provider beside the cost

  1. They send the same two POSTs
  2. Each payload's hidden_params now carries upstream_provider, the serving provider's name, next to response_cost
  3. The streaming call carries it too, on the assembled response the callback receives
  4. Which provider served each call is a fact in their own logs, with no trip to the activity page

Relevant issues

Closes #48038 (record which provider served an OpenRouter request, next to its reported cost)

Related: #16021 (provider-reported cost in streaming, now on main), #38802 (the same pass-through for DeepInfra's reported cost, a follow-up)

Pre-Submission checklist

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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Real OpenRouter calls through the LiteLLM SDK with OPENROUTER_API_KEY set, model openrouter/z-ai/glm-5.3-flash, prompt Reply with the single word: ok, max_tokens=1024, reasoning_effort="low". A custom logger records what the standard logging payload's hidden_params carry for one non-streaming and one streaming call; the same script runs at both commits with PYTHONPATH pointed at the checkout.

import asyncio, json, litellm
from litellm.integrations.custom_logger import CustomLogger

captured = []

class Capture(CustomLogger):
    def _grab(self, kwargs):
        slo = kwargs.get("standard_logging_object") or {}
        hidden = slo.get("hidden_params") or {}
        captured.append({"stream": bool(kwargs.get("stream")), "response_cost": slo.get("response_cost"),
                         "hidden_params.upstream_provider": hidden.get("upstream_provider", "<field absent>"),
                         "hidden_params.keys": sorted(hidden)})
    def log_success_event(self, kwargs, response_obj, start_time, end_time): self._grab(kwargs)
    async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): self._grab(kwargs)

async def main():
    litellm.callbacks = [Capture()]
    messages = [{"role": "user", "content": "Reply with the single word: ok"}]
    model = "openrouter/z-ai/glm-5.3-flash"
    r = await litellm.acompletion(model=model, messages=messages, max_tokens=1024, reasoning_effort="low")
    print("non-streaming content:", repr(r.choices[0].message.content))
    s = await litellm.acompletion(model=model, messages=messages, max_tokens=1024, reasoning_effort="low", stream=True)
    text = ""
    async for chunk in s:
        text += chunk.choices[0].delta.content or ""
    print("streaming content:", repr(text))
    await asyncio.sleep(2)
    print(json.dumps(captured, indent=2))

asyncio.run(main())

Before (cb94567)

Non-streaming

  1. PYTHONPATH=. python proof_upstream_provider.py (first call)
  2. Output: content 'ok', response_cost 1.48e-06, hidden_params.upstream_provider <field absent>; hidden_params.keys are additional_headers, api_base, batch_failed_requests, batch_models, batch_successful_requests, cache_key, litellm_model_name, litellm_overhead_time_ms, model_id, response_cost, usage_object

Streaming

  1. Same script (second call, stream=True)
  2. Output: content 'ok', response_cost 1.48e-06, hidden_params.upstream_provider <field absent>; the same eleven keys

After (244e0c1)

Non-streaming

  1. PYTHONPATH=. python proof_upstream_provider.py (first call)
  2. Output: content 'ok', response_cost 1.48e-06, hidden_params.upstream_provider InferenceNet; hidden_params.keys now also include upstream_provider

Streaming

  1. Same script (second call, stream=True)
  2. Output: content 'ok', response_cost 1.48e-06, hidden_params.upstream_provider InferenceNet; upstream_provider present among the keys

Both runs routed to the same provider at the same reported cost; the field is what changed.

Type

🆕 New Feature

Caveats (if any)

Low

  • The value is OpenRouter's provider display name per call, not the endpoint: quantization and endpoint id are not in the response, so a consumer resolves the name against the model's endpoint listing
  • Streaming relies on the chunks carrying provider; a chunk without it is skipped and the field is simply absent, never wrong
  • Only the OpenRouter chat path sets the field in this PR; Responses and other providers are untouched

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

…ng payload

OpenRouter returns the provider that actually served a request as the
top-level `provider` field, on the response body and on every streaming
chunk. Since cost for openrouter/* became provider-reported per call, the
same model's cost varies call to call and nothing in the logging payload
said why. Pass the field through as the `upstream_provider` hidden param
and carry it into StandardLoggingHiddenParams for both non-streaming and
streaming completions.

- types/utils.py: StandardLoggingHiddenParams gains upstream_provider
  (ReadOnly[str | None]); the three literal constructions set it to None.
- openrouter/chat/transformation.py: transform_response reads the body's
  `provider` next to the existing usage.cost read; chunk_parser records it
  on each parsed chunk.
- streaming_handler.py: _ParsedChunkHiddenParams/_provider_hidden_params
  forward it onto the chunks returned to the caller.
- streaming_chunk_builder_utils.py: the assembled response takes it from
  whichever chunk carries it, without mutating a chunk's dict.

The value is OpenRouter's provider display name for that call; it names
the provider, not the endpoint. Nothing is computed from it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@CLAassistant

CLAassistant commented Oct 13, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codspeed

codspeed Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 35 untouched benchmarks


Comparing BeWayllar:feat/openrouter-upstream-provider (c188607) with main (f2118fc)

Open in CodSpeed

The strict-rule gate flagged TRY300 on chunk_parser: returning a name from
inside the try body. The base returned a call expression, which the rule
exempts. Keep the parsing and the upstream_provider hidden param inside
the try, and return from the else clause, as the rule suggests.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@codecov

codecov Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

BeWayllar and others added 3 commits October 13, 2026 11:59
…er change

Keep the cast-ok markers the discipline gate requires; remove the
narrative comments and restore the original except-clause comment.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@BeWayllar
BeWayllar marked this pull request as ready for review October 13, 2026 18:30
BeWayllar and others added 3 commits October 13, 2026 13:36
Covers the no-hidden-params branch of _with_upstream_provider that codecov
flagged, and the chunk scan skipping chunks without the field.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Resolve the conflict in litellm/llms/openrouter/chat/transformation.py
with upstream BerriAI#45388: keep the validated response mapping and the
isinstance guard on the cost, and read the top-level provider key
directly from the validated body instead of through a cast.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Resolves three end-of-file conflicts in the unit test modules where both
sides appended tests; both sets are kept. No change to the feature.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

#48038 was fixed by #49287 on main, so this pull request is closed. Reopen it if something was missed.

@github-actions github-actions Bot closed this Oct 30, 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.

[Feature]: record which provider served an OpenRouter request, next to its reported cost

2 participants