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]

feat(advisor): auto-strip advisor_tool_result blocks when advisor tool absent

Ishaan Jaffer3a89465d18aa
diff --git a/litellm/llms/anthropic/common_utils.py b/litellm/llms/anthropic/common_utils.py
index 7d2d0a74961..1205d1afbcf 100644
--- a/litellm/llms/anthropic/common_utils.py
+++ b/litellm/llms/anthropic/common_utils.py
@@ -2,7 +2,7 @@
This file contains common utils for anthropic calls.
"""
-from typing import Dict, List, Optional, Union
+from typing import Any, Dict, List, Optional, Union
import httpx
@@ -464,9 +464,9 @@ class AnthropicModelInfo(BaseLLMModelInfo):
if web_search_tool_used:
from litellm.types.llms.anthropic import ANTHROPIC_BETA_HEADER_VALUES
- headers[
- "anthropic-beta"
- ] = ANTHROPIC_BETA_HEADER_VALUES.WEB_SEARCH_2025_03_05.value
+ headers["anthropic-beta"] = (
+ ANTHROPIC_BETA_HEADER_VALUES.WEB_SEARCH_2025_03_05.value
+ )
elif len(betas) > 0:
headers["anthropic-beta"] = ",".join(betas)
@@ -639,6 +639,54 @@ class AnthropicModelInfo(BaseLLMModelInfo):
return AnthropicTokenCounter()
+def strip_advisor_blocks_from_messages(messages: List[Any]) -> List[Any]:
+ """
+ Remove server_tool_use (name='advisor') and advisor_tool_result blocks from
+ assistant message content when the advisor tool is absent from the request.
+
+ Prevents Anthropic 400 invalid_request_error: if advisor_tool_result blocks
+ exist in history but the advisor tool is not in the tools array, the API rejects
+ the request. This happens when the user has removed the advisor tool for cost
+ control or on a follow-up turn.
+ """
+ for message in messages:
+ if message.get("role") != "assistant":
+ continue
+ content = message.get("content")
+ if not isinstance(content, list):
+ continue
+ advisor_ids: set = set()
+ for block in content:
+ if (
+ isinstance(block, dict)
+ and block.get("type") == "server_tool_use"
+ and block.get("name") == "advisor"
+ ):
+ bid = block.get("id")
+ if bid:
+ advisor_ids.add(bid)
+ if not advisor_ids:
+ continue
+ message["content"] = [
+ block
+ for block in content
+ if not (
+ isinstance(block, dict)
+ and (
+ (
+ block.get("type") == "server_tool_use"
+ and block.get("name") == "advisor"
+ )
+ or (
+ block.get("type") == "advisor_tool_result"
+ and block.get("tool_use_id") in advisor_ids
+ )
+ )
+ )
+ ]
+ return messages
+
+
def process_anthropic_headers(headers: Union[httpx.Headers, dict]) -> dict:
openai_headers = {}
if "anthropic-ratelimit-requests-limit" in headers: