The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(google_ai_studio): working context caching (#5421)
Krish Dholakia559a6ad826b5
diff --git a/litellm/llms/vertex_ai_and_google_ai_studio/context_caching/transformation.py b/litellm/llms/vertex_ai_and_google_ai_studio/context_caching/transformation.pyindex d394cafd3a3..86fb757b729 100644--- a/litellm/llms/vertex_ai_and_google_ai_studio/context_caching/transformation.py+++ b/litellm/llms/vertex_ai_and_google_ai_studio/context_caching/transformation.py@@ -11,7 +11,7 @@ from litellm.types.llms.vertex_ai import CachedContentRequestBody, SystemInstrucfrom litellm.utils import is_cached_messagefrom ..common_utils import VertexAIError, get_supports_system_message-from ..gemini.transformation import transform_system_message+from ..gemini.transformation import _transform_system_messagefrom ..gemini.vertex_and_google_ai_studio_gemini import (_gemini_convert_messages_with_history,)@@ -75,7 +75,7 @@ def transform_openai_messages_to_gemini_context_caching(model=model, custom_llm_provider="gemini")- transformed_system_messages, new_messages = transform_system_message(+ transformed_system_messages, new_messages = _transform_system_message(supports_system_message=supports_system_message, messages=messages)@@ -83,7 +83,7 @@ def transform_openai_messages_to_gemini_context_caching(data = CachedContentRequestBody(contents=transformed_messages,model="models/{}".format(model),- name="cachedContents/{}".format(cache_key),+ displayName=cache_key,)if transformed_system_messages is not None:data["system_instruction"] = transformed_system_messagesdiff --git a/litellm/llms/vertex_ai_and_google_ai_studio/context_caching/vertex_ai_context_caching.py b/litellm/llms/vertex_ai_and_google_ai_studio/context_caching/vertex_ai_context_caching.pyindex 991883e4090..d087d721295 100644--- a/litellm/llms/vertex_ai_and_google_ai_studio/context_caching/vertex_ai_context_caching.py+++ b/litellm/llms/vertex_ai_and_google_ai_studio/context_caching/vertex_ai_context_caching.py@@ -9,6 +9,7 @@ from litellm.litellm_core_utils.litellm_logging import Loggingfrom litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandlerfrom litellm.llms.openai import AllMessageValuesfrom litellm.types.llms.vertex_ai import (+ CachedContentListAllResponseBody,RequestBody,VertexAICachedContentResponseObject,)@@ -38,7 +39,6 @@ class ContextCachingEndpoints:gemini_api_key: Optional[str],custom_llm_provider: Literal["gemini"],api_base: Optional[str],- cached_key: Optional[str],) -> Tuple[Optional[str], str]:"""Internal function. Returns the token and url for the call.@@ -51,16 +51,9 @@ class ContextCachingEndpoints:if custom_llm_provider == "gemini":auth_header = Noneendpoint = "cachedContents"- if cached_key is not None:- url = "https://generativelanguage.googleapis.com/v1beta/{}/{}?key={}".format(- endpoint, cached_key, gemini_api_key- )- else:- url = (- "https://generativelanguage.googleapis.com/v1beta/{}?key={}".format(- endpoint, gemini_api_key- )- )+ url = "https://generativelanguage.googleapis.com/v1beta/{}?key={}".format(+ endpoint, gemini_api_key+ )else:raise NotImplementedError@@ -85,14 +78,22 @@ class ContextCachingEndpoints:api_key: str,api_base: Optional[str],logging_obj: Logging,- ) -> bool:- """Checks if content already cached."""+ ) -> Optional[str]:+ """+ Checks if content already cached.++ Currently, checks cache list, for cache key == displayName, since Google doesn't let us set the name of the cache (their API docs are out of sync with actual implementation).++ Returns+ - cached_content_name - str - cached content name stored on google. (if found.)+ OR+ - None+ """_, url = self._get_token_and_url(gemini_api_key=api_key,custom_llm_provider="gemini",api_base=api_base,- cached_key=cache_key,)try:## LOGGING@@ -108,15 +109,94 @@ class ContextCachingEndpoints:resp = client.get(url=url, headers=headers)resp.raise_for_status()- return Trueexcept httpx.HTTPStatusError as e:if e.response.status_code == 403:- return False+ return None+ raise VertexAIError(+ status_code=e.response.status_code, message=e.response.text+ )+ except Exception as e:+ raise VertexAIError(status_code=500, message=str(e))+ raw_response = resp.json()+ logging_obj.post_call(original_response=raw_response)++ if "cachedContents" not in raw_response:+ return None++ all_cached_items = CachedContentListAllResponseBody(**raw_response)++ for cached_item in all_cached_items["cachedContents"]:+ if (+ cached_item.get("displayName") is not None+ and cached_item["displayName"] == cache_key+ ):+ return cached_item.get("name")++ return None++ async def async_check_cache(+ self,+ cache_key: str,+ client: AsyncHTTPHandler,+ headers: dict,+ api_key: str,+ api_base: Optional[str],+ logging_obj: Logging,+ ) -> Optional[str]:+ """+ Checks if content already cached.++ Currently, checks cache list, for cache key == displayName, since Google doesn't let us set the name of the cache (their API docs are out of sync with actual implementation).++ Returns+ - cached_content_name - str - cached content name stored on google. (if found.)+ OR+ - None+ """++ _, url = self._get_token_and_url(+ gemini_api_key=api_key,+ custom_llm_provider="gemini",+ api_base=api_base,+ )+ try:+ ## LOGGING+ logging_obj.pre_call(+ input="",+ api_key="",+ additional_args={+ "complete_input_dict": {},+ "api_base": url,+ "headers": headers,+ },+ )++ resp = await client.get(url=url, headers=headers)+ resp.raise_for_status()+ except httpx.HTTPStatusError as e:+ if e.response.status_code == 403:+ return Noneraise VertexAIError(status_code=e.response.status_code, message=e.response.text)except Exception as e:raise VertexAIError(status_code=500, message=str(e))+ raw_response = resp.json()+ logging_obj.post_call(original_response=raw_response)++ if "cachedContents" not in raw_response:+ return None++ all_cached_items = CachedContentListAllResponseBody(**raw_response)++ for cached_item in all_cached_items["cachedContents"]:+ if (+ cached_item.get("displayName") is not None+ and cached_item["displayName"] == cache_key+ ):+ return cached_item.get("name")++ return Nonedef check_and_create_cache(self,@@ -124,7 +204,7 @@ class ContextCachingEndpoints:api_key: str,api_base: Optional[str],model: str,- client: Optional[Union[HTTPHandler, AsyncHTTPHandler]],+ client: Optional[HTTPHandler],timeout: Optional[Union[float, httpx.Timeout]],logging_obj: Logging,extra_headers: Optional[dict] = None,@@ -148,7 +228,6 @@ class ContextCachingEndpoints:gemini_api_key=api_key,custom_llm_provider="gemini",api_base=api_base,- cached_key=None,)headers = {@@ -178,7 +257,7 @@ class ContextCachingEndpoints:## CHECK IF CACHED ALREADYgenerated_cache_key = local_cache_obj.get_cache_key(messages=cached_messages)- cache_exists = self.check_cache(+ google_cache_name = self.check_cache(cache_key=generated_cache_key,client=client,headers=headers,@@ -186,8 +265,8 @@ class ContextCachingEndpoints:api_base=api_base,logging_obj=logging_obj,)- if cache_exists:- return non_cached_messages, generated_cache_key+ if google_cache_name:+ return non_cached_messages, google_cache_name## TRANSFORM REQUESTcached_content_request_body = (@@ -224,8 +303,110 @@ class ContextCachingEndpoints:)return (non_cached_messages, cached_content_response_obj["name"])- def async_create_cache(self):- pass+ async def async_check_and_create_cache(+ self,+ messages: List[AllMessageValues], # receives openai format messages+ api_key: str,+ api_base: Optional[str],+ model: str,+ client: Optional[AsyncHTTPHandler],+ timeout: Optional[Union[float, httpx.Timeout]],+ logging_obj: Logging,+ extra_headers: Optional[dict] = None,+ cached_content: Optional[str] = None,+ ) -> Tuple[List[AllMessageValues], Optional[str]]:+ """+ Receives+ - messages: List of dict - messages in the openai format++ Returns+ - messages - List[dict] - filtered list of messages in the openai format.+ - cached_content - str - the cache content id, to be passed in the gemini request body++ Follows - https://ai.google.dev/api/caching#request-body+ """+ if cached_content is not None:+ return messages, cached_content++ ## AUTHORIZATION ##+ token, url = self._get_token_and_url(+ gemini_api_key=api_key,+ custom_llm_provider="gemini",+ api_base=api_base,+ )++ headers = {+ "Content-Type": "application/json",+ }+ if token is not None:+ headers["Authorization"] = f"Bearer {token}"+ if extra_headers is not None:+ headers.update(extra_headers)++ if client is None or not isinstance(client, AsyncHTTPHandler):+ _params = {}+ if timeout is not None:+ if isinstance(timeout, float) or isinstance(timeout, int):+ timeout = httpx.Timeout(timeout)+ _params["timeout"] = timeout+ client = AsyncHTTPHandler(**_params) # type: ignore+ else:+ client = client++ cached_messages, non_cached_messages = separate_cached_messages(+ messages=messages+ )++ if len(cached_messages) == 0:+ return messages, None++ ## CHECK IF CACHED ALREADY+ generated_cache_key = local_cache_obj.get_cache_key(messages=cached_messages)+ google_cache_name = await self.async_check_cache(+ cache_key=generated_cache_key,+ client=client,+ headers=headers,+ api_key=api_key,+ api_base=api_base,+ logging_obj=logging_obj,+ )+ if google_cache_name:+ return non_cached_messages, google_cache_name++ ## TRANSFORM REQUEST+ cached_content_request_body = (+ transform_openai_messages_to_gemini_context_caching(+ model=model, messages=cached_messages, cache_key=generated_cache_key+ )+ )++ ## LOGGING+ logging_obj.pre_call(+ input=messages,+ api_key="",+ additional_args={+ "complete_input_dict": cached_content_request_body,+ "api_base": url,+ "headers": headers,+ },+ )++ try:+ response = await client.post(+ url=url, headers=headers, json=cached_content_request_body # type: ignore+ )+ response.raise_for_status()+ except httpx.HTTPStatusError as err:+ error_code = err.response.status_code+ raise VertexAIError(status_code=error_code, message=err.response.text)+ except httpx.TimeoutException:+ raise VertexAIError(status_code=408, message="Timeout error occurred.")++ raw_response_cached = response.json()+ cached_content_response_obj = VertexAICachedContentResponseObject(+ name=raw_response_cached.get("name"), model=raw_response_cached.get("model")+ )+ return (non_cached_messages, cached_content_response_obj["name"])def get_cache(self):passdiff --git a/litellm/llms/vertex_ai_and_google_ai_studio/gemini/transformation.py b/litellm/llms/vertex_ai_and_google_ai_studio/gemini/transformation.pyindex a25cd2db7a2..2dc8a013521 100644--- a/litellm/llms/vertex_ai_and_google_ai_studio/gemini/transformation.py+++ b/litellm/llms/vertex_ai_and_google_ai_studio/gemini/transformation.py@@ -4,13 +4,184 @@ Transformation logic from OpenAI format to Gemini format.Why separate file? Make it easy to see how transformation works"""-from typing import List, Optional, Tuple+from typing import List, Literal, Optional, Tuple, Union+import httpx++import litellm+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler+from litellm.llms.prompt_templates.factory import response_schema_promptfrom litellm.types.llms.openai import AllMessageValues-from litellm.types.llms.vertex_ai import PartType, SystemInstructions+from litellm.types.llms.vertex_ai import (+ GenerationConfig,+ PartType,+ RequestBody,+ SafetSettingsConfig,+ SystemInstructions,+ ToolConfig,+ Tools,+)++from ..common_utils import get_supports_system_message+from ..vertex_ai_non_gemini import _gemini_convert_messages_with_history+++def _transform_request_body(+ messages: List[AllMessageValues],+ model: str,+ optional_params: dict,+ custom_llm_provider: Literal["vertex_ai", "vertex_ai_beta", "gemini"],+ litellm_params: dict,+ cached_content: Optional[str],+) -> RequestBody:+ """+ Common transformation logic across sync + async Gemini /generateContent calls.+ """+ # Separate system prompt from rest of message+ supports_system_message = get_supports_system_message(+ model=model, custom_llm_provider=custom_llm_provider+ )+ system_instructions, messages = _transform_system_message(+ supports_system_message=supports_system_message, messages=messages+ )+ # Checks for 'response_schema' support - if passed in+ if "response_schema" in optional_params:+ supports_response_schema = litellm.supports_response_schema(+ model=model, custom_llm_provider="vertex_ai"+ )+ if supports_response_schema is False:+ user_response_schema_message = response_schema_prompt(+ model=model, response_schema=optional_params.get("response_schema") # type: ignore+ )+ messages.append({"role": "user", "content": user_response_schema_message})+ optional_params.pop("response_schema")++ # Check for any 'litellm_param_*' set during optional param mapping++ remove_keys = []+ for k, v in optional_params.items():+ if k.startswith("litellm_param_"):+ litellm_params.update({k: v})+ remove_keys.append(k)++ optional_params = {k: v for k, v in optional_params.items() if k not in remove_keys}++ try:+ content = _gemini_convert_messages_with_history(messages=messages)+ tools: Optional[Tools] = optional_params.pop("tools", None)+ tool_choice: Optional[ToolConfig] = optional_params.pop("tool_choice", None)+ safety_settings: Optional[List[SafetSettingsConfig]] = optional_params.pop(+ "safety_settings", None+ ) # type: ignore+ generation_config: Optional[GenerationConfig] = GenerationConfig(+ **optional_params+ )+ data = RequestBody(contents=content)+ if system_instructions is not None:+ data["system_instruction"] = system_instructions+ if tools is not None:+ data["tools"] = tools+ if tool_choice is not None:+ data["toolConfig"] = tool_choice+ if safety_settings is not None:+ data["safetySettings"] = safety_settings+ if generation_config is not None:+ data["generationConfig"] = generation_config+ if cached_content is not None:+ data["cachedContent"] = cached_content+ except Exception as e:+ raise e++ return data++def sync_transform_request_body(+ gemini_api_key: Optional[str],+ messages: List[AllMessageValues],+ api_base: Optional[str],+ model: str,+ client: Optional[HTTPHandler],+ timeout: Optional[Union[float, httpx.Timeout]],+ extra_headers: Optional[dict],+ optional_params: dict,+ logging_obj: litellm.litellm_core_utils.litellm_logging.Logging,+ custom_llm_provider: Literal["vertex_ai", "vertex_ai_beta", "gemini"],+ litellm_params: dict,+) -> RequestBody:+ from ..context_caching.vertex_ai_context_caching import ContextCachingEndpoints-def transform_system_message(+ context_caching_endpoints = ContextCachingEndpoints()++ if gemini_api_key is not None:+ messages, cached_content = context_caching_endpoints.check_and_create_cache(+ messages=messages,+ api_key=gemini_api_key,+ api_base=api_base,+ model=model,+ client=client,+ timeout=timeout,+ extra_headers=extra_headers,+ cached_content=optional_params.pop("cached_content", None),+ logging_obj=logging_obj,+ )+ else: # [TODO] implement context caching for gemini as well+ cached_content = optional_params.pop("cached_content", None)++ return _transform_request_body(+ messages=messages,+ model=model,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ cached_content=cached_content,+ optional_params=optional_params,+ )+++async def async_transform_request_body(+ gemini_api_key: Optional[str],+ messages: List[AllMessageValues],+ api_base: Optional[str],+ model: str,+ client: Optional[AsyncHTTPHandler],+ timeout: Optional[Union[float, httpx.Timeout]],+ extra_headers: Optional[dict],+ optional_params: dict,+ logging_obj: litellm.litellm_core_utils.litellm_logging.Logging,+ custom_llm_provider: Literal["vertex_ai", "vertex_ai_beta", "gemini"],+ litellm_params: dict,+) -> RequestBody:+ from ..context_caching.vertex_ai_context_caching import ContextCachingEndpoints++ context_caching_endpoints = ContextCachingEndpoints()++ if gemini_api_key is not None:+ messages, cached_content = (+ await context_caching_endpoints.async_check_and_create_cache(+ messages=messages,+ api_key=gemini_api_key,+ api_base=api_base,+ model=model,+ client=client,+ timeout=timeout,+ extra_headers=extra_headers,+ cached_content=optional_params.pop("cached_content", None),+ logging_obj=logging_obj,+ )+ )+ else: # [TODO] implement context caching for gemini as well+ cached_content = optional_params.pop("cached_content", None)++ return _transform_request_body(+ messages=messages,+ model=model,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ cached_content=cached_content,+ optional_params=optional_params,+ )+++def _transform_system_message(supports_system_message: bool, messages: List[AllMessageValues]) -> Tuple[Optional[SystemInstructions], List[AllMessageValues]]:"""@@ -45,3 +216,15 @@ def transform_system_message(return SystemInstructions(parts=system_content_blocks), messagesreturn None, messages+++def set_headers(auth_header: Optional[str], extra_headers: Optional[dict]) -> dict:+ headers = {+ "Content-Type": "application/json",+ }+ if auth_header is not None:+ headers["Authorization"] = f"Bearer {auth_header}"+ if extra_headers is not None:+ headers.update(extra_headers)++ return headersdiff --git a/litellm/llms/vertex_ai_and_google_ai_studio/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai_and_google_ai_studio/gemini/vertex_and_google_ai_studio_gemini.pyindex 819a94cb0c1..ed7cd8dbaba 100644--- a/litellm/llms/vertex_ai_and_google_ai_studio/gemini/vertex_and_google_ai_studio_gemini.py+++ b/litellm/llms/vertex_ai_and_google_ai_studio/gemini/vertex_and_google_ai_studio_gemini.py@@ -62,10 +62,11 @@ from ..common_utils import (all_gemini_url_modes,get_supports_system_message,)-from ..context_caching.vertex_ai_context_caching import ContextCachingEndpoints-from .transformation import transform_system_message--context_caching_endpoints = ContextCachingEndpoints()+from .transformation import (+ async_transform_request_body,+ set_headers,+ sync_transform_request_body,+)class VertexAIConfig:@@ -824,7 +825,7 @@ class VertexLLM(BaseLLM):optional_params: dict,litellm_params: dict,api_key: str,- data: Union[dict, str],+ data: Union[dict, str, RequestBody],messages: List,print_verbose,encoding,@@ -1231,7 +1232,7 @@ class VertexLLM(BaseLLM):api_base: str,model_response: ModelResponse,print_verbose: Callable,- data: str,+ data: dict,timeout: Optional[Union[float, httpx.Timeout]],encoding,logging_obj,@@ -1242,6 +1243,9 @@ class VertexLLM(BaseLLM):headers={},client: Optional[AsyncHTTPHandler] = None,) -> CustomStreamWrapper:+ request_body = await async_transform_request_body(**data) # type: ignore++ request_body_str = json.dumps(request_body)streaming_response = CustomStreamWrapper(completion_stream=None,make_call=partial(@@ -1249,7 +1253,7 @@ class VertexLLM(BaseLLM):client=client,api_base=api_base,headers=headers,- data=data,+ data=request_body_str,model=model,messages=messages,logging_obj=logging_obj,@@ -1267,17 +1271,19 @@ class VertexLLM(BaseLLM):api_base: str,model_response: ModelResponse,print_verbose: Callable,- data: str,+ data: dict,timeout: Optional[Union[float, httpx.Timeout]],encoding,logging_obj,stream,optional_params: dict,litellm_params: dict,+ headers: dict,logger_fn=None,- headers={},client: Optional[AsyncHTTPHandler] = None,) -> Union[ModelResponse, CustomStreamWrapper]:++ request_body = await async_transform_request_body(**data) # type: ignoreif client is None:_params = {}if timeout is not None:@@ -1289,7 +1295,7 @@ class VertexLLM(BaseLLM):client = client # type: ignoretry:- response = await client.post(api_base, headers=headers, json=data) # type: ignore+ response = await client.post(api_base, headers=headers, json=request_body) # type: ignoreresponse.raise_for_status()except httpx.HTTPStatusError as err:error_code = err.response.status_code@@ -1303,7 +1309,7 @@ class VertexLLM(BaseLLM):model_response=model_response,logging_obj=logging_obj,api_key="",- data=data,+ data=request_body,messages=messages,print_verbose=print_verbose,optional_params=optional_params,@@ -1353,100 +1359,21 @@ class VertexLLM(BaseLLM):should_use_v1beta1_features=should_use_v1beta1_features,)- ## TRANSFORMATION ##- ### CHECK CONTEXT CACHING ###- if gemini_api_key is not None:- messages, cached_content = context_caching_endpoints.check_and_create_cache(- messages=messages,- api_key=gemini_api_key,- api_base=api_base,- model=model,- client=client,- timeout=timeout,- extra_headers=extra_headers,- cached_content=optional_params.pop("cached_content", None),- logging_obj=logging_obj,- )- else: # [TODO] implement context caching for gemini as well- cached_content = optional_params.pop("cached_content", None)-- # Separate system prompt from rest of message- supports_system_message = get_supports_system_message(- model=model, custom_llm_provider=custom_llm_provider- )- system_instructions, messages = transform_system_message(- supports_system_message=supports_system_message, messages=messages- )- # Checks for 'response_schema' support - if passed in- if "response_schema" in optional_params:- supports_response_schema = litellm.supports_response_schema(- model=model, custom_llm_provider="vertex_ai"- )- if supports_response_schema is False:- user_response_schema_message = response_schema_prompt(- model=model, response_schema=optional_params.get("response_schema") # type: ignore- )- messages.append(- {"role": "user", "content": user_response_schema_message}- )- optional_params.pop("response_schema")-- # Check for any 'litellm_param_*' set during optional param mapping-- remove_keys = []- for k, v in optional_params.items():- if k.startswith("litellm_param_"):- litellm_params.update({k: v})- remove_keys.append(k)-- optional_params = {- k: v for k, v in optional_params.items() if k not in remove_keys+ transform_request_params = {+ "gemini_api_key": gemini_api_key,+ "messages": messages,+ "api_base": api_base,+ "model": model,+ "client": client,+ "timeout": timeout,+ "extra_headers": extra_headers,+ "optional_params": optional_params,+ "logging_obj": logging_obj,+ "custom_llm_provider": custom_llm_provider,+ "litellm_params": litellm_params,}- try:- content = _gemini_convert_messages_with_history(messages=messages)- tools: Optional[Tools] = optional_params.pop("tools", None)- tool_choice: Optional[ToolConfig] = optional_params.pop("tool_choice", None)- safety_settings: Optional[List[SafetSettingsConfig]] = optional_params.pop(- "safety_settings", None- ) # type: ignore- generation_config: Optional[GenerationConfig] = GenerationConfig(- **optional_params- )- data = RequestBody(contents=content)- if system_instructions is not None:- data["system_instruction"] = system_instructions- if tools is not None:- data["tools"] = tools- if tool_choice is not None:- data["toolConfig"] = tool_choice- if safety_settings is not None:- data["safetySettings"] = safety_settings- if generation_config is not None:- data["generationConfig"] = generation_config- if cached_content is not None:- data["cachedContent"] = cached_content-- headers = {- "Content-Type": "application/json",- }- if auth_header is not None:- headers["Authorization"] = f"Bearer {auth_header}"- if extra_headers is not None:- headers.update(extra_headers)- except Exception as e:- raise e-- ## LOGGING- logging_obj.pre_call(- input=messages,- api_key="",- additional_args={- "complete_input_dict": data,- "api_base": url,- "headers": headers,- },- )+ headers = set_headers(auth_header=auth_header, extra_headers=extra_headers)### ROUTING (ASYNC, STREAMING, SYNC)if acompletion:@@ -1455,7 +1382,6 @@ class VertexLLM(BaseLLM):return self.async_streaming(model=model,messages=messages,- data=json.dumps(data), # type: ignoreapi_base=url,model_response=model_response,print_verbose=print_verbose,@@ -1465,15 +1391,16 @@ class VertexLLM(BaseLLM):stream=stream,litellm_params=litellm_params,logger_fn=logger_fn,- headers=headers,timeout=timeout,client=client, # type: ignore+ data=transform_request_params,+ headers=headers,)### ASYNC COMPLETIONreturn self.async_completion(model=model,messages=messages,- data=data, # type: ignore+ data=transform_request_params, # type: ignoreapi_base=url,model_response=model_response,print_verbose=print_verbose,@@ -1483,24 +1410,39 @@ class VertexLLM(BaseLLM):stream=stream,litellm_params=litellm_params,logger_fn=logger_fn,- headers=headers,timeout=timeout,client=client, # type: ignore+ headers=headers,)## SYNC STREAMING CALL ##+ ## TRANSFORMATION ##+ data = sync_transform_request_body(**transform_request_params)++ ## LOGGING+ logging_obj.pre_call(+ input=messages,+ api_key="",+ additional_args={+ "complete_input_dict": data,+ "api_base": url,+ "headers": headers,+ },+ )+if stream is not None and stream is True:+ request_data_str = json.dumps(data)streaming_response = CustomStreamWrapper(completion_stream=None,make_call=partial(make_sync_call,client=None,api_base=url,- headers=headers, # type: ignore- data=json.dumps(data),+ data=request_data_str,model=model,messages=messages,logging_obj=logging_obj,+ headers=headers,),model=model,custom_llm_provider="vertex_ai_beta",@@ -1509,6 +1451,7 @@ class VertexLLM(BaseLLM):return streaming_response## COMPLETION CALL ##+if client is None or isinstance(client, AsyncHTTPHandler):_params = {}if timeout is not None:diff --git a/litellm/tests/test_amazing_vertex_completion.py b/litellm/tests/test_amazing_vertex_completion.pyindex 02683de158d..a4238995dcb 100644--- a/litellm/tests/test_amazing_vertex_completion.py+++ b/litellm/tests/test_amazing_vertex_completion.py@@ -2290,61 +2290,98 @@ def mock_gemini_request(*args, **kwargs):return mock_response-gemini_context_caching_messages = [- # System Message- {- "role": "system",- "content": [- {- "type": "text",- "text": "Here is the full text of a complex legal agreement" * 4000,- "cache_control": {"type": "ephemeral"},- }- ],- },- # marked for caching with the cache_control parameter, so that this checkpoint can read from the previous cache.- {- "role": "user",- "content": [- {- "type": "text",- "text": "What are the key terms and conditions in this agreement?",- "cache_control": {"type": "ephemeral"},- }- ],- },- {- "role": "assistant",- "content": "Certainly! the key terms and conditions are the following: the contract is 1 year long for $10/mo",- },- # The final turn is marked with cache-control, for continuing in followups.- {- "role": "user",- "content": [- {- "type": "text",- "text": "What are the key terms and conditions in this agreement?",- }- ],- },-]+def mock_gemini_list_request(*args, **kwargs):+ from litellm.types.llms.vertex_ai import (+ CachedContent,+ CachedContentListAllResponseBody,+ )++ print(f"kwargs: {kwargs}")+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.headers = {"Content-Type": "application/json"}+ mock_response.json.return_value = CachedContentListAllResponseBody(+ cachedContents=[CachedContent(name="test", displayName="test")]+ )++ return mock_response+import uuid+++ "sync_mode",+ [True, False],+)@pytest.mark.asyncio-async def test_gemini_context_caching_anthropic_format():- from litellm.llms.custom_httpx.http_handler import HTTPHandler+async def test_gemini_context_caching_anthropic_format(sync_mode):+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandlerlitellm.set_verbose = True- client = HTTPHandler(concurrent_limit=1)+ gemini_context_caching_messages = [+ # System Message+ {+ "role": "system",+ "content": [+ {+ "type": "text",+ "text": "Here is the full text of a complex legal agreement {}".format(+ uuid.uuid4()+ )+ * 4000,+ "cache_control": {"type": "ephemeral"},+ }+ ],+ },+ # marked for caching with the cache_control parameter, so that this checkpoint can read from the previous cache.+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "What are the key terms and conditions in this agreement?",+ "cache_control": {"type": "ephemeral"},+ }+ ],+ },+ {+ "role": "assistant",+ "content": "Certainly! the key terms and conditions are the following: the contract is 1 year long for $10/mo",+ },+ # The final turn is marked with cache-control, for continuing in followups.+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "What are the key terms and conditions in this agreement?",+ }+ ],+ },+ ]+ if sync_mode:+ client = HTTPHandler(concurrent_limit=1)+ else:+ client = AsyncHTTPHandler(concurrent_limit=1)with patch.object(client, "post", side_effect=mock_gemini_request) as mock_client:try:- response = litellm.completion(- model="gemini/gemini-1.5-flash-001",- messages=gemini_context_caching_messages,- temperature=0.2,- max_tokens=10,- client=client,- )+ if sync_mode:+ response = litellm.completion(+ model="gemini/gemini-1.5-flash-001",+ messages=gemini_context_caching_messages,+ temperature=0.2,+ max_tokens=10,+ client=client,+ )+ else:+ response = await litellm.acompletion(+ model="gemini/gemini-1.5-flash-001",+ messages=gemini_context_caching_messages,+ temperature=0.2,+ max_tokens=10,+ client=client,+ )except Exception as e:print(e)@@ -2365,23 +2402,6 @@ async def test_gemini_context_caching_anthropic_format():# response.usage.cache_creation_input_tokens > 0# )- check_cache_mock = MagicMock()- client.get = check_cache_mock- try:- response = litellm.completion(- model="gemini/gemini-1.5-flash-001",- messages=gemini_context_caching_messages,- temperature=0.2,- max_tokens=10,- client=client,- )-- except Exception as e:- print(e)-- check_cache_mock.assert_called_once()- assert mock_client.call_count == 3-@pytest.mark.asyncioasync def test_partner_models_httpx_ai21():diff --git a/litellm/types/llms/vertex_ai.py b/litellm/types/llms/vertex_ai.pyindex aeda8679793..e502f44c393 100644--- a/litellm/types/llms/vertex_ai.py+++ b/litellm/types/llms/vertex_ai.py@@ -171,9 +171,26 @@ class TTL(TypedDict, total=False):nano: float+class UsageMetadata(TypedDict, total=False):+ promptTokenCount: int+ totalTokenCount: int+ candidatesTokenCount: int++class CachedContent(TypedDict, total=False):ttl: TTLexpire_time: str+ contents: List[ContentType]+ tools: List[Tools]+ createTime: str # "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z"+ updateTime: str # "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z"+ usageMetadata: UsageMetadata+ expireTime: str # "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z"+ name: str+ displayName: str+ model: str+ systemInstruction: ContentType+ toolConfig: ToolConfigclass RequestBody(TypedDict, total=False):@@ -193,10 +210,14 @@ class CachedContentRequestBody(TypedDict, total=False):toolConfig: ToolConfigmodel: Required[str] # Format: models/{model}ttl: str # ending in 's' - Example: "3.5s".- name: str # Format: cachedContents/{id}displayName: str+class CachedContentListAllResponseBody(TypedDict, total=False):+ cachedContents: List[CachedContent]+ nextPageToken: str++class SafetyRatings(TypedDict):category: HarmCategoryprobability: HarmProbability@@ -261,12 +282,6 @@ class PromptFeedback(TypedDict):blockReasonMessage: str-class UsageMetadata(TypedDict, total=False):- promptTokenCount: int- totalTokenCount: int- candidatesTokenCount: int--class GenerateContentResponseBody(TypedDict, total=False):candidates: Required[List[Candidates]]promptFeedback: PromptFeedback