Repository navigation
Cost Optimization Improvements: what do you want to see? #32172
Replies: 18 comments 14 replies
|
Advisor mode API? |
|
Operating notes from running a tier-based router in production, since the ask is intentionally broad (disclosure at the end):
Disclosure: I am the founder of a commercial tier-routing API, so I have an obvious bias toward the "named classes" shape — deliberately not linking it here. These are meant as operational lessons for building this into LiteLLM itself. |
|
Cursor vibe coding support - Cursor seems to have blocked AI Gateway compatibility in our conversations directly with them. The public LiteLLM documents don't appear to address the issue. We have usage split across claude code, opencode, cursor - Cursor usage representing about 20% of token usage, which we want to route correctly to the best appropriate model/service for liquidity. |
Proposal: Gateway-side shell tool-output compression with a lightweight LLM fallbackOne cost-optimization improvement I would strongly like to see is optional LiteLLM Proxy middleware that centrally compresses large shell and terminal tool outputs before forwarding them to the primary LLM. The shell command should execute exactly as it does today. The client should not need to install a command wrapper or replace its shell implementation. Only the provider-bound copy of the tool result would be compressed. I would recommend a hybrid approach:
This is tool-result transformation, not model routing. The lightweight model does not decide which primary model handles the request. It performs a bounded preprocessing task before the main request is forwarded. Intended request flowThe raw output would still reach LiteLLM. This feature would prevent unnecessary raw output from reaching the primary model provider, but it would not provide the same privacy boundary as client-side compression. Why implement this in LiteLLM?LiteLLM is a common control point for many agent clients. A proxy-side implementation could therefore provide organization-wide tool-output compression without requiring separate integrations for every client, editor, shell, or agent runtime. Typical examples of unnecessarily large output include:
These results consume the context window of the expensive primary model even though much of the content can be reduced safely. Protocol supportThe middleware should preserve the protocol-specific relationship between a tool invocation and its result.
Only the textual result content should be replaced. IDs, ordering, roles, result types, error flags, and other structural fields must remain unchanged. Shell tools do not have one standardized name. Detection should therefore be configurable and based on the paired tool invocation, for example Proposed compression pipeline1. Eligibility and thresholdsFor each tool result:
The trigger should be based primarily on the size of the individual tool result, rather than only on the total conversation length. This allows LiteLLM to reduce a large result before it creates context-window pressure. 2. Deterministic compression firstKnown output formats should use deterministic filters because these are fast, reproducible, inexpensive, and easier to validate than an LLM summary. Generic filters could include:
Command-aware filters could support output from tools such as The initial command-aware filters should be conservative. For example, a failing test result should retain the failure name, assertion, stack trace, captured error output, and summary rather than returning only "one test failed." 3. Lightweight LLM fallbackA lightweight model should be optional and invoked only when:
The compression call should receive only the information required for this task:
It should not require the complete conversation or system prompt. The compression model should:
An internal response could use a structure similar to: {
"summary": "The test suite completed with two failures.",
"critical_sections": [
{
"start_line": 418,
"end_line": 446,
"reason": "First failing test and stack trace"
}
],
"warnings": [
"Deprecated API used in src/client.py:91"
],
"omitted_line_count": 5238
}LiteLLM would validate this response and construct the final textual tool result itself. The lightweight model should not be allowed to generate protocol fields or tool-call identifiers. Example provider-bound result: The summary must be clearly labeled as generated. Critical lines selected from the raw output should remain verbatim so that the primary model can distinguish source evidence from the generated summary. 4. Raw-output retrievalCompression is inherently lossy, so the primary model needs a safe recovery path. LiteLLM could reuse or extend the existing {
"name": "litellm_tool_output_retrieve",
"arguments": {
"key": "tool-result-7d21...",
"start_line": 400,
"end_line": 470
}
}Useful retrieval operations could include retrieving a line range, searching for a literal string, retrieving matching lines with surrounding context, or retrieving one bounded chunk. Retrieval should not automatically return the entire original output, because that could recreate the same context-window problem. The cache should have the following properties:
A process-local cache is useful for development, but a shared cache is needed when subsequent requests can reach a different LiteLLM worker. LiteLLM should also cache the compressed representation by a tenant-scoped content hash. Agent clients often resend the same historical tool result on every turn, and the proxy should not call the compression model repeatedly for identical content. 5. Failure behaviorCompression must not make the main model request less reliable. Suggested behavior:
Conceptual configurationThe exact names can follow existing LiteLLM conventions, but a configuration could look like this: model_list:
- model_name: tool-output-compressor
litellm_params:
model: openai/<approved-small-model>
api_base: os.environ/TOOL_COMPRESSOR_API_BASE
api_key: os.environ/TOOL_COMPRESSOR_API_KEY
litellm_settings:
callbacks:
- tool_output_compression
tool_output_compression_params:
enabled: true
mode: hybrid
min_input_tokens: 4000
target_tokens: 1200
deterministic_first: true
compression_model: tool-output-compressor
compression_timeout_ms: 750
fallback_on_timeout: deterministic
preserve_first_lines: 40
preserve_last_lines: 120
preserve_errors: true
preserve_warnings: true
preserve_file_references: true
preserve_exit_status: true
include_tools:
- Bash
- shell
- terminal
- exec
enable_retrieval: true
raw_content_ttl_seconds: 900
cache_backend: redis
log_content: falseThe latency value above is illustrative and should be configurable. A small model still needs to read the input, so very large output can have significant prefill latency. This is why deterministic preprocessing and a strict timeout are important. Request-level control could be exposed through metadata or a dedicated parameter: {
"metadata": {
"tool_output_compression": {
"enabled": true,
"mode": "hybrid"
}
}
}Administrators should be able to prevent clients from overriding centrally enforced security or data-residency policies. Security and privacy requirementsShell output may contain source code, credentials, internal URLs, personal data, customer data, or production logs. Therefore:
Prompt instructions alone are not a complete defense against malicious command output. Protocol validation, disabled tools, deterministic preservation rules, timeouts, model restrictions, and exact-output retrieval are still required. ObservabilityUseful non-content metrics would include:
Optional response headers could expose aggregate information: Possible implementation shapeThis could be implemented as a dedicated integration rather than changing the semantics of the existing generic Possible components:
The existing compression-interception hook, retrieval mechanism, and agentic-loop implementation appear to provide useful foundations. However, tool-output compression should remain separately configurable because its accuracy, latency, privacy, and failure requirements differ from historical message compaction. Acceptance criteria
Suggested tests
The quality benchmark should measure whether the primary model still completes the task correctly, rather than evaluating only the compression ratio. Out of scopeThis proposal does not require LiteLLM to:
Motivation and expected benefitCoding agents frequently insert very large shell results into the next model request. The primary model then spends context, latency, and money processing repetitive output that could often be reduced to a summary, critical evidence, and an on-demand retrieval reference. Client-side tools can already optimize individual environments, but they require installation and configuration in every supported agent. A LiteLLM implementation would establish one centrally managed policy across multiple clients while preserving their existing command execution behavior. A lightweight model is a good fit for the semantic fallback because the task is narrow: identify failures, warnings, relevant artifacts, and important output sections. The expensive primary model can then spend its context and reasoning budget on solving the user's actual task. The lightweight model should not front every result unconditionally. Deterministic filters should handle predictable output, while the lightweight model is reserved for large or unknown formats. This hybrid design provides most of the context savings without adding an extra model call to every request. The expected benefits are:
The main trade-offs are additional preprocessing latency, the risk of lossy summarization, cache sensitivity, and the fact that raw output still reaches LiteLLM. These trade-offs should be explicit, measurable, and configurable. A conservative, opt-in hybrid implementation with exact retrieval would make this a strong proxy-level capability rather than relying on each client to implement its own shell interception. The closest existing proposal I found is #29320, but its explicit decision to skip tool exchanges makes the distinction clear: this feature is about safely compressing the current tool result, not general conversation-history compaction. The per-model controls proposed in #28940 would be complementary. Existing work in #25637 and #25729 also looks like a useful foundation. |
MCP Proxy ModeAdd an optional MCP proxy mode that exposes only three generic tools to the model:
Instead of registering every MCP tool individually in the model's tool list, LiteLLM would act as a router behind these generic endpoints. The model would first discover relevant tools via search_tools, retrieve the schema if needed, and then invoke the selected tool with call_tool. BenefitsDramatically reduces tool definitions included in every request. Would this work?Yes, technically this is a viable approach and is similar to how some agent frameworks implement tool discovery rather than eagerly exposing every tool. The main tradeoff is an extra round trip: So you trade a few additional tool calls for significantly smaller prompts. For deployments with hundreds of MCP tools, that's usually a worthwhile tradeoff because prompt overhead is paid on every request, whereas discovery only happens when tools are actually needed. The biggest challenge is model behavior. Models need to reliably perform the discovery step instead of expecting all tools up front. That can be addressed with good prompting or by making proxy mode opt-in. MCP Semantic FilteringAllow returning zero toolsWhen semantic filtering is enabled, allow the result to be zero matching MCP tools. Currently, if no embedding similarity threshold is met, LiteLLM falls back to returning all MCP tools. This defeats the purpose of semantic filtering by:
Instead, developers should be able to configure the behavior when no matches are found (for example: return zero tools, return a default MCP, or return all as today's behavior). Keyword-based routingAllow developers to define explicit keyword or phrase mappings for MCPs or individual tools. Examples:
This provides deterministic routing for common workflows that semantic search may miss, while still allowing embedding-based matching as a fallback. A hybrid approach (keywords first, semantic search second) would likely produce the best accuracy while minimizing unnecessary tool exposure. |
|
HeadRoom Test Connection Button |
|
The Cost Optimization → Autorouter page does not show auto routers configured in The routers are loaded and usable by the proxy, but they are not present in Expected behaviorThe Autorouter page should either:
It would also be useful if the page showed the source of each router (config.yaml |
|
Related to #31606 and #31725: LiteLLM now has a concrete request and an open PR for time-based off-peak pricing, but this appears to cover cost calculation more than routing. DeepSeek V4 is a useful acceptance case: its official pricing has peak windows at 01:00-04:00 and 06:00-10:00 UTC; all other hours are off-peak, with off-peak rates at 50% of peak. It also distinguishes cache-hit input, cache-miss input, and output pricing. A minimal implementation could:
For DeepSeek Flash, a peak-default configuration could express off-peak as the complementary windows 10:00-01:00 and 04:00-06:00 UTC. The key cost-optimization question is whether time-based pricing should affect only accounting, or also the deployment-selection score used by cost-based-routing. Applying a temporal rate to spend tracking alone would not let the router choose the currently cheaper deployment. The request-start vs completion-time semantics should also be explicit for long or streaming requests that cross a pricing boundary. |
|
The wall we hit: cost tracking has no time axis, and three providers now price by the clock. Checked against
Those are the peak rates. Off-peak is exactly half on all three numbers, and off-peak is the majority of the week: peak is Beijing 09:00–12:00 and 14:00–18:00, Monday to Friday ( Budgets are where this stops being cosmetic: a tenant with I checked the whole file for anywhere to put this and there is nowhere: keys = set()
for v in json.load(open("model_prices_and_context_window.json")).values():
if isinstance(v, dict): keys.update(v)
[k for k in keys if any(w in k.lower()
for w in ("peak", "time", "hour", "window", "schedule", "effective"))]
# []Empty across ~2000 entries. That is the actual ask here — a schema gap, not a data-freshness gap. Patching the DeepSeek numbers just picks which half of the week is wrong. It is not one vendor, and the second one does not fit a DeepSeek-shaped special case. DeepSeek moved to peak/off-peak on 2026-08-16 and made weekends fully off-peak on 2026-08-23. Z.ai/Zhipu's GLM Coding Plan is reported to charge peak on Mon–Fri 14:00–18:00 Singapore time with off-peak at 50% — one window, not two, a different What the shape has to include, from measuring 46 downstream implementations of the DeepSeek rule. Four failure modes showed up, and each one maps to a field that has to exist or the bug is unavoidable:
Concretely, that is roughly: "deepseek/deepseek-v4-pro": {
"input_cost_per_token": 1.32e-06, // unchanged: the peak/default row
"pricing_schedule": {
"timezone": "Asia/Shanghai", // the vendor's clock, not the host's
"effective_from": "2026-08-23", // nullable; null ⇒ refuse to re-cost older windows
"windows": [{"days": "mon-fri", "hours": ["09:00-12:00", "14:00-18:00"],
"multiplier": 1.0}],
"default_multiplier": 0.5
}
}…plus Offer, no strings. We keep dated conformance vectors for this rule — the window edges, both midnight boundaries of the weekend, the pre-effective-date instants, and the two-clock disagreement band — as JSON under CC0, so an implementation can be tested rather than argued about: https://github.com/xyzs996/deepseek-peak-hours. Take the file, vendor it, relicense it, no attribution needed. The write-up of the four failure modes and where each one bites is here: https://xyzs996.github.io/llm-api-pricing/deepseek-peak-hours.html (same piece as plain static HTML, no scripts, if that host is blocked for you: https://telegra.ph/DeepSeek-peak-and-off-peak-hours-08-23). Disclosure: those are mine. The vectors are the useful part and they cost you nothing to check — every number in them traces to a quoted line on the vendor's page, with the date it was read. Added a few hours later, because "a schema field nobody has" is a weak claim and it turned out to be measurable. I transcribed the peak/off-peak predicate of nine published DeepSeek billing plugins — commit-pinned, same branches and operators, ~10 lines of arithmetic each — and ran the vectors above against all of them: Zero dependencies, no network, Node 16+. Two of the nine pass everything they can run. Seven fail the same three weekend instants, because they decide peak/off-peak from the hour and nothing else — so as of 2026-08-22T16:00:00Z they report double on 14 hours a week. That is the part I would offer as evidence here, because it is not a "those projects were careless" story. Every one of the seven has the hour arithmetic right, several handle the timezone carefully through
Two details from that exercise worth folding into
If a transcription is wrong that is my bug and not a finding about anyone's project — the adapters are in one file and I will fix and re-run on a word. |
Support for fine-grained model cost structuresEnterprise customers (we use LiteLLM Enterprise) have custom token costs negotiated with different providers and these are often not straightforward discounts, instead the discount structure could scale with use, e.g. First 10k of that month gets 5% off, 50k+ gets 10% off, 200k+ gets us 25% off, and so on, and these counters reset per month. Having the ability to reflect these negotiated price structures in the model costs would be very helpful when tracking internal spend, because right now we cannot trust the costs reported in the LiteLLM UI. This would also pair well with a cost-aware model router to send requests to the most cost-effective provider of a given model (e.g., route Claude models to Bedrock first, and after those discount quotas have been exhausted, route to Vertex instead, and finally Anthropic first party). |
|
Ability to export cost data into focus format would be great: https://focus.finops.org/ |
|
RTK, Headroom, Caveman, Ponytail are all good candidates, how suitable are to be in litellm I can't say , but if I can configure them per client or per model might be quite useful. |
|
A cost line that doesn't show up in routing or caching, but was my largest single waste: The shape: a call whose outcome was unverifiable got classified as failed and retried. Two things that would make it visible at the gateway layer:
The general rule that saved me the most: keep FAILED ("it did not happen", safe to Related for the escalation feature in #32168: an escalation fired on unknown state has |
|
Ability to customize Heuristic classification scores. IE - I'd like to set SIMPLE < 0.30, MEDIUM 0.30 - 0.45, COMPLEX 0.45 - 0.65, REASONING > 0.65 (or 2+ markers). |
Bro! This was way too long. But Headroom AI has a direct LiteLLM Proxy integration (actually several options) that will perform all you are talking about. Litellm proxy even has its own compression and context offload features. Check out: https://docs.litellm.ai/docs/proxy/headroom |
|
One measure I’d put beside token cost is cost per accepted task on a fixed, representative workload. For coding agents, track task quality, retries and human review time alongside total API cost and end-to-end latency; a lower per-call bill can still mean a higher finished-task cost when extra attempts or cleanup are needed. Make the workload and acceptance criteria explicit in any comparison. Disclosure: I’m Ryan, founder of AsterWise, a usage-based API that handles model choice for coding and everyday agent work. I’m sharing this as a product builder, not making an Aster performance claim. |
|
Add jev (or other future open-weights system one models) as a classifier option for auto-routers. |
1 Support multi-currency billingLiteLLM is used globally, for instance, billing in GBP, YEN, EURO etc. We are fine with this being limited to only 1 currency to prevent having to do currency conversions. 2 Support no-currency billingFor "token grants" in e.g. a university or research institute, no money is exchanged. Instead Organisations and Teams are allocated tokens. For this case we would want a token multiplier, for example: qwen3-0.6b would have a 1x token multiplier, qwen3-8b would have a 1.5x token multiplier, and qwen3-27b would have a 3x token multiplier. |
Uh oh!
There was an error while loading. Please reload this page.
We're collecting suggestions for cost optimization improvements in LiteLLM. This is intentionally broad: routing (auto-router, load balancing, fallbacks), budgets and spend controls, caching, or anything else that would help you spend less while still getting the model behavior you need.
If you've hit a wall trying to control or reduce cost with LiteLLM, or have an idea for how it could work better, we want to hear it here.
All reactions