Skip to content

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]

fix(vertex_ai): evaluate cached-block terminal turn after system extraction

mateo-berri819dc7812af8
diff --git a/litellm/llms/vertex_ai/context_caching/transformation.py b/litellm/llms/vertex_ai/context_caching/transformation.py
index a74e0c97abc..36c78974aca 100644
--- a/litellm/llms/vertex_ai/context_caching/transformation.py
+++ b/litellm/llms/vertex_ai/context_caching/transformation.py
@@ -156,11 +156,14 @@ def cached_messages_end_on_supported_turn(cached_messages: Sequence[AllMessageVa
"""
The cachedContents API rejects contents ending on a model turn, which is how it
classifies both assistant messages and tool results, with HTTP 400
- "Requests ending with a model turn are not supported".
+ "Requests ending with a model turn are not supported". System messages are
+ extracted into system_instruction before contents are built, so the terminal
+ turn is the last non-system message.
"""
- if not cached_messages:
- return False
- return cached_messages[-1].get("role") not in ("assistant", "tool", "function")
+ non_system_messages = tuple(message for message in cached_messages if message.get("role") != "system")
+ if not non_system_messages:
+ return bool(cached_messages)
+ return non_system_messages[-1].get("role") not in ("assistant", "tool", "function")
def transform_openai_messages_to_gemini_context_caching(
diff --git a/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py b/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py
index fe4cd4ec451..f8774e33ca4 100644
--- a/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py
+++ b/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py
@@ -311,8 +311,9 @@ class ContextCachingEndpoints(VertexBase):
if not cached_messages_end_on_supported_turn(cached_messages):
verbose_logger.debug(
- "Vertex AI context caching: cached message block ends on an assistant or "
- "tool turn, which the cachedContents API rejects. Skipping context caching."
+ "Vertex AI context caching: cached message block ends on a model turn once "
+ "system messages are extracted, which the cachedContents API rejects. "
+ "Skipping context caching."
)
return messages, optional_params, None
@@ -469,8 +470,9 @@ class ContextCachingEndpoints(VertexBase):
if not cached_messages_end_on_supported_turn(cached_messages):
verbose_logger.debug(
- "Vertex AI context caching: cached message block ends on an assistant or "
- "tool turn, which the cachedContents API rejects. Skipping context caching."
+ "Vertex AI context caching: cached message block ends on a model turn once "
+ "system messages are extracted, which the cachedContents API rejects. "
+ "Skipping context caching."
)
return messages, optional_params, None
diff --git a/tests/test_litellm/llms/vertex_ai/context_caching/test_vertex_ai_context_caching.py b/tests/test_litellm/llms/vertex_ai/context_caching/test_vertex_ai_context_caching.py
index 1aa724e551e..ad890d0c7ea 100644
--- a/tests/test_litellm/llms/vertex_ai/context_caching/test_vertex_ai_context_caching.py
+++ b/tests/test_litellm/llms/vertex_ai/context_caching/test_vertex_ai_context_caching.py
@@ -1458,18 +1458,24 @@ class TestContextCachingEndpoints:
"type": "function",
"function": {"name": "get_weather", "arguments": '{"location": "Boston"}'},
}
- cached_tail = (
- [
+ cached_tail = {
+ "assistant": [],
+ "tool": [
{
"role": "tool",
"tool_call_id": "call_abc123",
"content": "72F and sunny",
"cache_control": {"type": "ephemeral"},
}
- ]
- if final_cached_role == "tool"
- else []
- )
+ ],
+ "system": [
+ {
+ "role": "system",
+ "content": "Tool results are authoritative.",
+ "cache_control": {"type": "ephemeral"},
+ }
+ ],
+ }[final_cached_role]
return [
{
"role": "user",
@@ -1491,7 +1497,7 @@ class TestContextCachingEndpoints:
{"role": "user", "content": "What is the weather in Boston?"},
]
- @pytest.mark.parametrize("final_cached_role", ["assistant", "tool"])
+ @pytest.mark.parametrize("final_cached_role", ["assistant", "tool", "system"])
def test_check_and_create_cache_skips_when_cached_block_ends_on_model_turn(
self, final_cached_role
):
@@ -1525,7 +1531,7 @@ class TestContextCachingEndpoints:
self.mock_client.get.assert_not_called()
self.mock_client.post.assert_not_called()
- @pytest.mark.parametrize("final_cached_role", ["assistant", "tool"])
+ @pytest.mark.parametrize("final_cached_role", ["assistant", "tool", "system"])
@pytest.mark.asyncio
async def test_async_check_and_create_cache_skips_when_cached_block_ends_on_model_turn(
self, final_cached_role
@@ -1571,6 +1577,22 @@ def test_cached_messages_end_on_supported_turn():
)
assert cached_messages_end_on_supported_turn([{"role": "system", "content": "be brief"}]) is True
assert cached_messages_end_on_supported_turn([{"role": "assistant", "content": "hi"}]) is False
+ assert (
+ cached_messages_end_on_supported_turn(
+ [
+ {"role": "user", "content": "hello"},
+ {"role": "assistant", "content": "hi"},
+ {"role": "system", "content": "be brief"},
+ ]
+ )
+ is False
+ )
+ assert (
+ cached_messages_end_on_supported_turn(
+ [{"role": "system", "content": "be brief"}, {"role": "user", "content": "hello"}]
+ )
+ is True
+ )
assert (
cached_messages_end_on_supported_turn([{"role": "tool", "tool_call_id": "x", "content": "y"}])
is False