Commit graph

43876 commits

Author SHA1 Message Date
mateo-berri
35176fa64a fix(guardrails): retry usage upserts only on connection errors
The daily guardrail metrics and usage-unit upserts are non-idempotent
increments, but the retry loop re-sent every failed row on any exception.
An ambiguous post-send failure such as a read timeout after the write had
already committed therefore stacked a second increment and inflated the
billable unit totals served by the guardrail usage endpoints.

Retry only DB_RETRY_SAFE_ERROR_TYPES (httpx.ConnectError), the same rule
the spend writer and autorouter rollup use for increment upserts, and log
any other failure once as terminal for that row while the rest of the
batch still lands.

Follows up #37225
2026-08-17 19:05:50 -07:00
Mateo Wang
4d57bf0bdd
Merge pull request #37225 from BerriAI/litellm_lit5650_guardrail_usage_units
feat(guardrails): track bedrock guardrail usage units per invocation
2026-08-17 18:55:22 -07:00
ryan-crabbe-berri
68d4ba5da5
refactor(ui): move dashboard toasts from antd message/notification onto sonner (#37207)
* refactor(ui): move dashboard toasts from antd message/notification onto sonner

Add lib/toast.ts as the single toast surface (success/info/warning/error/
fromError/dismiss) backed by sonner, with a <Toaster /> in the root layout.
fromError titles a toast from the proxy error type or the HTTP status instead
of matching prose phrases, and shows the extracted proxy message as the
description.

MessageManager and NotificationManager become thin facades over lib/toast so
the ~250 existing call sites keep working; the mutable antd instance setters,
setMessageInstance/setNotificationInstance, and the antd App/message/
notification providers in AntdGlobalProvider are gone. Prunes the eslint
suppression baseline accordingly.

* test(ui): mock the MessageManager seam in the Fallbacks tests and drop toast doc comments

AddFallbacks and FallbackSelectionForm asserted on a mocked antd message spy
that MessageManager no longer calls; they now mock the facade the components
import. Also removes the explanatory comments Greptile flagged in lib/toast.ts
and both facades.

* fix(ui): keep NotificationManager's antd config-object contract on the sonner facade

success/info/warning/error accept the { message, description, duration } object
form again (CreateMCPServer's admin-review notice uses it) and fromBackend keeps
its extra.duration seconds argument, both mapped onto lib/toast. Prunes stale
suppressions picked up by the rebase.

* feat(ui): read the proxy error type and code out of JSON envelopes embedded in string errors

Legacy networking helpers throw new Error(responseText) and callers prefix
that text, so the envelope arrives as a substring. fromError now parses the
first embedded JSON object for type/code and shows the unwrapped message in
its place, so those toasts get a status title (Request Error, Not Found) and
a readable description instead of raw JSON.
2026-08-17 18:22:41 -07:00
Mateo Wang
b69068c290
Merge pull request #26900 from BerriAI/litellm_model-deprecation-alerts-55bc
feat(proxy): proactive model deprecation alerts and `/model/deprecations` endpoint
2026-08-17 18:15:20 -07:00
tin-berri
b20314efcf
fix(shadow_eval): schema-constrain the judge verdict like the classifier (#37239) 2026-08-17 18:12:07 -07:00
tin-berri
1648273469
feat(ui): configure the auto router's heuristic scorer from the Admin UI (#37216)
* feat(ui): configure the auto router's heuristic scorer from the Admin UI

The complexity router has always read tier_boundaries, token_thresholds and
dimension_weights from its config, and /model/new already persists them, but the
dashboard had no control for any of the three, so tuning the scorer meant editing
config.yaml by hand.

Adds an "Advanced scoring" panel to the classification section, shown whenever the
scorer actually runs: on a heuristic router, and on an LLM classifier that falls back
to the heuristic. An untouched knob is omitted from the payload, so a router keeps
tracking the shipped defaults instead of freezing today's numbers.

The three keys join MANAGED_COMPLEXITY_ROUTER_KEYS, so the edit modal now rebuilds
them from form state rather than carrying the stored copy through. That makes
hydration load-bearing, and it hydrates an absent knob to undefined rather than to
the defaults, so an untouched save cannot pin a router that was tracking them.

The "How Classification Works" card now reads the configured boundaries instead of
hardcoding 0.15 / 0.35 / 0.60, which would otherwise start lying the moment an
operator changed them.

* test(complexity_router): pin the dashboard scorer defaults against config.py

The Admin UI keeps its own copy of the boundary, threshold and weight defaults to
prefill its controls. The copy is display only, since an untouched knob is omitted
from the payload, so drift shows a stale placeholder rather than pinning a router.
Nothing caught that drift before, and a blank or dead control is worse, so the two
copies and the dimension key set are pinned against each other here.

* fix(ui): surface out-of-order scorer thresholds as an error, not a hint

Boundaries that decrease make the tiers between them unreachable, which silently
changes where traffic goes, so amber body text undersold it. Saving stays allowed:
a router configured this way in config.yaml would otherwise become uneditable in
the UI for every unrelated change.

* fix(test): search the default-model picker instead of trusting option order

The pinned model is appended after every model the presets contribute, and that list
has reached 11, so the option fell outside the virtualized dropdown's rendered slice
and the two default-model-pin cases failed on staging. CI only runs them when this
file is touched, which is why they went unnoticed. Searching for the model filters
the list to it, so the cases no longer depend on how long the preset list grows.

* revert(test): drop the dashboard scorer defaults parity test

It parsed TypeScript from Python with a hand-rolled brace matcher and a numeric
literal regex, which is not a mechanism this repo should carry: two review rounds
went into fixing the parser rather than the feature. The UI copy of the defaults is
display only, since an untouched knob is omitted from the payload, so drift shows a
stale placeholder and cannot pin a router.

* fix(ui): clamp the scorer inputs and drive the panel from one group spec

min and max are inert attributes on a text input, so the fields accepted a weight of
999, a boundary of -50, and Infinity, and persisted them into the router config.
Values are now clamped on commit and non-finite input is refused.

The three sections were near copies of each other, so they now render from a single
group spec, which also removes the triplicated warning logic.

Moves the scorer constants and types into heuristic_scoring_knobs, the leaf module.
Reading them back through ComplexityRouterConfig was a cycle, so the top-level
DIMENSION_KEYS.map in the panel ran while the constant was still undefined and every
test importing it failed to collect.

* feat(ui): serve the scorer defaults from the proxy instead of mirroring them

The dashboard kept its own copy of DEFAULT_TIER_BOUNDARIES, DEFAULT_TOKEN_THRESHOLDS
and DEFAULT_DIMENSION_WEIGHTS to prefill the Advanced scoring controls. Two copies of
one fact, and the earlier attempt to police the gap parsed TypeScript from a Python
test, which was worse than the problem.

GET /public/complexity_router/scorer_defaults now returns them, following the
/public/providers/fields pattern: a typed response model, the dashboard fetching it
through a react-query hook next to useProviderFields. The controls and the "How
Classification Works" card both read that, so a recalibration of the defaults can no
longer leave the form stating numbers the router stopped using.

The dimension set now comes from the proxy too, so a dimension added backend-side
renders without a dashboard change, under its raw key until it is given a label.
Hydration keeps a stored dict exactly as stored rather than filling it from a local
copy, since the backend already defaults any key omitted at scoring time.

* fix(types): type the scorer defaults response as Mapping, not dict

LIT001 gates mutable collections in annotations, and the three dict fields tripped it.
Mapping is what the codebase already uses for a read-only map on a response model, and
the endpoint hands the config constants over directly rather than copying them into a
fresh dict, which would have traded the LIT001 hit for a LIT002 one.

* test(ui): stub the scorer defaults request for the auto-router tree

The Advanced scoring panel and the classification card read the shipped defaults over
the network, so every render of that tree in a test paid for a request jsdom cannot
serve. That was enough to push the slowest default-model-pin case past its 30s timeout
on CI, where the suite runs 14 forks in parallel.

One fixture in tests/mocks, pulled in by a single vi.mock line per test file, rather
than the same stub pasted into each of the seven that render the tree.

* fix(ui): tell a failed scorer-defaults load apart from a slow one

The panel read only the query's data, so a permanent failure was indistinguishable
from a request still in flight and it sat on "Loading the shipped defaults..." for
good. It now branches on the query state: pending says loading, an error says so and
offers a retry, and the values the router already overrides stay visible and editable
either way.

Two more places had the same flaw. The classification card silently dropped the tier
ranges it used to always show, and now says they could not be loaded. The weight total
was summed over whatever keys were present, so a failed load made it state a total
built from the overrides alone; a total is only shown when the dimension set is known.
2026-08-18 01:10:13 +00:00
mateo-berri
7017df5732 fix(alerting): back off a day after a deprecation pass raises and label the alert in the UI
A pass that raises (a missing Slack webhook, say) now waits the daily interval instead of logging the
same exception every 30 seconds, and the Admin UI alerting settings list the new alert type so it can be
toggled like the others
2026-08-17 17:57:37 -07:00
tin-berri
e2d8fc919f
feat(complexity_router): operator-defined tier sets for the LLM classifier (#37226) 2026-08-17 17:57:30 -07:00
ryan-crabbe-berri
6e9a3b50c3
test(cli): use example.com placeholder host in base-url trailing slash test (#37240)
The trailing-slash normalization test used gateway.litellm-sandbox.ai as
its base URL. Swap it for gateway.example.com so the test file does not
reference a real-looking hostname. The test is fully mocked, so the host
value has no effect on what is exercised.

Co-authored-by: yuneng-jiang <yuneng@berri.ai>
2026-08-18 00:52:10 +00:00
Bruno Felthes
dc54b16d3c
fix(fireworks): skip accounts/ rewrite for FW-* Foundry deployment ids
resolve_fireworks_resource_name prefixes bare names with
accounts/fireworks/models/ (or routers/ for *-fast). Azure AI Foundry
hosts Fireworks models under deployment ids like FW-Kimi-K3; rewriting
those yields 404 DeploymentNotFound.

Leave names that already start with FW- unchanged. Native Fireworks
short names still get the accounts/ path.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 21:43:24 -03:00
mateo-berri
ae23bf85d2 fix(guardrails): retry failed daily metrics and usage unit upserts with backoff
A transient DB error during the spend log flush dropped that batch's guardrail
metrics and usage unit rows for good. Retry only the rows that failed, up to 3
times with 1s/2s/4s backoff, mirroring the daily spend writer, and inject the
sleep so tests stay fast. Lowers the lint budgets the refactor freed up
2026-08-17 17:41:57 -07:00
mateo-berri
308865bad0 fix(alerting): claim the deprecation lock only with content and retry failed claims next poll
An empty pass no longer holds the daily lock, a False lock claim (held or redis
error) is retried on the next 30 second poll instead of sleeping a day, and a
sent alert is stamped in the shared cache for a day so sibling pods and restarts
stay quiet
2026-08-17 17:38:05 -07:00
yuneng-jiang
175b639bc3
Merge pull request #37227 from BerriAI/litellm_/resolve-stacked-pr-conflicts-e95c06
test(ui): settle the in-flight search before the loading tests end
2026-08-17 17:34:41 -07:00
Mateo Wang
9cd7696156
Merge pull request #37229 from BerriAI/litellm_comprehend_medical_passthrough
feat(proxy): add Amazon Comprehend Medical passthrough provider
2026-08-17 17:25:01 -07:00
mateo-berri
8ba2263d4c perf(guardrails): aggregate usage units in one sorted pass
The flush and the usage endpoints summed units with a scan per distinct key,
quadratic in rows times keys; group sorted rows instead. Skip payloads without
a request_id like the metrics path, type the flush key as a NamedTuple, and drop
the (guardrail_id, date) index that the primary key already covers
2026-08-17 17:19:05 -07:00
tin-berri
5277dab4f2
fix(shadow_eval): copy messages before router call and raise judge output cap (#37232)
* fix(shadow_eval): copy messages before router call and raise judge output cap

* fix(shadow_eval): lead failure detail with location and pin post-failure continuation
2026-08-17 17:10:52 -07:00
mateo-berri
7f42c84f57 fix(passthrough): dispatch Comprehend Medical logging on the provider tag only
Config-driven pass_through_endpoints pointed at a comprehendmedical.*.amazonaws.com
target were being claimed by the Comprehend Medical logging handler through the
hostname arm, which overrode their operator-set cost_per_request and relabeled
their spend rows. Only the built-in /comprehendmedical routes tag the provider,
so match on that alone.

Also mirror /comprehendmedical into the helm ingress and terraform gateway
prefix lists that hand-copy gateway/routes/allowlist.py
2026-08-17 17:07:31 -07:00
Mateo Wang
e81cedb13a
Merge pull request #37231 from BerriAI/litellm_lit5696_system_hoist_writeback
fix(anthropic): fold guardrail-modified leading system rows into top-level system param
2026-08-17 17:05:42 -07:00
mateo-berri
5437139b94 chore(guardrails): sync lazy OpenAPI snapshot and dashboard types for usage units
Regenerates the guardrails and policy_engine fragments of the lazy OpenAPI
snapshot for the usage-unit fields, regenerates schema.d.ts from it, and
exports DailyGuardrailUsageUnitsRepository next to its sibling repositories
2026-08-17 16:43:58 -07:00
mateo-berri
d9bd678f64 fix(gateway): expose comprehendmedical passthrough routes on the gateway component 2026-08-17 16:34:08 -07:00
Mateo Wang
b70df5bdf6
Merge pull request #37194 from BerriAI/litellm_azure_di_native_ocr_format
feat(ocr): return Azure Document Intelligence's native payload from /v1/ocr via req_format=native
2026-08-17 16:30:27 -07:00
mateo-berri
0cbec3f05c refactor(anthropic): drop bare generics and Any from new guardrail fold helpers 2026-08-17 16:17:00 -07:00
Mateo Wang
50e71313b7
Merge pull request #37219 from BerriAI/litellm_internal_copy_37077
fix(batches): price a retrieved batch from its deployment's model and rates (internal copy of #37077)
2026-08-17 16:07:39 -07:00
mateo-berri
b7593a99c7 fix(guardrails): keep remaining usage upserts when one write fails
Per-row guards in the daily metrics and usage unit flush so a single DB error no longer drops the rest of the batch, plus removal of narrating comments flagged in review
2026-08-17 16:01:53 -07:00
mateo-berri
a972f172d7 fix(anthropic): fold guardrail-modified leading system rows into top-level system param 2026-08-17 15:57:46 -07:00
Mateo Wang
77b7c6c40c
Merge pull request #37198 from BerriAI/litellm_lit5660_batches_limit_400
fix(proxy): reject out-of-range limit on GET /v1/batches with OpenAI-parity 400
2026-08-17 15:53:46 -07:00
mateo-berri
7ba78c9ea9 fix(ocr): reject invalid req_format values as 400 on the SDK path 2026-08-17 15:49:18 -07:00
Mateo Wang
96d2ceef3b
Merge pull request #31435 from kingdoooo/litellm_bedrock_output_bucket
fix(bedrock): validate file-content retrieval against the configured output bucket (#26335)
2026-08-17 15:48:56 -07:00
mateo-berri
915a1cabcd feat(proxy): add Amazon Comprehend Medical passthrough provider 2026-08-17 15:44:06 -07:00
Mateo Wang
a6de0736e1
Merge pull request #37201 from BerriAI/litellm_fix_batches_404
fix(proxy): return 404 instead of 500 for unresolvable batch and file ids on /v1/batches
2026-08-17 15:43:49 -07:00
Mateo Wang
6858fda3ee
Merge pull request #37218 from BerriAI/litellm_lit5675_rust_param_leak
fix: stop rust flag from leaking into upstream provider request bodies
2026-08-17 15:43:31 -07:00
Yuneng Jiang
a7baf1d8e2
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_/resolve-stacked-pr-conflicts-e95c06 2026-08-17 15:41:52 -07:00
Yuneng Jiang
3cc16de0d2
test(ui): settle the in-flight search before the loading tests end
Both loading tests mock searchToolQueryCall as a promise that resolves on a
timer, assert the loading affordance, then return with that promise still in
flight. When the worker outlives the file's jsdom environment, the component's
setIsLoading(false) runs against a torn-down window, and React reports
"ReferenceError: window is not defined" as an unhandled rejection. Vitest counts
that as an error, so ui-unit-tests fails the job while reporting every one of
its 7351 tests as passed.

Awaiting the settled state keeps both assertions and leaves nothing pending at
teardown.
2026-08-17 15:41:31 -07:00
mateo-berri
e736b59802 test(cost): type the batch_cost_calculator model_info literals instead of suppressing 2026-08-17 15:40:29 -07:00
mateo-berri
91c12ec810 test(proxy): run managed passthrough limit tests in CI 2026-08-17 15:39:46 -07:00
Mateo Wang
2975265f0b
Merge pull request #35013 from BerriAI/litellm_openrouter_stream_usage_cost
fix(streaming): track provider-reported cost when caller omits include_usage
2026-08-17 15:38:12 -07:00
Itai Modiano
fbd09ca27d
perf(guardrails): stop sending the conversation twice in the noma v2 payload (#36764)
The Noma guardrail sends the conversation to the scanner in `inputs`. It
also forwarded `request_data` whole, which repeats that same conversation
under `messages` (or `input` on the responses API), and attached
`logging_obj.model_call_details`, which repeats it a third time.

For image-heavy calls that duplication is most of the request. A
production scan of a request carrying base64 images measured 100MB total,
of which 94.8MB was `request_data` against 5.1MB of `inputs` - the proxy
was uploading ~95% redundant bytes, and paying to serialize them.

Drop `messages` and `input` from `request_data` and from
`model_call_details`. This is a denylist rather than an allowlist on
purpose: every other key is still forwarded untouched, so a scanner-side
change that starts reading a new `request_data` key needs no matching
release of this hook. The removed keys are ones the scanner never reads -
it takes context only from metadata, litellm_metadata,
provider_specific_header, litellm_session_id/trace_id/call_id, stream,
response/responses ids, and litellm_logging_obj.complete_streaming_response,
all of which still pass through.

The conversation still reaches the scanner in full via `inputs`, so no
detection coverage changes.

Trimming happens before serialization, so the duplicate is never encoded.

Existing payload tests asserted the duplication; they now assert the trim
while keeping what they originally guarded - deep-copy semantics and the
unpicklable-object (uvloop.Loop) regression.
2026-08-17 15:37:17 -07:00
mateo-berri
5a11fe141e fix(batches): price poller-tracked batches from the deployment's registered rates 2026-08-17 15:36:39 -07:00
Mateo Wang
ce20c282e9
Merge pull request #37197 from BerriAI/litellm_gemini_36_flash_introductory_pricing
fix(gemini): price gemini 3.6 flash at Google's introductory rates on every service tier
2026-08-17 15:32:08 -07:00
Mateo Wang
67635d832e
Merge pull request #36638 from cu-aaii/litellm_redaction_deepcopy_aborts_success_logging
fix(logging): stop deepcopying results redaction cannot redact
2026-08-17 15:22:07 -07:00
mateo-berri
55e80849d1 feat(guardrails): track bedrock guardrail usage units per invocation 2026-08-17 15:18:53 -07:00
yuneng-jiang
6a0bd0dffb
Merge pull request #37019 from BerriAI/litellm_mock_assertion_strength
test(ui): assert what collaborators are called with, not merely that they were
2026-08-17 15:18:21 -07:00
tin-berri
c1aae9d723
feat(shadow-eval): name the shadowed key in job responses and the UI headline (#37221) 2026-08-17 22:12:59 +00:00
Yuneng Jiang
6db82c0d15 test(ui): assert what collaborators are called with, not merely that they were
A bare toHaveBeenCalled() passes no matter what the caller passed, so the CSV
export could serialize the wrong rows, write the wrong content type, and name
the file wrong while its test stayed green.

Strengthens the load-bearing cases in three files onto the arguments that carry
the behaviour: the rows handed to the CSV serializer, the blob content type, the
anchor that gets attached and cleaned up, and the specific message each
validation failure shows the user. Two of the discount and margin tests
previously asserted the same bare call for different validation failures, so
neither could tell the two apart.

Each rewrite was proven by mutating the source it covers and confirming the test
goes red where the bare assertion stayed green.
2026-08-17 15:09:06 -07:00
yuneng-jiang
0d3dd8b4e1
Merge pull request #37018 from BerriAI/litellm_testing_library_lint_rules
test(ui): gate dashboard test assertions with testing-library and jest-dom rules
2026-08-17 15:09:02 -07:00
yucheng-berri
7984ae4636
fix(mcp): scope authorization server issuer for named MCP servers (#37204)
* fix(mcp): scope authorization server issuer

Generated with AI

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(mcp): keep the bare-origin issuer when no server was named

The scoped issuer must key off whether the request actually carried a server
name. _build_oauth_authorization_server_response rebinds mcp_server_name when
root discovery resolves the single configured OAuth2 server, so gating on the
rebound value also scoped /.well-known/openid-configuration, whose document is
served from the bare origin and whose issuer must stay the bare origin

Adds the named-server regression test for the reported mismatch, restores the
bare-origin assertion, and covers the OIDC document

* test(mcp): type the delegate_auth_to_upstream helper parameter

* refactor(mcp): bind the discovery issuer to a local before building the response

---------

Co-authored-by: Irosh <15094153+irosh-colombage-ZocDoc2@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-08-17 15:06:12 -07:00
Mateo Wang
e8154c3e4c
Revert "fix(mcp): scope authorization server issuer" (#37220) 2026-08-17 15:06:01 -07:00
ryan-crabbe-berri
427ed9e2d1
fix(ui): search every user in the Usage page user filter (#37206)
The User Usage view handed EntityUsage a static entityList holding only
the first /user/list page, so its filter could only find the 50 most
recently created users and anyone beyond that page, including users
with spend in the selected period, was unreachable

Add a self-contained UserDropdown that owns useInfiniteUsers (server-side
search plus load-more, mirroring TeamDropdown) and use it both as the
User Usage filterSlot and for the Global Usage user filter. Resolve a
selected user that is outside the loaded page by id so its label
survives view round-trips. Drop the now dead single-select branch from
UsageExportHeader
2026-08-17 15:00:38 -07:00
mateo-berri
678a636846 Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_internal_copy_37077
# Conflicts:
#	tests/test_litellm/batches/test_batch_utils.py
2026-08-17 14:57:29 -07:00
mateo-berri
fbc5c1c3d4 refactor(streaming): copy usage-only chunk instead of mutating the parameter 2026-08-17 14:52:14 -07:00