ADK/LiteLLM: BadRequestError with Claude 3.7 on Vertex When Using Tools and thinking Feature Enabled
When using the Google Agent Development Kit (ADK) with litellm to interact with Anthropic's Claude 3.7 Sonnet model hosted on Google Cloud Vertex AI (vertex_ai/claude-3-7-sonnet@...), a litellm.BadRequestError occurs if the thinking feature is enabled in the LiteLlm configuration and the agent successfully uses a tool.
The error happens during the step where the ADK Runner sends the tool execution results back to the model to get the final natural language response. The error message from Vertex AI indicates an expectation mismatch: it expected the assistant's response turn (after the tool result) to begin with a thinking block, but it received something else (likely the start of a standard text block implicitly requested by ADK/LiteLLM).
Disabling the thinking feature (by removing the thinking={...} parameter from LiteLlm) avoids the error, but prevents users from leveraging the explicit reasoning output provided by this Claude feature.
Steps to Reproduce
Environment Setup:
Install necessary packages: google-adk, litellm, google-cloud-aiplatform.
Set environment variables: GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION.
Code: weather_agent_claude = None # Initialize to None runner_claude = None # Initialize runner to None
try: weather_agent_claude = Agent( name="weather_agent_claude", # Key change: Wrap the LiteLLM model identifier model=LiteLlm(model=MODEL_CLAUDE_3_7,vertex_ai_project=os.environ.get("GOOGLE_CLOUD_PROJECT"), vertex_ai_location=os.environ.get("GOOGLE_CLOUD_LOCATION"), thinking={"type": "enabled", "budget_tokens": 1024},), #https://docs.litellm.ai/docs/providers/vertex description="Provides weather information (using Claude Sonnet).", instruction="You are a helpful weather assistant powered by Claude Sonnet. " "Use the 'get_weather' tool for city weather requests. " "Analyze the tool's dictionary output ('status', 'report'/'error_message'). " "Clearly present successful reports or polite error messages.", tools=[get_weather], # Re-use the same tool ) print(f"Agent '{weather_agent_claude.name}' created using model '{MODEL_CLAUDE_3_7}'.")
# InMemorySessionService is simple, non-persistent storage for this tutorial.
session_service_claude = InMemorySessionService() # Create a dedicated service
# Define constants for identifying the interaction context
APP_NAME_CLAUDE = "weather_tutorial_app_claude" # Unique app name
USER_ID_CLAUDE = "user_1_claude"
SESSION_ID_CLAUDE = "session_001_claude" # Using a fixed ID for simplicity
# Create the specific session where the conversation will happen
session_claude = session_service_claude.create_session(
app_name=APP_NAME_CLAUDE,
user_id=USER_ID_CLAUDE,
session_id=SESSION_ID_CLAUDE
)
print(f"Session created: App='{APP_NAME_CLAUDE}', User='{USER_ID_CLAUDE}', Session='{SESSION_ID_CLAUDE}'")
# Create a runner specific to this agent and its session service
runner_claude = Runner(
agent=weather_agent_claude,
app_name=APP_NAME_CLAUDE, # Use the specific app name
session_service=session_service_claude # Use the specific session service
)
print(f"Runner created for agent '{runner_claude.agent.name}'.")
# --- Test the Claude Agent ---
print("\n--- Testing Claude Agent ---")
# Ensure call_agent_async uses the correct runner, user_id, session_id
asyncio.run(call_agent_async("What's the weather in Hamburg?",runner_claude,USER_ID_CLAUDE, SESSION_ID_CLAUDE))
except Exception as e: print(f"❌ Could not create or run Claude agent '{MODEL_CLAUDE_3_7}'. Check API Key and model name. Error: {e}")
->
❌ Could not create or run Claude agent 'vertex_ai/claude-3-7-sonnet@20250219'. Check API Key and model name. Error: litellm.BadRequestError: VertexAIException BadRequestError - {"type":"error","error":{"type":"invalid_request_error","message":"messages.1.content.0.type: Expected thinking or redacted_thinking, but found text. When thinking is enabled, a final assistant message must start with a thinking block (preceeding the lastmost set of tool_use and tool_result blocks). We recommend you include thinking blocks from previous turns. To avoid this requirement, disable thinking. Please consult our documentation at https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking"}}
Actual Behavior
When the code above is run (with valid GCP Project/Location and ADC configured):
The agent receives the query ("What's the weather in Hamburg?").
The agent correctly identifies the need for the get_weather tool and generates a function call.
The ADK Runner executes the get_weather function successfully.
The Runner attempts to send the conversation history (including the user query, the model's function call, and the function's result) back to the Claude 3.7 model via LiteLLM to generate the final summary.
Expected Behavior
The agent execution should complete successfully without a BadRequestError. After the get_weather tool returns its result:
The ADK Runner should send the history and tool result to the Claude 3.7 model via LiteLLM.
The model should process the tool result and generate a final natural language response summarizing the weather (e.g., "Okay, I found the weather for Hamburg. It's currently partly cloudy with a temperature of 15°C.").
Critically, because thinking was enabled, the underlying response object from LiteLLM/Vertex should contain the thinking block metadata alongside the text content (though accessing this metadata might require separate ADK/LiteLLM features).
@genquan9 Could you help take a look?
It looks like the claude models were not loaded properly. what is the value of MODEL_CLAUDE_3_7?
please make sure to add some codes as:
from google.adk.models.registry import LLMRegistry # Import needed for registration
from google.adk.models.anthropic_llm import Claude # Import needed for registration
LLMRegistry.register(Claude)
root_agent = LlmAgent(
...
model="claude-3-5-sonnet-v2@20241022",
...
)
Then, the model should be loaded by ADK.
A more detailed example can be found in https://google.github.io/adk-docs/agents/models/#third-party-models-on-vertex-ai-eg-anthropic-claude.
@genquan9: here an example. Thinking without tool seams to work. Thinking with tool doen't work
root_agent = Agent(
name="agent_c37",
model=LiteLlm(
model="vertex_ai/claude-3-7-sonnet@20250219",
vertex_ai_project=settings.GOOGLE_CLOUD_PROJECT,
vertex_ai_location=settings.GOOGLE_CLOUD_LOCATION,
#tool_choice="auto",
reasoning_effort="low"
# Alternatively
#thinking={"type": "enabled", "budget_tokens": 1024}, (lite_llm style, doesn't work)
# The combination with planner does not seem to be possible with LiteLLM either,
# planner=BuiltInPlanner(
# thinking_config=genai_types.ThinkingConfig(
# include_thoughts=True,
# `budget_tokens` is not directly part of genai_types.ThinkingConfig.
# Token control for thinking would be model-specific
# and would need to be supported by the Claude class in the ADK, which is unlikely.
# )
# ),
),
description="Agent that answers user queries accurately, reliably, and responsibly",
# Use the google_search tool for web search.
instruction=generic_instruction,
# The combination of Thinking and Tools is not possible, as the ADK does not support the expected sequence (first Thinking, then Tool).
#tools=[search_google_custom],
)
--> Works (but no stream only one chunk? samle Problem without LiteLLM.)
root_agent = Agent(
name="agent_c37",
model=LiteLlm(
model="vertex_ai/claude-3-7-sonnet@20250219",
vertex_ai_project=settings.GOOGLE_CLOUD_PROJECT,
vertex_ai_location=settings.GOOGLE_CLOUD_LOCATION,
reasoning_effort="low"
),
description="Agent der präzise, zuverlässige und verantwortungsvoll die Anfragen von Benutzern beantwortet",
# Nutze das Tool google_search für die Websuche.
instruction=generic_instruction,
tools=[search_google_custom],
)
-> doesn't work:
{"type":"invalid_request_error","message":"messages.1.content.0.type: Expected thinking or redacted_thinking, but found tool_use. When thinking is enabled, a final assistant message must start with a thinking block (preceeding the lastmost set of tool_use and tool_result blocks). We recommend you include thinking blocks from previous turns. To avoid this requirement, disable thinking. Please consult our documentation at https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking"}}'"
}
I can reproduce the issue. The root cause is in litellm. LiteLLM doesn't preserve thinking blocks when reconstructing conversation history for anthropic models. It would be better to fix in litellm side.
Hi @schulz-and-friends and thanks to everyone who participated in this thread.
We're currently doing some housekeeping on our issue tracker. Given the rapid pace of development and the number of updates since this was last active, there's a good chance this issue has been resolved in a newer version. To help us keep our backlog focused on current issues, we are closing this as stale.
If you're still facing this problem, could you please update to the very latest version of the library and confirm the issue still exists? If it does, please comment here, and we will be happy to reopen this issue and investigate further.
Thanks for your contribution and understanding!