Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
1fa4206
fix(core_helpers.py): return None, instead of raising kwargs is None …
Oct 29, 2024
d866b12
docs(cost_tracking.md): cleanup doc
Oct 29, 2024
f147e33
fix(vertex_and_google_ai_studio.py): handle function call with no par…
Oct 29, 2024
dd309f8
test(test_router_timeout.py): add test for router timeout + retry logic
Oct 29, 2024
ba49202
test: update test to use module level values
Oct 29, 2024
149dd18
(fix) Prometheus - Log Postgres DB latency, status on prometheus (#6…
ishaan-jaff Oct 29, 2024
0dc957c
docs clarify vertex vs gemini
ishaan-jaff Oct 29, 2024
37f5feb
(router_strategy/) ensure all async functions use async cache methods…
ishaan-jaff Oct 29, 2024
947af8c
(fix) proxy - fix when `STORE_MODEL_IN_DB` should be set (#6492)
ishaan-jaff Oct 29, 2024
17695e1
(fix) `PrometheusServicesLogger` `_get_metric` should return metric i…
ishaan-jaff Oct 29, 2024
fe811a5
bump: version 1.51.0 → 1.51.1
ishaan-jaff Oct 29, 2024
74d7216
Add `azure/gpt-4o-mini-2024-07-18` to model_prices_and_context_window…
xingyaoww Oct 29, 2024
3b385fb
Update utils.py (#6468)
vibhanshu-ob Oct 29, 2024
6b991e7
(perf) Litellm redis router fix - ~100ms improvement (#6483)
Oct 29, 2024
9d25552
refactor(prometheus.py): move to using standard logging payload for r…
Oct 30, 2024
50ff8c3
fix: fix linting error
Oct 30, 2024
c72ea56
fix(redis_cache.py): make sure ttl is always int (handle float values)
Oct 30, 2024
3cec40a
fix: fix linting error
Oct 30, 2024
498d2d9
test: update test
Oct 30, 2024
669cda3
fix: fix linting error
Oct 30, 2024
5569838
Merge branch 'main' into litellm_dev_10_29_2024
Oct 30, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,7 @@ jobs:
- run: ruff check ./litellm
- run: python ./tests/documentation_tests/test_general_setting_keys.py
- run: python ./tests/code_coverage_tests/router_code_coverage.py
- run: python ./tests/code_coverage_tests/test_router_strategy_async.py
- run: python ./tests/documentation_tests/test_env_keys.py
- run: helm lint ./deploy/charts/litellm-helm

Expand Down
20 changes: 16 additions & 4 deletions docs/my-website/docs/providers/gemini.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,23 @@ import TabItem from '@theme/TabItem';

# Gemini - Google AI Studio

## Pre-requisites
* `pip install -q google-generativeai`
* Get API Key - https://aistudio.google.com/
| Property | Details |
|-------|-------|
| Description | Google AI Studio is a fully-managed AI development platform for building and using generative AI. |
| Provider Route on LiteLLM | `gemini/` |
| Provider Doc | [Google AI Studio ↗](https://ai.google.dev/aistudio) |
| API Endpoint for Provider | https://generativelanguage.googleapis.com |

<br />


## API Keys

```python
import os
os.environ["GEMINI_API_KEY"] = "your-api-key"
```

# Gemini-Pro
## Sample Usage
```python
from litellm import completion
Expand Down
11 changes: 11 additions & 0 deletions docs/my-website/docs/providers/vertex.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@ import TabItem from '@theme/TabItem';

# VertexAI [Anthropic, Gemini, Model Garden]


| Property | Details |
|-------|-------|
| Description | Vertex AI is a fully-managed AI development platform for building and using generative AI. |
| Provider Route on LiteLLM | `vertex_ai/` |
| Link to Provider Doc | [Vertex AI ↗](https://cloud.google.com/vertex-ai) |
| Base URL | [https://{vertex_location}-aiplatform.googleapis.com/](https://{vertex_location}-aiplatform.googleapis.com/) |

<br />
<br />

<a target="_blank" href="https://colab.research.google.com/github/BerriAI/litellm/blob/main/cookbook/liteLLM_VertextAI_Example.ipynb">
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
</a>
Expand Down
4 changes: 1 addition & 3 deletions docs/my-website/docs/proxy/cost_tracking.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,9 +284,7 @@ Output from script

:::info

Customer This is the value of `user_id` passed when calling [`/key/generate`](https://litellm-api.up.railway.app/#/key%20management/generate_key_fn_key_generate_post)

[this is `user` passed to `/chat/completions` request](#how-to-track-spend-with-litellm)
Customer [this is `user` passed to `/chat/completions` request](#how-to-track-spend-with-litellm)
- [LiteLLM API key](virtual_keys.md)


Expand Down
5 changes: 3 additions & 2 deletions litellm/caching/caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ def get_cache_key(self, *args, **kwargs) -> str:
cache_key += f"{str(param)}: {str(param_value)}"

verbose_logger.debug("\nCreated cache key: %s", cache_key)
hashed_cache_key = self._get_hashed_cache_key(cache_key)
hashed_cache_key = Cache._get_hashed_cache_key(cache_key)
hashed_cache_key = self._add_redis_namespace_to_cache_key(
hashed_cache_key, **kwargs
)
Expand Down Expand Up @@ -431,7 +431,8 @@ def _get_kwargs_to_exclude_from_cache_key(self) -> Set[str]:
"""
return set(["metadata"])

def _get_hashed_cache_key(self, cache_key: str) -> str:
@staticmethod
def _get_hashed_cache_key(cache_key: str) -> str:
"""
Get the hashed cache key for the given cache key.

Expand Down
107 changes: 76 additions & 31 deletions litellm/caching/dual_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
- async_get_cache
"""

import time
import traceback
from typing import TYPE_CHECKING, Any, List, Optional
from typing import TYPE_CHECKING, Any, List, Optional, Tuple

import litellm
from litellm._logging import print_verbose, verbose_logger
Expand All @@ -25,6 +26,19 @@
else:
Span = Any

from collections import OrderedDict


class LimitedSizeOrderedDict(OrderedDict):
def __init__(self, *args, max_size=100, **kwargs):
super().__init__(*args, **kwargs)
self.max_size = max_size

def __setitem__(self, key, value):
# If inserting a new key exceeds max size, remove the oldest item
if len(self) >= self.max_size:
self.popitem(last=False)
super().__setitem__(key, value)

class DualCache(BaseCache):
"""
Expand All @@ -39,13 +53,18 @@ def __init__(
redis_cache: Optional[RedisCache] = None,
default_in_memory_ttl: Optional[float] = None,
default_redis_ttl: Optional[float] = None,
default_redis_batch_cache_expiry: float = 1,
default_max_redis_batch_cache_size: int = 100,
) -> None:
super().__init__()
# If in_memory_cache is not provided, use the default InMemoryCache
self.in_memory_cache = in_memory_cache or InMemoryCache()
# If redis_cache is not provided, use the default RedisCache
self.redis_cache = redis_cache

self.last_redis_batch_access_time = LimitedSizeOrderedDict(
max_size=default_max_redis_batch_cache_size
)
self.redis_batch_cache_expiry = default_redis_batch_cache_expiry
self.default_in_memory_ttl = (
default_in_memory_ttl or litellm.default_in_memory_ttl
)
Expand Down Expand Up @@ -150,20 +169,34 @@ def batch_get_cache(
- for the none values in the result
- check the redis cache
"""
sublist_keys = [
key for key, value in zip(keys, result) if value is None
]
# If not found in in-memory cache, try fetching from Redis
redis_result = self.redis_cache.batch_get_cache(
sublist_keys, parent_otel_span=parent_otel_span
)
if redis_result is not None:
# Update in-memory cache with the value from Redis
for key in redis_result:
self.in_memory_cache.set_cache(key, redis_result[key], **kwargs)
# Track the last access time for these keys
current_time = time.time()
key_tuple = tuple(keys)

# Only hit Redis if the last access time was more than 5 seconds ago
if (
key_tuple not in self.last_redis_batch_access_time
or current_time - self.last_redis_batch_access_time[key_tuple]
>= self.redis_batch_cache_expiry
):

sublist_keys = [
key for key, value in zip(keys, result) if value is None
]
# If not found in in-memory cache, try fetching from Redis
redis_result = self.redis_cache.batch_get_cache(
sublist_keys, parent_otel_span=parent_otel_span
)
if redis_result is not None:
# Update in-memory cache with the value from Redis
for key in redis_result:
self.in_memory_cache.set_cache(
key, redis_result[key], **kwargs
)

for key, value in redis_result.items():
result[keys.index(key)] = value

for key, value in redis_result.items():
result[keys.index(key)] = value

print_verbose(f"async batch get cache: cache result: {result}")
return result
Expand Down Expand Up @@ -227,29 +260,41 @@ async def async_batch_get_cache(

if in_memory_result is not None:
result = in_memory_result

if None in result and self.redis_cache is not None and local_only is False:
"""
- for the none values in the result
- check the redis cache
"""
sublist_keys = [
key for key, value in zip(keys, result) if value is None
]
# If not found in in-memory cache, try fetching from Redis
redis_result = await self.redis_cache.async_batch_get_cache(
sublist_keys, parent_otel_span=parent_otel_span
)
# Track the last access time for these keys
current_time = time.time()
key_tuple = tuple(keys)

# Only hit Redis if the last access time was more than 5 seconds ago
if (
key_tuple not in self.last_redis_batch_access_time
or current_time - self.last_redis_batch_access_time[key_tuple]
>= self.redis_batch_cache_expiry
):
sublist_keys = [
key for key, value in zip(keys, result) if value is None
]
# If not found in in-memory cache, try fetching from Redis
redis_result = await self.redis_cache.async_batch_get_cache(
sublist_keys, parent_otel_span=parent_otel_span
)

if redis_result is not None:
# Update in-memory cache with the value from Redis

if redis_result is not None:
# Update in-memory cache with the value from Redis
for key, value in redis_result.items():
if value is not None:
await self.in_memory_cache.async_set_cache(
key, redis_result[key], **kwargs
)
for key, value in redis_result.items():
if value is not None:
await self.in_memory_cache.async_set_cache(
key, redis_result[key], **kwargs
)
for key, value in redis_result.items():
index = keys.index(key)
result[index] = value
index = keys.index(key)
result[index] = value

return result
except Exception:
Expand Down
38 changes: 25 additions & 13 deletions litellm/integrations/prometheus.py
Original file line number Diff line number Diff line change
Expand Up @@ -849,9 +849,13 @@ def set_llm_deployment_success_metrics(
):
try:
verbose_logger.debug("setting remaining tokens requests metric")
standard_logging_payload: StandardLoggingPayload = request_kwargs.get(
"standard_logging_object", {}
standard_logging_payload: Optional[StandardLoggingPayload] = (
request_kwargs.get("standard_logging_object")
)

if standard_logging_payload is None:
return

model_group = standard_logging_payload["model_group"]
api_base = standard_logging_payload["api_base"]
_response_headers = request_kwargs.get("response_headers")
Expand All @@ -862,22 +866,30 @@ def set_llm_deployment_success_metrics(
_model_info = _metadata.get("model_info") or {}
model_id = _model_info.get("id", None)

remaining_requests = None
remaining_tokens = None
remaining_requests: Optional[int] = None
remaining_tokens: Optional[int] = None
if additional_headers := standard_logging_payload["hidden_params"][
"additional_headers"
]:
remaining_requests = additional_headers.get(
"x_ratelimit_remaining_requests", None
)
remaining_tokens = additional_headers.get(
"x_ratelimit_remaining_tokens", None
)
# OpenAI / OpenAI Compatible headers
if (
_response_headers
and "x-ratelimit-remaining-requests" in _response_headers
additional_headers
and "x_ratelimit_remaining_requests" in additional_headers
):
remaining_requests = _response_headers["x-ratelimit-remaining-requests"]
remaining_requests = additional_headers[
"x_ratelimit_remaining_requests"
]
if (
_response_headers
and "x-ratelimit-remaining-tokens" in _response_headers
additional_headers
and "x_ratelimit_remaining_tokens" in additional_headers
):
remaining_tokens = _response_headers["x-ratelimit-remaining-tokens"]
verbose_logger.debug(
f"remaining requests: {remaining_requests}, remaining tokens: {remaining_tokens}"
)
remaining_tokens = additional_headers["x_ratelimit_remaining_tokens"]

if remaining_requests:
"""
Expand Down
17 changes: 9 additions & 8 deletions litellm/integrations/prometheus_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import litellm
from litellm._logging import print_verbose, verbose_logger
from litellm.types.integrations.prometheus import LATENCY_BUCKETS
from litellm.types.services import ServiceLoggerPayload, ServiceTypes


Expand Down Expand Up @@ -80,29 +81,29 @@ def is_metric_registered(self, metric_name) -> bool:
return True
return False

def get_metric(self, metric_name):
for metric in self.REGISTRY.collect():
for sample in metric.samples:
if metric_name == sample.name:
return metric
return None
def _get_metric(self, metric_name):
"""
Helper function to get a metric from the registry by name.
"""
return self.REGISTRY._names_to_collectors.get(metric_name)

def create_histogram(self, service: str, type_of_request: str):
metric_name = "litellm_{}_{}".format(service, type_of_request)
is_registered = self.is_metric_registered(metric_name)
if is_registered:
return self.get_metric(metric_name)
return self._get_metric(metric_name)
return self.Histogram(
metric_name,
"Latency for {} service".format(service),
labelnames=[service],
buckets=LATENCY_BUCKETS,
)

def create_counter(self, service: str, type_of_request: str):
metric_name = "litellm_{}_{}".format(service, type_of_request)
is_registered = self.is_metric_registered(metric_name)
if is_registered:
return self.get_metric(metric_name)
return self._get_metric(metric_name)
return self.Counter(
metric_name,
"Total {} for {} service".format(type_of_request, service),
Expand Down
2 changes: 1 addition & 1 deletion litellm/litellm_core_utils/core_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def _get_parent_otel_span_from_kwargs(
) -> Union[Span, None]:
try:
if kwargs is None:
raise ValueError("kwargs is None")
return None
litellm_params = kwargs.get("litellm_params")
_metadata = kwargs.get("metadata") or {}
if "litellm_parent_otel_span" in _metadata:
Expand Down
Loading