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]

Return anthropic thinking blocks on streaming + VertexAI Minor Fixes & Improvements (Thinking, Global regions, Parallel tool calling) (#11194)

Krish Dholakia05e0a6d8d5a5
diff --git a/litellm/llms/anthropic/chat/handler.py b/litellm/llms/anthropic/chat/handler.py
index 397aa1e047c..7f1fe0a4451 100644
--- a/litellm/llms/anthropic/chat/handler.py
+++ b/litellm/llms/anthropic/chat/handler.py
@@ -564,6 +564,24 @@ class ModelResponseIterator:
reasoning_content += thinking_content
return reasoning_content
+ def _handle_redacted_thinking_content(
+ self,
+ content_block_start: ContentBlockStart,
+ provider_specific_fields: Dict[str, Any],
+ ) -> Tuple[List[ChatCompletionRedactedThinkingBlock], Dict[str, Any]]:
+ """
+ Handle the redacted thinking content
+ """
+ thinking_blocks = [
+ ChatCompletionRedactedThinkingBlock(
+ type="redacted_thinking",
+ data=content_block_start["content_block"]["data"], # type: ignore
+ )
+ ]
+ provider_specific_fields["thinking_blocks"] = thinking_blocks
+
+ return thinking_blocks, provider_specific_fields
+
def chunk_parser(self, chunk: dict) -> ModelResponseStream:
try:
type_chunk = chunk.get("type", "") or ""
@@ -621,12 +639,13 @@ class ModelResponseIterator:
elif (
content_block_start["content_block"]["type"] == "redacted_thinking"
):
- thinking_blocks = [
- ChatCompletionRedactedThinkingBlock(
- type="redacted_thinking",
- data=content_block_start["content_block"]["data"],
- )
- ]
+ (
+ thinking_blocks,
+ provider_specific_fields,
+ ) = self._handle_redacted_thinking_content( # type: ignore
+ content_block_start=content_block_start,
+ provider_specific_fields=provider_specific_fields,
+ )
elif type_chunk == "content_block_stop":
ContentBlockStop(**chunk) # type: ignore
# check if tool call content block
diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
index b52e3798a89..1ab851b9b4b 100644
--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
@@ -411,6 +411,10 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
else:
raise ValueError(f"Invalid reasoning effort: {reasoning_effort}")
+ @staticmethod
+ def _is_thinking_budget_zero(thinking_budget: Optional[int]) -> bool:
+ return thinking_budget is not None and thinking_budget == 0
+
@staticmethod
def _map_thinking_param(
thinking_param: AnthropicThinkingParam,
@@ -419,7 +423,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
thinking_budget = thinking_param.get("budget_tokens")
params: GeminiThinkingConfig = {}
- if thinking_enabled:
+ if thinking_enabled and not VertexGeminiConfig._is_thinking_budget_zero(
+ thinking_budget
+ ):
params["includeThoughts"] = True
if thinking_budget is not None and isinstance(thinking_budget, int):
params["thinkingBudget"] = thinking_budget
@@ -491,7 +497,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
if _tool_choice_value is not None:
optional_params["tool_choice"] = _tool_choice_value
elif param == "parallel_tool_calls":
- if value is False:
+ if value is False and not (
+ drop_params or litellm.drop_params
+ ): # if drop params is True, then we should just ignore this
tools = non_default_params.get(
"tools", non_default_params.get("functions")
)
@@ -503,10 +511,12 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
message=(
"`parallel_tool_calls=False` is not supported when multiple tools are "
"provided for Gemini. Specify a single tool, or set "
- "`parallel_tool_calls=True`."
+ "`parallel_tool_calls=True`. If you want to drop this param, set `litellm.drop_params = True` or pass in `(.., drop_params=True)` in the requst - https://docs.litellm.ai/docs/completion/drop_params"
),
status_code=400,
)
+ else:
+ optional_params["parallel_tool_calls"] = value
elif param == "seed":
optional_params["seed"] = value
elif param == "reasoning_effort" and isinstance(value, str):
diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py
index 9d67b4e8f9a..bcfdcb69ca5 100644
--- a/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py
+++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py
@@ -44,29 +44,69 @@ def create_vertex_url(
api_base: Optional[str] = None,
) -> str:
"""Return the base url for the vertex partner models"""
+
+ api_base = api_base or f"https://{vertex_location}-aiplatform.googleapis.com"
if partner == VertexPartnerProvider.llama:
- return f"https://{vertex_location}-aiplatform.googleapis.com/v1beta1/projects/{vertex_project}/locations/{vertex_location}/endpoints/openapi/chat/completions"
+ return f"{api_base}/v1beta1/projects/{vertex_project}/locations/{vertex_location}/endpoints/openapi/chat/completions"
elif partner == VertexPartnerProvider.mistralai:
if stream:
- return f"https://{vertex_location}-aiplatform.googleapis.com/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/mistralai/models/{model}:streamRawPredict"
+ return f"{api_base}/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/mistralai/models/{model}:streamRawPredict"
else:
- return f"https://{vertex_location}-aiplatform.googleapis.com/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/mistralai/models/{model}:rawPredict"
+ return f"{api_base}/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/mistralai/models/{model}:rawPredict"
elif partner == VertexPartnerProvider.ai21:
if stream:
- return f"https://{vertex_location}-aiplatform.googleapis.com/v1beta1/projects/{vertex_project}/locations/{vertex_location}/publishers/ai21/models/{model}:streamRawPredict"
+ return f"{api_base}/v1beta1/projects/{vertex_project}/locations/{vertex_location}/publishers/ai21/models/{model}:streamRawPredict"
else:
- return f"https://{vertex_location}-aiplatform.googleapis.com/v1beta1/projects/{vertex_project}/locations/{vertex_location}/publishers/ai21/models/{model}:rawPredict"
+ return f"{api_base}/v1beta1/projects/{vertex_project}/locations/{vertex_location}/publishers/ai21/models/{model}:rawPredict"
elif partner == VertexPartnerProvider.claude:
if stream:
- return f"https://{vertex_location}-aiplatform.googleapis.com/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/anthropic/models/{model}:streamRawPredict"
+ return f"{api_base}/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/anthropic/models/{model}:streamRawPredict"
else:
- return f"https://{vertex_location}-aiplatform.googleapis.com/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/anthropic/models/{model}:rawPredict"
+ return f"{api_base}/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/anthropic/models/{model}:rawPredict"
class VertexAIPartnerModels(VertexBase):
def __init__(self) -> None:
pass
+ def get_complete_url(
+ self,
+ custom_api_base: Optional[str],
+ vertex_location: Optional[str],
+ vertex_project: Optional[str],
+ project_id: str,
+ partner: VertexPartnerProvider,
+ stream: Optional[bool],
+ model: str,
+ ) -> str:
+ api_base = self.get_api_base(
+ api_base=custom_api_base, vertex_location=vertex_location
+ )
+ default_api_base = create_vertex_url(
+ vertex_location=vertex_location or "us-central1",
+ vertex_project=vertex_project or project_id,
+ partner=partner, # type: ignore
+ stream=stream,
+ model=model,
+ api_base=api_base,
+ )
+
+ if len(default_api_base.split(":")) > 1:
+ endpoint = default_api_base.split(":")[-1]
+ else:
+ endpoint = ""
+
+ _, api_base = self._check_custom_proxy(
+ api_base=custom_api_base,
+ custom_llm_provider="vertex_ai",
+ gemini_api_key=None,
+ endpoint=endpoint,
+ stream=stream,
+ auth_header=None,
+ url=default_api_base,
+ )
+ return api_base
+
def completion(
self,
model: str,
@@ -138,28 +178,17 @@ class VertexAIPartnerModels(VertexBase):
partner = VertexPartnerProvider.ai21
elif "claude" in model:
partner = VertexPartnerProvider.claude
-
- default_api_base = create_vertex_url(
- vertex_location=vertex_location or "us-central1",
- vertex_project=vertex_project or project_id,
- partner=partner, # type: ignore
- stream=stream,
- model=model,
- )
-
- if len(default_api_base.split(":")) > 1:
- endpoint = default_api_base.split(":")[-1]
else:
- endpoint = ""
+ raise ValueError(f"Unknown partner model: {model}")
- _, api_base = self._check_custom_proxy(
- api_base=api_base,
- custom_llm_provider="vertex_ai",
- gemini_api_key=None,
- endpoint=endpoint,
+ api_base = self.get_complete_url(
+ custom_api_base=api_base,
+ vertex_location=vertex_location,
+ vertex_project=vertex_project,
+ project_id=project_id,
+ partner=partner,
stream=stream,
- auth_header=None,
- url=default_api_base,
+ model=model,
)
if "codestral" in model or "mistral" in model:
diff --git a/litellm/llms/vertex_ai/vertex_llm_base.py b/litellm/llms/vertex_ai/vertex_llm_base.py
index 9349fb56da9..4d0dd8a75b8 100644
--- a/litellm/llms/vertex_ai/vertex_llm_base.py
+++ b/litellm/llms/vertex_ai/vertex_llm_base.py
@@ -135,6 +135,16 @@ class VertexBase:
return google_auth.default(scopes=scopes)
+ def get_api_base(
+ self, api_base: Optional[str], vertex_location: Optional[str]
+ ) -> str:
+ if api_base:
+ return api_base
+ elif vertex_location and vertex_location == "global":
+ return "https://aiplatform.googleapis.com"
+ else:
+ return f"https://{vertex_location}-aiplatform.googleapis.com"
+
def refresh_auth(self, credentials: Any) -> None:
from google.auth.transport.requests import (
Request, # type: ignore[import-untyped]
diff --git a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_handler.py b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_handler.py
index 25ec01167e4..a569a272039 100644
--- a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_handler.py
+++ b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_handler.py
@@ -36,3 +36,6 @@ def test_redacted_thinking_content_block_delta():
model_response.choices[0].delta.thinking_blocks[0]["type"]
== "redacted_thinking"
)
+
+ assert model_response.choices[0].delta.provider_specific_fields is not None
+ assert "thinking_blocks" in model_response.choices[0].delta.provider_specific_fields
diff --git a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
index 24705bb6ea5..18ffd7ca60a 100644
--- a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
+++ b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
@@ -377,6 +377,22 @@ def test_vertex_ai_usage_metadata_response_token_count():
assert result.completion_tokens_details.text_tokens == 74
+def test_vertex_ai_map_thinking_param_with_budget_tokens_0():
+ """
+ If budget_tokens is 0, do not set includeThoughts to True
+ """
+ from litellm.types.llms.anthropic import AnthropicThinkingParam
+
+ v = VertexGeminiConfig()
+ thinking_param: AnthropicThinkingParam = {"type": "enabled", "budget_tokens": 0}
+ assert "includeThoughts" not in v._map_thinking_param(thinking_param=thinking_param)
+
+ thinking_param: AnthropicThinkingParam = {"type": "enabled", "budget_tokens": 100}
+ assert v._map_thinking_param(thinking_param=thinking_param) == {
+ "includeThoughts": True,
+ "thinkingBudget": 100,
+ }
+
def test_vertex_ai_map_tools():
v = VertexGeminiConfig()
tools = v._map_function(value=[{"code_execution": {}}])
@@ -430,3 +446,4 @@ def test_vertex_ai_map_tool_with_anyof():
] == {
"anyOf": [{"type": "string", "nullable": True, "title": "Base Branch"}]
}, f"Expected only anyOf field and its contents to be kept, but got {tools[0]['function_declarations'][0]['parameters']['properties']['base_branch']}"
+
diff --git a/tests/test_litellm/llms/vertex_ai/test_vertex_llm_base.py b/tests/test_litellm/llms/vertex_ai/test_vertex_llm_base.py
index 9704bd4294b..c463404a971 100644
--- a/tests/test_litellm/llms/vertex_ai/test_vertex_llm_base.py
+++ b/tests/test_litellm/llms/vertex_ai/test_vertex_llm_base.py
@@ -242,3 +242,37 @@ class TestVertexBase:
assert token == "refreshed-token"
assert project == not_quota_project_id
+
+ @pytest.mark.parametrize(
+ "api_base, vertex_location, expected",
+ [
+ (None, "us-central1", "https://us-central1-aiplatform.googleapis.com"),
+ (None, "global", "https://aiplatform.googleapis.com"),
+ (
+ "https://us-central1-aiplatform.googleapis.com",
+ "us-central1",
+ "https://us-central1-aiplatform.googleapis.com",
+ ),
+ (
+ "https://aiplatform.googleapis.com",
+ "global",
+ "https://aiplatform.googleapis.com",
+ ),
+ (
+ "https://us-central1-aiplatform.googleapis.com",
+ "global",
+ "https://us-central1-aiplatform.googleapis.com",
+ ),
+ (
+ "https://aiplatform.googleapis.com",
+ "us-central1",
+ "https://aiplatform.googleapis.com",
+ ),
+ ],
+ )
+ def test_get_api_base(self, api_base, vertex_location, expected):
+ vertex_base = VertexBase()
+ assert (
+ vertex_base.get_api_base(api_base=api_base, vertex_location=vertex_location)
+ == expected
+ ), f"Expected {expected} with api_base {api_base} and vertex_location {vertex_location}"