MCPcopy Create free account
hub / github.com/BerriAI/litellm / _update_user_cache

Function _update_user_cache

litellm/proxy/proxy_server.py:2706–2757  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

2704
2705 ### UPDATE USER SPEND ###
2706 async def _update_user_cache():
2707 ## UPDATE CACHE FOR USER ID + GLOBAL PROXY
2708 if response_cost is None:
2709 return
2710 user_ids = [user_id]
2711 try:
2712 for _id in user_ids:
2713 # Fetch the existing cost for the given user
2714 if _id is None:
2715 continue
2716 cached_user = await user_api_key_cache.async_get_cache(key=_id)
2717 if cached_user is None:
2718 # do nothing if there is no cache value
2719 return
2720 existing_spend_obj = CacheCodec.deserialize(cached_user, LiteLLM_UserTable)
2721 if existing_spend_obj is None:
2722 return
2723 verbose_proxy_logger.debug(
2724 f"_update_user_db: existing spend: {existing_spend_obj}; response_cost: {response_cost}"
2725 )
2726
2727 existing_spend = existing_spend_obj.spend or 0.0
2728 # Calculate the new cost by adding the existing cost and response_cost
2729 new_spend = existing_spend + response_cost
2730
2731 existing_spend_obj.spend = new_spend
2732 values_to_update_in_cache.append(
2733 (
2734 _id,
2735 CacheCodec.serialize(existing_spend_obj, model_type=LiteLLM_UserTable),
2736 )
2737 )
2738 ## UPDATE GLOBAL PROXY ##
2739 global_proxy_spend = await user_api_key_cache.async_get_cache(
2740 key="{}:spend".format(litellm_proxy_admin_name)
2741 )
2742 if global_proxy_spend is None:
2743 # do nothing if not in cache
2744 return
2745 elif response_cost is not None and global_proxy_spend is not None:
2746 increment = global_proxy_spend + response_cost
2747 values_to_update_in_cache.append(("{}:spend".format(litellm_proxy_admin_name), increment))
2748 except Exception as e:
2749 verbose_proxy_logger.warning(
2750 "Spend tracking - failed to update user spend in cache. "
2751 "Budget enforcement may use stale spend values. "
2752 "user_id=%s, response_cost=%s - %s\n%s",
2753 user_id,
2754 response_cost,
2755 str(e),
2756 traceback.format_exc(),
2757 )
2758
2759 ### UPDATE END-USER SPEND ###
2760 async def _update_end_user_cache():

Callers 1

update_cacheFunction · 0.85

Calls 6

deserializeMethod · 0.80
debugMethod · 0.80
async_get_cacheMethod · 0.45
appendMethod · 0.45
serializeMethod · 0.45
formatMethod · 0.45

Tested by

no test coverage detected