Repository navigation
Conversation
Port of BerriAI#16162 by @dhruvyad onto litellm_internal_staging. OpenRouter sends a usage chunk (including a provider-reported cost field) after the finish_reason chunk. Previously the stream handler raised StopIteration on the first post-finish chunk, so that usage/cost never reached the assembled response and cost tracking fell back to token-based estimates. Carry usage.cost through chunk accumulation, preserve stripped usage in _hidden_params, and propagate the provider cost into _hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] so the cost calculator uses it.
The /guardrails/usage/{overview,detail,logs} endpoints resolved guardrails only
from the litellm_guardrailstable Prisma table, so guardrails defined in
config.yaml (which live only in IN_MEMORY_GUARDRAIL_HANDLER) were invisible:
detail 404'd, overview omitted them or rendered them as Custom/Guardrail
orphans, and logs missed their logical-name alias.
Add config-owned accessors (list_config_guardrails, get_config_guardrail_by_id)
to the in-memory handler and use them in the usage endpoints, mirroring the
union/fallback already used by list_guardrails_v2 and get_guardrail_info. Also
preserve guardrail_info when storing a config guardrail (type/description were
dropped at initialize time) and read the Prisma-row / dict / LitellmParams
shapes uniformly.
Resolves LIT-2529
Addresses PR review: _to_dict special-cased LitellmParams and returned an empty dict for any other pydantic model. Switch to isinstance(value, BaseModel) so it coerces any pydantic model uniformly (BaseModel is already imported for the response models), which also drops the now-unused LitellmParams import. Behavior is unchanged for the current call sites.
…ock Invoke /v1/messages
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix(proxy): route master key to team-scoped models * fix(router): reject ambiguous admin team model pools * fix(router): cover internal-only admin model routing
… on failed re-discovery
…on_url carry-forward
…itellm_e2e_bedrock_mid_system_cache
…erriAI#33027) grok-4.3 is a third-party frontier model on Bedrock Mantle, served on the /openai/v1 base (like gpt-5.x and gemma-4), not the standard /v1 path used by open-weights models such as gpt-oss. BerriAI#31916 added the model without use_openai_responses_path, so mantle_base_segment() routed it to /v1, where Bedrock rejects the call with "Berm is not enabled for this account" (access_denied) — the model is only reachable on the frontier /openai/v1 path. Add use_openai_responses_path=true to the bedrock_mantle/xai.grok-4.3 price-map entry (both model_prices_and_context_window.json and the backup) so mantle_base_segment() returns "openai/v1", and update the registry test to assert use_openai_path is True.
…api (BerriAI#33110) * feat(guardrails): support streaming text transformation in generic_guardrail_api * chore(guardrails): address PR review feedback * fix(guardrails): fail closed on tool-call and prefix-rewrite leaks in streaming transform * fix(guardrails): address Bugbot review on streaming transform correctness * fix(guardrails): coerce holdback in handler for in-process guardrails * fix(guardrails): harden streaming transform (holdback coercion, tool-call passthrough, n>1 finish_reason) * test(guardrails): targeted _mode_matches coverage for all guardrail_mode shapes * fix(guardrails): inspect streamed tool calls and harden incremental_diff edge cases * test: move ComplianceChecker mode tests to the compliance PR * fix(guardrails): strip content from tool-call passthrough so streamed text can't bypass the transform * fix(guardrails): four correctness fixes for incremental_diff streaming path Four bug fixes on top of the OSS PR's incremental_diff streaming text transformation, all inside the incremental_diff code paths only. No existing block_only, non-streaming, or pre_call behavior is touched. Fix BerriAI#1 — Mixed content+tool_call finish_reason ordering _tool_call_passthrough_chunk now takes an optional finish_reason_per_choice map. For a choice carrying both delta.content and delta.tool_calls, finish_reason is stripped from the passthrough and recorded on the map so the final synthetic text chunk delivers it. Without this, SSE-compliant clients stopping at finish_reason drop the guardrailed text — defeating the redaction the whole feature exists for. (Greptile P1 twice, Veria.) Fix BerriAI#2 — Choice index sort in _process_streaming_transform indices/texts_to_check were derived from dict insertion order. For n>1 streams where choice 1 emits before choice 0, guardrail-returned texts aligned to the input order mapped back to the wrong choice indices on write-back — wrong text goes to wrong choice. Sort raw_by_index.keys() up front so realignment is deterministic. (Bugbot Medium.) Fix BerriAI#3 — Cross-chunk pre-tool-call text flush With default streaming_sampling_rate=5, text chunks followed by a pure tool-call chunk carrying finish_reason='tool_calls' would emit the passthrough with finish_reason before any transformed text delta had fired. Same failure mode as fix BerriAI#1 but cross-chunk. Now we flush any accumulated text via _round(is_final=False) BEFORE yielding the tool-call passthrough. (Greptile P1.) Fix BerriAI#4 — Terminator chunk for deferred finish_reason on empty mutated_text _build_transform_chunk returned None early when mutated_text_per_choice was empty. If a mixed content+tool_call chunk had deferred its finish_reason (via fix BerriAI#1) and the guardrail then suppressed the text (empty return), the deferred finish_reason was never delivered. Now on is_final=True with empty mutated_text_per_choice, we emit a terminator carrying finish_reason per choice from finish_reason_per_choice. (Bugbot High.) Also normalized Optional[X] → X | None across the OSS PR's added surface via ruff UP045 autofix to keep the strict-rule gate within budget. Pure mechanical typing style change, no semantic effect. Regression tests for all four fixes: - test_mixed_chunk_finish_reason_arrives_after_transformed_text (BerriAI#1) - test_text_flush_precedes_tool_call_passthrough (BerriAI#3) - test_final_finish_reason_flushed_when_guardrail_suppresses_text (BerriAI#4) - test_transform_sends_texts_sorted_by_choice_index (BerriAI#2) All fixes reachable only when streaming_transform_mode == 'incremental_diff' is configured (via _run_incremental_transform_stream) or when a StreamTransformSink is present (via _process_streaming_transform). Verified scope-clean: no changes to block_only, non-streaming, pre_call, moderation, or sibling guardrails. --------- Co-authored-by: Marton Schneider <marton@schneider.co.nl>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…itellm_websearch_responses_interception
…_system_cache test(e2e): cover model-aware mid-conversation system handling on Bedrock Invoke /v1/messages
…ld hook is the provenance-guarded writer
An empty upstream delta (e.g. Bedrock Converse's empty reasoning delta
mid-thinking-block) falls through the translate fallback as
text_delta {"text": ""} at the open thinking block's index, crashing
Anthropic SDK clients like Claude Code with "Content block is not a
text block". Payload-less deltas carry no information, so never emit
them.
…ilter startup index The semantic tool filter builds its index by listing every MCP server without per-user credentials, so servers needing per-user auth (interactive OAuth tokens, user-scoped env vars) reject the anonymous tools/list and contribute zero routes. Request-time expansion resolves that auth, so filter_tools received tools the router could never select: an empty index failed open N->N (past 128 tools OpenAI rejects the request outright) and a partial index matched only unavailable tools, stripping every tool from the request. filter_tools now syncs missing tools into the router before matching (building the router when absent) behind an asyncio lock so each tool embeds once, and falls back to the full tool list when matches map to no available tool, consistent with the zero-match fallback. Context-window overflows keep failing closed.
Extracts the adapter stream's closed delta-type set into StreamingContentBlockDeltaType, shared by the translate layer's return type and an exhaustive match in _delta_payload_field, so adding a new delta type without handling it in the emission gate fails type-checking instead of being silently dropped.
…dict allocation in the fast path
…sts/e2e (BerriAI#32548) * test(claude_code): move the Claude Code compatibility matrix under tests/e2e Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci(claude_code): drop the CircleCI compat PR gate; the matrix runs in the scheduled e2e suite instead Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: restore the upload-coverage job dropped by mistake with the compat gate Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(e2e/claude_code): print rate-limit summary on failed compat runs and fix stale run_daily.sh header comments * test(claude_code): assert fine-grained tool streaming via input_json_delta instead of an event-count floor Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: mateo <mateo@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
The preemptive-401 gate for auth_type=oauth2 MCP servers keyed the challenge on whether an Authorization header was present (not oauth2_headers). Because the header parser classifies any Authorization bearer as an OAuth token before the target server is resolved, a LiteLLM virtual key presented as Authorization: Bearer sk-... suppressed the challenge on a gateway-managed authorization_code server; the session then opened with no upstream token and tools/list masked the failure as 200 with an empty tool list. The same gate also wrongly challenged client_credentials (M2M) servers, which the gateway authenticates by minting its own token at egress. The decision is per oauth2 sub-mode, not per header. Gateway-managed modes never receive a client-supplied upstream token: client_credentials mints at egress so it is never challenged, and gateway-managed interactive (authorization_code, non-delegate) is challenged whenever no stored per-user token exists, regardless of any bearer. Only the delegate/upstream-PKCE mode, where a present bearer genuinely is the upstream token, keeps keying on the Authorization header. oauth2_headers itself is left untouched so the delegate/passthrough egress paths that forward the client bearer are unchanged.
…e-401 gate Grafted from PR BerriAI#33582 (closing as superseded by this PR): drives handle_streamable_http_mcp with real MCPServer objects, parametrized over a stamped client_credentials row and a legacy unstamped M2M-shape row; both must reach the session manager without the per-user token store being consulted
…rriAI#33312) A `lite login` token 429'd with "Budget has been exceeded! Max budget: 0.25" even when no budget was configured anywhere. cli_poll_key stamped the minted CLI session token with litellm.max_ui_session_budget ($0.25) as a fallback whenever the user and team had no budget of their own. That cap was designed for the Admin UI "Test Key" chat pane; the CLI reused the same session-token machinery, so it inherited a playground-sized budget baked into the encrypted token at login (unchangeable without re-login), which trips fast under real CLI/agent use. The cap is also redundant: the token already carries user_id and team_id, so the real user/team budgets are enforced independently at request time. Pass max_budget=None so the CLI token is governed only by those real budgets, and drop the now-dead user/team budget lookups. The UI login token's guard (get_experimental_ui_login_jwt_auth_token) is untouched.
* test(e2e): read datadog log delivery back from the real datadog api (BerriAI#33604) * test(e2e): read datadog log delivery back from the real datadog api * test(e2e): compare datadog-read cost with math.isclose, not bit-equality The response_cost now round-trips through DataDog's attribute indexing pipeline, whose float serialization is not guaranteed to preserve the exact bit pattern the proxy shipped. rel_tol=1e-9 (equal to 9 significant digits) still fails on any real cost discrepancy while tolerating representation drift. Addresses the Greptile P2 on this PR. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(e2e): widen the duplicate-settle window to 30s for real DataDog Against the local sink one poll interval (5s) after the first hit was enough to catch a same-call duplicate, because both events arrived in the same flush batch. Against real DataDog, ingestion jitter can make one call's two events searchable tens of seconds apart, so a 5s settle could let the LIT-4447 duplicate slip past the exactly-one assertion. The reader now keeps re-reading for DD_SETTLE_SECONDS (default 30s, env-overridable via E2E_DD_SETTLE_SECONDS) after the first event appears, returning early only when a duplicate is already visible - more waiting cannot clear it. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(e2e): point UI tests at dashboard service; register complexity router Stage gateway 404s /ui; the Next.js dashboard is litellm-ui:3000. Drive playwright against E2E_UI_BASE_URL and wait on login placeholders after client render. Register complexity-smart-router via /model/new when the proxy does not already list it so stage matches compose config * docs(e2e): clarify E2E_UI_BASE_URL should be ALB when ingress splits UI * docs(e2e): prefer single path-routing host for control plane and UI CONTROL_PLANE and UI already default to PROXY_BASE_URL; clarify that stage should set one ALB host rather than three endpoints * fix(e2e): always capture complexity router model_id for teardown Split /model/new from the data-plane wait so a propagation timeout still deletes the control-plane registration (greptile orphan-model concern) * fix(e2e): click exact Login button so SSO control is not matched Playwright strict mode matched both Login and Login with SSO * fix(router): score complexity by difficulty not request length The LLM classifier prompt treated short wording as SIMPLE, so probes like "Is P equal to NP?" stayed on the SIMPLE backend even though the classifier ran. Judge intellectual difficulty so short hard questions route higher * fix(e2e): open key edit via Key ID and wait for team models Key Alias text is not the row open control on the virtual keys table; KeyInfoView opens from the Key ID button in that row. Also wait for a real team model in the edit Models dropdown so we do not race the async availableModels fetch that only has All Team Models on first paint * fix(e2e): keep settled DD events on empty search; bump mcp for OSV Do not let a transient empty DataDog search wipe events already seen in the settle window (Greptile P1). Make the logs-search from window env-overridable via E2E_DD_SEARCH_FROM (Greptile P2). Prefer the mono Key ID button when opening key edit. Bump mcp 1.26.0 -> 1.28.1 so OSV clears the three high GHSA findings on the staging PR * revert: drop mcp lock bump from e2e staging PR OSV mcp upgrade is unrelated to the e2e fixes; leave the dep pin alone --------- Co-authored-by: yucheng-berri <yucheng@berri.ai> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…_gpt_big3 test(e2e/claude_code): add GPT-5.6 Sol/Terra/Luna columns for OpenAI, Azure OpenAI, and Bedrock Mantle
…enge_mode_aware fix(mcp): make the preemptive-401 OAuth challenge decision mode-aware
…#33628) The policy attachment form fetched /team/list with the caller's own user_id, which the backend treats as a membership filter even for proxy admins. Admins only saw teams they were personally a member of, and the scope validation added in BerriAI#32131 then rejected every other valid team alias as nonexistent. Drop the user_id filter; the policies page is admin-only and /team/list without user_id returns all teams for admin roles. Fixes LIT-4199
…o shared DataTable (BerriAI#33629) * refactor(ui): migrate AI Hub, public hub, and MCP Toolsets tables onto shared DataTable * test(ui): stub skillHubPublicCall in the public model hub networking mock
…he real datadog api (BerriAI#33566) * fix(e2e): make the datadog read-back find what DataDog actually indexes Live verification of the merged BerriAI#33604 against real DataDog (us5) exposed three read-back defects that the local-sink tests could never see; all three fixes are verified against the real API: - Marker search: DataDog consumes the shipped JSON message into the event's attributes and leaves the indexed message EMPTY, so the full-text '"marker"' query matched nothing and every test failed with zero events. The query is now '*:*marker*', which scans all attributes (the marker sits in messages.content); verified to return exactly the event for the call. - Rate limit: the Logs Search API budget is 2 requests per 10s org-wide (x-ratelimit-name logs_public_search_api). Polling at POLL_INTERVAL=5s sat exactly at the limit and the reader hard-failed on the first 429. Searches now pace at DD_SEARCH_INTERVAL (10s default) and a 429 backs off and retries up to 5 times; only non-429 failures stay hard fails. - Envelope status: DataDog re-derives the indexed event status from the parsed payload's status attribute ('success') and normalizes it to its OK severity, so the assertion expects 'ok', not the shipped 'info'. Live run: chat_completions and responses pass every assertion including the exact response-cost cross-check; messages red-pins the LIT-4447 duplicate for real (one call -> two sync-sweep copies + one async batch copy, same request id, confirmed in proxy debug logs). The duplicate is race-dependent, so the pin flickers until BerriAI#33589 lands. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(e2e): datadog log delivery for streamed chat, messages, and responses Rewritten from the dd-sink version (original BerriAI#33566) to judge delivery on what real DataDog ingested, matching the merged BerriAI#33604 conversion: the dd_logs reader searches events back through the Logs Search API and the assertions validate the indexed envelope (source:litellm tag, ok status) and the StandardLoggingPayload fields under the event's attributes. Each streamed test drives one STREAMED call per route, asserts the stream actually streamed (event-stream content type, >0 chunks, no upstream error event), then pins exactly one DataDog event whose payload records stream=true, the aggregated token count, and a response_cost equal to the /spend/logs row for the call - a stream's headers ship before its cost exists, so the spend row is the cross-check anchor, and the spend row and DataDog event must also agree on total_tokens. Coverage registry: adds logging.datadog.stream.exports_metric exercised on chat_completions, messages, and responses. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Update test_datadog_log_e2e.py --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
chore(ci): promote internal staging to main
da8eb69 to
dc9297d
Compare
…tection Rebased onto current main. Keeps prior PR BerriAI#33469 intent.
|
Closing: stuck base (~100 commits / ~500 files in PR UI) after tip rebase. Clean successor opens next. |
c9d4fbf to
3a80cc4
Compare
| return data | ||
|
|
||
| async def _moderate_message(self, message: dict) -> dict: | ||
| content = message.get("content") |
There was a problem hiding this comment.
Medium: Tool-call arguments bypass LLM Guard
An attacker can place prohibited content in messages[].tool_calls[].function.arguments; this method only moderates content, so those arguments reach the provider unchanged. Include tool-call arguments in moderation and apply the same sanitization used for message content.
| raise self._unscannable_block_error(reason) | ||
| attachments = attachments[:MAX_FILE_ATTACHMENTS_PER_REQUEST] | ||
|
|
||
| for attachment in attachments: |
There was a problem hiding this comment.
Medium: Unbounded attachment scan fan-out
An authenticated caller can submit an arbitrary number of small inline attachments and make this loop issue one Model Armor request per attachment, consuming guardrail quota and holding the request worker for the full sequence. Add a configurable per-request attachment limit and reject excess attachments before beginning any scans.
PR overviewThis PR updates LiteLLM's Bedrock Nova 2 model detection so JP and global geo-prefixed model identifiers are recognized correctly. It also touches guardrail-related request handling paths for LLM Guard and Model Armor. There are two open security concerns. Tool-call arguments are not currently included in LLM Guard moderation, allowing prohibited content in those arguments to pass through unchanged, and Model Armor attachment scanning can be fanned out with many inline attachments by an authenticated caller. No issues have been addressed yet, so the PR still carries moderate request-abuse and guardrail-bypass risk. Open issues (2)
Fixed/addressed: 0 · PR risk: 6/10 |
Folds in the code fix orphaned by the closed base PR BerriAI#33469: - _is_nova_2_model now strips jp. and global. geo prefixes so jp.amazon.nova-2-lite-v1:0 (the renamed pricing key) is detected - docstring updated; apac. lite test fixtures repointed to a valid apac. Nova 2 SKU so legacy apac. stripping still has coverage
Folds in the code fix orphaned by the closed base PR BerriAI#33469: - _is_nova_2_model now strips jp. and global. geo prefixes so jp.amazon.nova-2-lite-v1:0 (the renamed pricing key) is detected - docstring updated; apac. lite test fixtures repointed to a valid apac. Nova 2 SKU so legacy apac. stripping still has coverage
Folds in the code fix orphaned by the closed base PR BerriAI#33469: - _is_nova_2_model now strips jp. and global. geo prefixes so jp.amazon.nova-2-lite-v1:0 (the renamed pricing key) is detected - docstring updated; apac. lite test fixtures repointed to a valid apac. Nova 2 SKU so legacy apac. stripping still has coverage
Folds in the code fix orphaned by the closed base PR BerriAI#33469: - _is_nova_2_model now strips jp. and global. geo prefixes so jp.amazon.nova-2-lite-v1:0 (the renamed pricing key) is detected - docstring updated; apac. lite test fixtures repointed to a valid apac. Nova 2 SKU so legacy apac. stripping still has coverage
Folds in the code fix orphaned by the closed base PR BerriAI#33469: - _is_nova_2_model now strips jp. and global. geo prefixes so jp.amazon.nova-2-lite-v1:0 (the renamed pricing key) is detected - docstring updated; apac. lite test fixtures repointed to a valid apac. Nova 2 SKU so legacy apac. stripping still has coverage
Folds in the code fix orphaned by the closed base PR BerriAI#33469: - _is_nova_2_model now strips jp. and global. geo prefixes so jp.amazon.nova-2-lite-v1:0 (the renamed pricing key) is detected - docstring updated; apac. lite test fixtures repointed to a valid apac. Nova 2 SKU so legacy apac. stripping still has coverage
Relevant issues
Related to #33211 (jp geo inference id for Nova 2 Lite). This PR is the detection-path fix, not the pricing-map key rename.
Companion pricing PR: #33470 (salvage of #33218, credit @vakudo) — renames the invalid pricing-map key
apac.amazon.nova-2-lite-v1:0→jp.amazon.nova-2-lite-v1:0.Linear ticket
Pre-Submission checklist
@greptileaito re-request a review after pushing changes)Screenshots / Proof of Fix
Unit tests only.
_is_nova_2_model(\"jp.amazon.nova-2-lite-v1:0\")andglobal.amazon.nova-2-lite-v1:0(plusbedrock/converse/jp.../global...routed forms) now return True. Lite map_openai_params / supported-params fixtures updated off the invalidapac.amazon.nova-2-lite-v1:0id (Greptile note on #33470).Type
🐛 Bug Fix
Changes
_is_nova_2_modelwithjp.andglobal.jp.amazon.nova-2-lite-v1:0apac.pro-preview assertion so prefix stripping remains coveredFinal Attestation