Skip to content

perf(caching): memoize _get_all_llm_api_params, rebuilt per request - #31430

Merged
yassin-berriai merged 1 commit into
litellm_internal_stagingfrom
litellm_cache_model_param_helper
Jun 26, 2026
Merged

yassin-berriai merged 1 commit into
litellm_internal_stagingfrom
litellm_cache_model_param_helper

Conversation

@yassin-berriai

Copy link
Copy Markdown
Contributor

Relevant issues

Linear ticket

LIT-4050 (found while investigating LIT-3910)

Context

Pre-existing per-request inefficiency, not a regression in any particular release. ModelParamHelper._get_all_llm_api_params() introspects six sets of supported kwargs (chat, text, embedding, transcription, rerank, responses) from static OpenAI type annotations plus fixed sets, unions them, and subtracts an exclude set. The result is constant for the process lifetime, yet it was recomputed on every request through two near-universal paths:

  • Cache.get_cache_key() runs on every request when caching is enabled
  • _get_relevant_args_to_use_for_logging() -> get_standard_logging_model_parameters() runs on every request that builds a StandardLoggingPayload (spend logging and most callbacks)

Fix

Memoize with lru_cache(maxsize=1). The function takes no arguments and its result is process-static, and both callers treat the result as read-only (membership tests and .difference(), no mutation), so sharing one cached instance is safe.

Pre-Submission checklist

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

Screenshots / Proof of Fix

Microbenchmark, cached vs the uncached underlying function (__wrapped__):

CACHED:   0.022 us/call
UNCACHED: 4.695 us/call

About 213x faster. Across the two per-request call sites that is roughly 9 us/req saved on every cached/logged request. Correctness verified in the same run: the cached result equals a fresh uncached computation, and repeated calls return the same object.

Type

🚄 Infrastructure

Changes

litellm/litellm_core_utils/model_param_helper.py: add lru_cache(maxsize=1) to _get_all_llm_api_params

tests/test_litellm/litellm_core_utils/test_model_param_helper.py: new mapped test file asserting the cached result equals the uncached computation and that the result is memoized (the memoization test fails if the cache is removed)

ModelParamHelper._get_all_llm_api_params() introspects six sets of supported
kwargs from static OpenAI type annotations and fixed sets and unions them. The
result is constant for the process lifetime, but it was recomputed on every
request through both Cache.get_cache_key (caching path) and
_get_relevant_args_to_use_for_logging -> get_standard_logging_model_parameters
(spend-logging / callback path). Memoize it with lru_cache(maxsize=1); the
function takes no arguments, its result is process-static, and both callers
treat it as read-only. ~4.7 us/call to ~0.02 us/call.
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR memoizes ModelParamHelper._get_all_llm_api_params() with lru_cache(maxsize=1), eliminating a per-request rebuild of a set that is constant for the process lifetime. Both call sites (Cache.get_cache_key and the spend-logging path) now share a single cached instance, saving ~9 µs per request.

  • model_param_helper.py: @lru_cache(maxsize=1) is stacked correctly under @staticmethod (correct Python ordering); the function takes no arguments, so cache invalidation is never needed; current callers use .difference() and membership tests, not in-place mutation.
  • test_model_param_helper.py: New test file asserts both correctness (cached result equals a fresh __wrapped__ call) and object-identity memoization.

Confidence Score: 4/5

Safe to merge; the change is a narrow, well-tested memoization of a process-static function with no side effects.

The only concern is that the cached function still advertises a mutable Set[str] return type, meaning a future caller could accidentally mutate the shared cached object. No current caller does this, so there is no present breakage. The decorator order (@staticmethod above @lru_cache) is correct, and the tests cover both correctness and memoization.

No files require special attention, though model_param_helper.py would benefit from changing the return type to FrozenSet[str] to prevent accidental mutation of the shared cached set by future callers.

Important Files Changed

Filename Overview
litellm/litellm_core_utils/model_param_helper.py Adds lru_cache(maxsize=1) to _get_all_llm_api_params; result type is still a mutable set, which is a latent mutation hazard for future callers sharing the same cached object.
tests/test_litellm/litellm_core_utils/test_model_param_helper.py New test file verifying correctness (cached == uncached) and memoization (same object identity); uses wrapped correctly to bypass the cache.

Comments Outside Diff (1)

  1. litellm/litellm_core_utils/model_param_helper.py, line 57-94 (link)

    P2 Mutable return type shared across callers via lru_cache

    _get_all_llm_api_params is now cached with lru_cache but still returns a plain (mutable) Set[str]. Every caller gets back the exact same set object. The current callers are safe — _get_relevant_args_to_use_for_logging calls .difference() (which creates a new set), and Cache.get_cache_key only does membership tests — but any future caller that calls .add(), .discard(), or |= on the return value would silently corrupt the cache for all subsequent requests in that process. Returning a frozenset would make the contract explicit and enforce immutability at the type level.

    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!

Reviews (1): Last reviewed commit: "perf(caching): memoize _get_all_llm_api_..." | Re-trigger Greptile

@greptile-apps

greptile-apps Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

Memoizes ModelParamHelper._get_all_llm_api_params() with @lru_cache(maxsize=1) so the per-process-static set of all LLM API parameter names is computed once rather than on every cache-key generation and spend-logging call.

  • model_param_helper.py: adds @staticmethod @lru_cache(maxsize=1) to _get_all_llm_api_params; the decorator order is correct for Python 3.8+, and the two active callers (Cache.get_cache_key and _get_relevant_args_to_use_for_logging) both use the result read-only via .difference() and membership tests.
  • test_model_param_helper.py: new test file verifying the cached result equals a fresh __wrapped__() computation and that repeated calls return the same object identity.

Confidence Score: 4/5

Safe to merge; the change is minimal and well-tested, with one minor concern about the mutable return type of the now-shared cached object.

The memoization is correct: lru_cache on a zero-argument static method is straightforward, and the module-level _relevant_logging_args initialisation already primes the cache at import time. The one concern is that the cached instance is a mutable set, so a future caller that mutates it would silently corrupt all subsequent calls for the lifetime of the process — the current callers are safe, but the return type annotation does not enforce the read-only contract.

Only model_param_helper.py warrants a look — specifically the frozenset vs mutable Set[str] return type on the cached method.

Important Files Changed

Filename Overview
litellm/litellm_core_utils/model_param_helper.py Adds @lru_cache(maxsize=1) to _get_all_llm_api_params; result is correct and the decorator order is valid for Python 3.8+, but the return type remains mutable Set[str] despite the cached object being shared across all callers.
tests/test_litellm/litellm_core_utils/test_model_param_helper.py New test file with two well-targeted tests: one asserts value equality against __wrapped__ (uncached) computation, the other asserts object identity across calls to verify memoization.

Reviews (2): Last reviewed commit: "perf(caching): memoize _get_all_llm_api_..." | Re-trigger Greptile

Comment on lines 57 to 59
@staticmethod
@lru_cache(maxsize=1)
def _get_all_llm_api_params() -> Set[str]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 The lru_cache now returns the same mutable set object on every call. Any caller that mutates the result (e.g. .add(), .update(), .discard()) would silently corrupt the process-lifetime cache, causing every subsequent caller to receive a wrong set. The current callers are verified read-only, but the Set[str] return type annotation does not communicate this contract to future callers. Returning a frozenset makes mutation a TypeError and documents the read-only intent in the type signature.

Suggested change
@staticmethod
@lru_cache(maxsize=1)
def _get_all_llm_api_params() -> Set[str]:
@staticmethod
@lru_cache(maxsize=1)
def _get_all_llm_api_params() -> frozenset:

@codecov

codecov Bot commented Jun 26, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@yassin-berriai
yassin-berriai enabled auto-merge (squash) June 26, 2026 11:45
@yassin-berriai
yassin-berriai merged commit aa49568 into litellm_internal_staging Jun 26, 2026
74 checks passed
@yassin-berriai
yassin-berriai deleted the litellm_cache_model_param_helper branch June 26, 2026 16:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants