Repository navigation
feat(auto-router): show the routed model and session savings in Claude Code and Codex - #40330
Conversation
|
@greptileai can you reply here with a score and why that score? |
|
bugbot run |
|
Confidence score: 4/5 This is a strong, well-scoped implementation:
I’m not giving 5/5 yet because the required CI status is still pending, the PR is stacked on #40319, and the documented operational caveats (rollup lag, Codex trust flow, and outstanding litellm-docs documentation) still need to be validated or completed. I found no blocking correctness issue in the implementation reviewed. |
Greptile SummaryThis PR adds key-scoped auto-router session reporting and surfaces routed-model and session-savings information in Claude Code and Codex. It also persists per-turn baseline labels, installs the shared status-line script atomically, pins resumed Claude sessions to the router model, and restores
Confidence Score: 4/5The PR is not yet safe to merge because The previous baseline-label, repository-access, docstring, credential-scoped cache, and atomic-script findings are fixed in the current code. The earlier compatibility finding is also fixed because Files Needing Attention: litellm/proxy/client/cli/commands/auth.py
|
| Filename | Overview |
|---|---|
| litellm/proxy/client/cli/commands/auth.py | Restores login --config-claude with static-token configuration, but returns before configuring when credential persistence fails. |
| litellm/proxy/management_endpoints/auto_router_endpoints.py | Adds a key-scoped auto-router session endpoint using the repository layer and persisted baseline metadata. |
| litellm/repositories/autorouter_session_repository.py | Encapsulates lookup of the latest session rollup for the caller’s exact key and session. |
| litellm/proxy/client/cli/commands/statusline_script.py | Implements sanitized routed-model and savings rendering with credential-scoped caching. |
| litellm/proxy/client/cli/commands/claude_settings.py | Installs the status-line script and performs owner-only atomic settings updates while preserving configuration ownership. |
| litellm/proxy/db/autorouter_session_rollup.py | Persists per-turn baseline-model counts so historical savings retain the correct comparison label. |
Comments Outside Diff (1)
-
litellm/proxy/client/cli/commands/auth.py, line 817-821 (link)Claude configuration silently skipped
If credential persistence returns
CredentialNotSavedorCredentialNotRecorded,_finish_loginreturns before honoring--config-claude. The login can therefore mint a usable key but silently leave Claude Code unconfigured, even though the requested setup had enough information to proceed. Configure Claude before this persistence-dependent return, or clearly report that the configuration was skipped.
Reviews (4): Last reviewed commit: "feat(auto-router): show routed model and..." | Re-trigger Greptile
| rows: Final = _SESSION_ROWS.validate_python( | ||
| await _query_raw(prisma_client, AUTOROUTER_SESSION_SQL, user_api_key_dict.api_key, session_id) or () |
There was a problem hiding this comment.
This handler calls _query_raw directly, violating the repository requirement that request paths use the approved key, team, or user helpers
Rule Used: What: In critical path of request, there should be... (source)
There was a problem hiding this comment.
Fixed in 6d0b48c: the endpoint now goes through AutoRouterSessionRepository.find_latest_for_key, so no raw SQL sits in the request path.
| class Session(NamedTuple): | ||
| """The proxy's record of one auto-routed session, as GET /auto_router/session returns it.""" |
There was a problem hiding this comment.
Routine docstrings violate policy
These explanatory docstrings violate the repository requirement limiting source comments to complex logic, tool inputs, or TODO and FIXME notes
Context Used: CLAUDE.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Fixed in 6d0b48c: the routine docstrings are gone from the script, claude_settings and agents; only non-obvious invariants keep one.
| try: | ||
| script_path.parent.mkdir(parents=True, exist_ok=True) | ||
| script_path.write_bytes(Path(statusline_script.__file__).read_bytes()) |
There was a problem hiding this comment.
Fixed in 6d0b48c: the script is staged beside the target and renamed into place via write_private_bytes, so no truncate-then-write remains.
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
6a8b56c to
a8c29b2
Compare
|
bugbot run |
|
@greptileai can you reply here with a score and why that score? |
be34b15 to
66696b3
Compare
|
Confidence score: 4/5 The feature is implemented end-to-end: the self-scoped session endpoint, bounded session IDs, Claude status-line installation/unconfiguration, Codex Stop-hook wiring, raw routed-model names, schema updates, and focused tests are all covered. The key-scoping and route-gating behavior is also exercised, and the PR includes real Claude/Codex/Postgres validation plus a passing e2e status check. I’m not giving it 5/5 because two edge cases remain: |
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 5 · PR risk: 0/10 |
a8c29b2 to
b9e9b0f
Compare
|
@greptileai can you reply here with a score and why that score? Since your last look: the cache is now keyed by proxy, key and session (b9e9b0f); the live-config baseline label is a documented caveat. |
|
bugbot run |
|
Confidence score: 4/5 (unchanged). The two concerns from my previous review are addressed: the status-line cache is now scoped by proxy, key, and session, and the live-config baseline behavior is clearly documented as an operational caveat rather than being presented as historical attribution. The implementation otherwise looks strong end-to-end: key-scoped session reads, bounded session IDs, Claude/Codex credential separation, receipt compatibility, and focused tests are covered. The latest e2e status is also passing. I’m holding at 4/5 because Once the hook installation permissions are hardened and the remaining CI checks are green, I would consider this a 5/5. |
66696b3 to
4a6f825
Compare
b9e9b0f to
1b73e52
Compare
|
@greptileai can you reply here with a score and why that score? 1b73e52 installs the script owner-only (0600 file, 0700 dir) and runs the apiKeyHelper only on a cache miss. |
|
bugbot run |
|
Confidence score: 5/5. The two remaining implementation concerns are addressed in
Together with the earlier proxy/key/session cache scoping and the documented live-baseline attribution caveat, I found no remaining feature-flow correctness blocker. CI is still pending, and the direct raw SQL call remains a repository maintainability concern, but neither changes the implementation confidence score. |
1b73e52 to
96d6090
Compare
|
Score: 4/5. The implementation is well-scoped and the validation is unusually thorough: it covers key-scoped session access, baseline persistence across router reconfiguration, resumed Claude sessions, static credential handling, Claude status-line output, Codex Stop hooks, and the no-key configuration failure path. The per-turn baseline recording and I’m not giving it 5/5 because this is a broad cross-cutting change spanning the API, migration, async spend rollups, Claude/Codex integrations, and local config mutation. The CI status is still pending, and the documented rollup timing, hook trust behavior, legacy configuration compatibility, and route-permission caveats leave some integration risk that should be confirmed by the remaining checks. |
7327498 to
41fd991
Compare
|
bugbot run |
|
@greptileai can you reply here with a score and why that score? |
|
Score: 4/5 (high confidence). The implementation is broad but cohesive and addresses the requested flow end to end:
I’m not giving 5/5 because this is a relatively large cross-cutting change touching proxy routes, persistence, schema/migration, CLI behavior, and agent integrations, so it carries more integration risk than a small isolated feature. I did not find a correctness issue that should block merge based on the reviewed head. |
|
@greptileai review |
| @@ -865,22 +820,16 @@ def _pkce_login(base_url: str, config_claude: bool, vault: SecretVault) -> None: | |||
| ), | |||
| ) | |||
| @click.pass_context | |||
| def login(ctx: click.Context, config_claude: bool, pkce: bool) -> None: | |||
| def login(ctx: click.Context, pkce: bool) -> None: | |||
| """Login to LiteLLM proxy using SSO authentication""" | |||
| from litellm.constants import LITELLM_CLI_SOURCE_IDENTIFIER | |||
|
|
|||
| ctx_obj: Final[CliContextObj] = ctx.obj | |||
There was a problem hiding this comment.
Removing login --config-claude breaks existing automation without an opt-in flag, violating the repository requirement against uncontrolled backwards-incompatible changes
Rule Used: What: avoid backwards-incompatible changes without user-controlled flags Why: This breaks current behaviour for users using existing functionality Example of BAD: this PR (#22164) introduced run_post_custom... (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
41fd991 to
e67939c
Compare
|
bugbot run |
|
@greptileai can you reply here with a score and why that score? |
|
Confidence score: 4/5 This is a strong end-to-end implementation. The latest changes address the earlier concerns: the status-line cache is scoped by proxy, key, and session; long session IDs use the same bounded representation as the rollup; baseline identities are recorded per turn; the endpoint uses the repository layer; and older Claude settings receipts have regression coverage. The feature is also backed by focused tests and a passing e2e status check. I’m not giving 5/5 because the change has a broad CLI/integration surface with documented operational caveats (async rollup lag, Codex hook trust, credential expiry, and externally tracked documentation), and the current status view does not establish that every required CI check is green. I found no blocking correctness issue in the current implementation. |
|
@greptileai review |
e67939c to
e485f6d
Compare
|
@greptileai fixed in e485f6d: --config-claude now configures Claude Code before the persistence-dependent return and reports when the CLI could not keep the key. Can you reply here with a score and why that score? |
|
bugbot run |
|
Confidence score: 5/5 The remaining issue is fixed in |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit e485f6d. Configure here.
TLDR
Problem this solves:
How it solves it:
GET /auto_router/sessionreturns one session's routed model, spend and baseline spend, scoped to the caller's own keyliteClaude Code wiring, rendersRouted toplus the savings barslite codexregisters the same script as a Stop hook, printing the block as a system messagelite configure claudenow requires a long-lived key (--api-key,lite --api-keyorLITELLM_PROXY_API_KEY) and writes it as a staticANTHROPIC_AUTH_TOKEN. Thelite loginfallback that wroteapiKeyHelper: lite auth print-tokenis gone: Claude Code re-ran that helper on every credential refresh, each run was a fulllitestart that probes the keychain, and the status line would have spawned it every 300ms.lite login --config-claudestays, andlite upkeeps working, but both now write the login's key statically (re-runlogin --config-claudewhen it expires); the status line reads the key from the env only--modelalso pinsenv.ANTHROPIC_MODEL: a resumed session (claude -c,--resume) otherwise re-sends the tier model its transcript recorded and a key scoped to the router gets a 403lite autoroutewizard turns onreturn_raw_model_name, so the transcript names the tier modellite autoroute upalso pins the top-levelmodeltoautorouter, so a leftovermodelfromlite configure claudecannot 400 the first turnUser Flow
Before: a developer running Claude Code through an auto-router sees the alias they requested and no cost feedback
lite configure claude --api-key sk-... --model claude-sonnet-5against a proxy whoseclaude-sonnet-5group is an auto-routerclaude-sonnet-5, even though the proxy routed the turn toclaude-haiku-4-5After: the same developer sees the served model and the session's savings in both tools
lite configure claude --api-key sk-... --model claude-sonnet-5; the command also installs~/.litellm/statusline.pyand registers it asstatusLineclaude-sonnet-5 · Routed to: claude-haiku-4-5 -80% vs Claude Opus 5with aLiteLLM $0.03bar under aClaude Opus 5 $0.17barlast_model,spend,baseline_spend,baseline_modelandbaseline_models; the same call with any other key gets 404claude -cresumes on the router alias, sinceANTHROPIC_MODELoutranks the model the transcript recordedlite codex, Codex asks once to trust the hook, and every later turn ends with the same block as a system messagelite unconfigure clauderemoves thestatusLineentry only while it still points at that scriptRelevant issues
Builds on #40319 (
lite configure claude, merged), which owns the settings merge this PR hooks into; the status line is one more key that merge writes and the configure receipt owns.Linear ticket
Resolves LIT-7356
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/test_litellm/<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@greptileaito re-request a review after pushing changes)Screenshots / Proof of Fix
Setup shared by both runs: a worktree proxy with real Postgres and real Anthropic models through the sandbox gateway. The
claude-sonnet-5group is a heuristic complexity router (SIMPLE haiku, MEDIUM/COMPLEX sonnet, REASONING opus, so the savings baseline resolves to opus). A virtual keysk-toN...scoped to that group is what Claude Code and Codex use; a second keysk-otheris the negative case.Before (11ec6f7)
Claude Code transcript names the alias, not the served model
claude -p "Reply with exactly: hello there"thenclaude -p --resume <session> "<a harder prompt>"withANTHROPIC_BASE_URLat the proxy andANTHROPIC_MODEL=claude-sonnet-5, then reading every assistant line of the transcriptmodel='claude-sonnet-5', while the proxy'sx-litellm-model-nameon the same turns wasanthropic/claude-haiku-4-5andanthropic/claude-sonnet-5Session endpoint
curl "$PROXY/auto_router/session?session_id=cf712ab8-4c7c-4d48-ba91-eed54bc2956b" -H "Authorization: Bearer $KEY"404(route does not exist), while the rollup row for that session already sat inLiteLLM_AutoRouterSessionCodex
codex exec "Reply with exactly: hello from codex"through the proxyAfter (e485f6d)
Claude Code transcript and status line
lite --base-url http://127.0.0.1:47358 configure claude --api-key $KEY --model claude-sonnet-5from a freshHOMEStartclaudefrom any terminal. Undo withlite unconfigure claude.;~/.claude/settings.jsonnow carries"statusLine": {"type": "command", "command": "/…/.venv/bin/python /…/.litellm/statusline.py"}beside the env block; the script itself is-rw-------inside the owner-only~/.litellmclaude(interactive, driven through a pty), two prompts; the status line under the input box reads, in order:model='claude-haiku-4-5'lite unconfigure claudeprintsNo settings file remains at …/settings.json; it held nothing but lite configure claude's own keys., sinceconfigurehad created the file andstatusLineis one of the keys its receipt ownsSession endpoint
curl "$PROXY/auto_router/session?session_id=cf712ab8-…" -H "Authorization: Bearer $KEY"{"session_id":"cdf2ff00-d966-44d9-a23f-101b563da88a","router_name":"claude-sonnet-5","router_type":"complexity","turns":3,"last_model":"anthropic/claude-haiku-4-5","spend":0.03897375,"saved_spend":0.155895,"baseline_spend":0.19486875,"baseline_model":"anthropic/claude-opus-5","baseline_models":{"anthropic/claude-opus-5":3}}404 {"detail":"No auto-routed turns recorded for session 'cf712ab8-…' under this key"}404(its own earlier session,463d0957-…, returns200withturns: 1)/auto_router/benchmarks: still401, the admin gate is untouchedopus-directtosonnet-direct, so its live savings baseline becameanthropic/claude-sonnet-5(the log showssavings_baseline_model: anthropic/claude-sonnet-5on the next decision). A fourth turn on the same session, then the same curl:{"session_id":"cdf2ff00-d966-44d9-a23f-101b563da88a","router_name":"claude-sonnet-5","router_type":"complexity","turns":4,"last_model":"anthropic/claude-haiku-4-5","spend":0.04037975,"saved_spend":0.157301,"baseline_spend":0.19768075,"baseline_model":"anthropic/claude-opus-5","baseline_models":{"anthropic/claude-opus-5":3,"anthropic/claude-sonnet-5":1}}The label stays
claude-opus-5, which is what three of the four turns'saved_spendwas priced against, andbaseline_modelsshows the split instead of relabelling the old money with the new baselineResuming a session
Before this round (settings carried
model: claude-sonnet-5but noANTHROPIC_MODEL), driven the same way through a pty on the same proxy:claude, one prompt: answered byclaude-haiku-4-5(the transcript records that id, since the router setsreturn_raw_model_name: true)claude -c, one prompt: Claude Code re-sends the transcript's model, the proxy log showsPOST /v1/messages?beta=true HTTP/1.1" 403 Forbidden, and the TUI printsPlease run /login · API Error: 403 key not allowed to access model.After:
lite configure claude --api-key $KEY --model claude-sonnet-5writes"model": "claude-sonnet-5[1m]"and"env": {"ANTHROPIC_MODEL": "claude-sonnet-5[1m]", ...}. Same two runs: every request the proxy saw namedmodel: claude-sonnet-5(56 of 56, zero 403s), the transcript still recordsclaude-haiku-4-5per turn, and the resumed session's status line readsclaude-sonnet-5 · Routed to: claude-haiku-4-5 -80% vs Claude Opus 5with the cost bars under it.lite unconfigure clauderestoresenv.ANTHROPIC_MODELwith the other keysConfigure without a key
lite configure claude --model claude-sonnet-5with no key anywhere:Error:lite configure claudeneeds a long-lived virtual key: pass --api-key,lite --api-key, or set LITELLM_PROXY_API_KEY. Yourlite logincredential expires within a day, so it is not written into Claude Code's settings.No settings file, no receipt, no request, no login promptCodex Stop hook
lite --base-url http://127.0.0.1:47358 codex --skip-verify exec "Reply with exactly: hello from codex"from a freshHOME, with the hook already trusted the way the Codex TUI records it ([hooks.state."/<session-flags>/config.toml:stop:0:0"] trusted_hash = "sha256:16acd9a2…",enabled = truein~/.codex/config.toml)liteprintslitellm: routing Codex through proxy at http://127.0.0.1:47358and launches Codex with-c hooks.Stop=[{hooks=[{type="command",command="…/python …/.litellm/statusline.py"}]}]… codex --skip-verify exec resume 01a08c71-86b2-7121-ab90-0f82e2e309a7 "Reply with exactly: second turn"; Codex's own output ends withGET /auto_router/session?session_id=01a08c71-86b2-7121-ab90-0f82e2e309a7 HTTP/1.1" 200 OK(on an earlier run the first turn's call was a404 Not Foundbecause the spend flush had not landed yet, and the second turn still found the row since the hook never caches)codex execruns hooks but does not print theirsystemMessage(the TUI does), so the same script was invoked by hand with the Stop payload Codex sends for that thread, under the same env, to show the text:Hooks need reviewwithTrust all and continue), which I could not drive through a pty reliably; what Codex writes after that choice is thehooks.stateblock above, and an untrusted hook is skipped silentlyType
🆕 New Feature
Caveats (if any)
Medium
allowed_routesconfines it tollm_api_routescannot call/auto_router/session(the route joinsself_managed_routes, which waives the role gate, not a key's own route ceiling); its status line shows only theRouted toline, and the 403 is cached for the TTL so it does not retry every refresh. Add/auto_router/sessionto that key'sallowed_routesto opt it inreturn_raw_model_name: true; otherwise the line shows the requested alias. The wizard sets it; hand-written configs must add itTrust all and continueonce in the TUI;codex execskips untrusted hooks silentlylite codexthen skips its own Stop hook with a notice, since a session flag would replace the wholehooks.Stoplistlite login --config-claudenow writes the login's key as a static token that expires with it (24h by default), so it is the per-login re-wire step rather than a one-time setup. It configures Claude Code from the key in hand even when the CLI's own token file or keychain refused to keep the credential, and says so, since the key is usable either way;lite configure clauderefuses to run on alite logincredential. A machine configured by an older version keeps working (itsapiKeyHelperstill resolves) until the next--config-claudeorconfigure claude --api-key, which strips the helper;lite unconfigure clauderestores whatever the receipt recorded for itlite upnow copies the resolved key intoenv.ANTHROPIC_AUTH_TOKENfor the life of the session; a key that expires whileupis running is not refreshed untilupis restarted. Everysettings.jsonwrite (configure,up,autoroute up, and both restores) now goes through one owner-only, atomic, symlink-aware writer (write_claude_settings), so a file that now carries the key is never created under the umask or truncated in place; verified live withlite upover a0644file (patched file0600, restored file0600, no temp files left)litecommands (credential-preflight) comes from the token store's migrate-on-read in fix(anthropic): carry the adaptive effort tier to every bridged Claude target #38533, not from this PR; this PR removes the two places that invokedlitefrom Claude CodeLow
proxy-infra / Run testswent red once ontest_check_migration.py::test_migrate_diff_stops_at_its_budget_and_takes_its_process_tree_with_it, a process-tree timing test this PR does not touch (green on the base PR head, on staging, and locally on this tree)osv-scanis red on this head and on the base PR's head from the same hour (new advisories onnext,sharp,js-yaml,vitestanddiskcachein lockfiles this PR does not touch); it needs its ownosv-scanner.tomlPR, not this onebaseline_modelis recorded per turn on the rollup row (baseline_models, a map of baseline to turns), so it names the counterfactual the money was actually priced against even after the router is reconfigured or removed; a session that straddles a baseline change reports the majority label and the full map. Rows written before this column existed, and adaptive or quality routers (which derive no savings baseline), reportbaseline_model: nullbaseline_modelscolumn ships as oneADD COLUMN IF NOT EXISTS ... JSONB NOT NULL DEFAULT '{}'migration onLiteLLM_AutoRouterSession(schema-only, applied at boot); theprisma migrate deployon the rig database and the real-Postgres rollup tests intests/proxy_behavior/spendran against itgofmt, vet, build, test(the terraform provider workflow) is red on this head; it is path-filtered toterraform/provider/**, which this PR does not touch, and it is green on the staging tipFinal Attestation
Note
Medium Risk
Touches proxy auth routing, spend rollup SQL, and CLI credential handling in user settings; session reads are key-scoped but keys with restricted
allowed_routesmay not reach the new endpoint without configuration.Overview
Adds per-session auto-router visibility for coding agents: a new
GET /auto_router/session(key-scoped) returns the last routed model, spend, savings baseline, and abaseline_modelsbreakdown; the spend rollup now recordssavings_baseline_modelper turn and persistsbaseline_modelsonLiteLLM_AutoRouterSession(migration + Prisma).The
liteCLI stops writingapiKeyHelperand instead copies a staticANTHROPIC_AUTH_TOKENinto Claude settings (lite up,login --config-claude,configure claudenow requires a long-lived virtual key).--modelalso setsenv.ANTHROPIC_MODELso resumed sessions stay on the router alias.lite autorouteenablesreturn_raw_model_name: trueso transcripts show tier models.A bundled
statusline.pyis installed atomically (write_private_bytes) and wired as Claude CodestatusLineand a Codex Stop hook, showing routed model and savings bars from the new endpoint (5s cache, stdlib-only).Reviewed by Cursor Bugbot for commit e485f6d. Bugbot is set up for automated code reviews on this repo. Configure here.