Deepseek Model return 422
this is my code:
import os
from google.adk.agents import Agent
from google.adk.models.lite_llm import LiteLlm
def get_weather(city: str) -> str:
"""Retrieves the current weather report for a specified city.
Args:
city (str): The name of the city for which to retrieve the weather report.
Returns:
str: result or error msg.
"""
if city.lower() == "new york":
return "The weather in New York is sunny with a temperature of 25 degrees"
else:
return f"Weather information for '{city}' is not available."
root_agent = Agent(
name="weather_agent",
model=LiteLlm(model="deepseek/deepseek-chat"), # Specifies the underlying LLM
description="Provides weather information for specific cities.", # Crucial for delegation later
instruction="You are a helpful agent who can answer user questions about the time and weather in a city.",
tools=[get_weather] # Make the tool available to this agent
)
fail msg is
2025-04-16 17:37:19,292 - INFO - _client.py:1740 - HTTP Request: POST https://api.deepseek.com/beta/chat/completions "HTTP/1.1 422 Unprocessable Entity"
2025-04-16 17:37:19,315 - ERROR - fast_api.py:616 - Error in event_generator: litellm.BadRequestError: DeepseekException - Failed to deserialize the JSON body into the target type: messages[2]: invalid type: sequence, expected a string at line 1 column 587
this is LLM request:
LLM Request:
-----------------------------------------------------------
System Instruction:
You are a helpful agent who can answer user questions about the time and weather in a city.
You are an agent. Your internal name is "weather_agent".
The description about you is "Provides weather information for specific cities."
-----------------------------------------------------------
Contents:
{"parts":[{"text":"What is the weather in New York?"}],"role":"user"}
{"parts":[{"function_call":{"id":"call_0_c657e3f7-3809-4508-9f98-e03c4a5a14c8","args":{"city":"New York"},"name":"get_weather"}}],"role":"model"}
{"parts":[{"function_response":{"id":"call_0_c657e3f7-3809-4508-9f98-e03c4a5a14c8","name":"get_weather","response":{"result":"The weather in New York is sunny with a temperature of 25 degrees"}}}],"role":"user"}
-----------------------------------------------------------
Functions:
get_weather: {'city': {'type': <Type.STRING: 'STRING'>}} -> None
-----------------------------------------------------------
Issue Code
# litellm._turn_on_debug()
weather_agent_deepseek = Agent(
name="weather_agent_deepseek",
# Key change: Wrap the LiteLLM model identifier
model=LiteLlm(model=MODEL_Deepseek_Chat,
model_config={
"stream": False, # Disable streaming output
"api_key": os.environ['DEEPSEEK_API_KEY']
}),
description="Provides weather information (using deepseek-chat).",
instruction="You are a helpful weather assistant powered by deepseek-chat. "
"Use the 'get_weather' tool for city weather requests. "
"Clearly present successful reports or polite error messages based on the tool's output status.",
tools=[get_weather], # Re-use the same tool
)
print(f"Agent '{weather_agent_deepseek.name}' created using model '{MODEL_Deepseek_Chat}'.")
Issue Description
I encountered the same issue. When integrating Deepseek Chat model with Google ADK framework using LiteLLM adapter, we encountered a serialization error:
httpx.HTTPStatusError: Client error '422 Unprocessable Entity' for url 'https://api.deepseek.com/beta/chat/completions'
For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422
File "E:\Code\PythonDir\MCP\Client\R_Client\.venv\Lib\site-packages\litellm\litellm_core_utils\exception_mapping_utils.py", line 419, in exception_type
raise BadRequestError(
litellm.exceptions.BadRequestError: litellm.BadRequestError: DeepseekException - Failed to deserialize the JSON body into the target type: messages[2]: invalid type: sequence, expected a string at line 1 column 710
Issue Traceback
Based on the error message and call chain, the problem is that Deepseek API expects messages in string format, but received a sequence type. We need to identify the root cause and fix it.
- The error occurs in
litellm.exceptions.BadRequestErrorwith the specific message "Failed to deserialize the JSON body into the target type: messages[2]: invalid type: sequence, expected a string" - This indicates that in the messages sent to Deepseek API, the third message (index 2) is not in string format but is a sequence type
The root cause appears to be in how the LiteLLM model adapter handles function responses. We need to modify the lite_llm.py file to ensure messages are properly serialized to the format expected by the Deepseek API.
Testing the following fix:
# In the generate_content_async method, find where completion_args is processed
# Add a function to ensure correct message format
async def generate_content_async(
self, llm_request: LlmRequest, stream: bool = False
) -> AsyncGenerator[LlmResponse, None]:
"""Generates content from the given request."""
# ... existing code ...
# Add a function to handle Deepseek message format issues
def ensure_deepseek_message_format(messages):
"""Ensure message format complies with Deepseek API requirements"""
if self.model.startswith("deepseek"):
for msg in messages:
# If message content is a complex object (like function response), convert it to string
if isinstance(msg.get("content"), (list, dict)):
msg["content"] = json.dumps(msg["content"])
return messages
# ... existing code ...
print("Debug-completion_args-", completion_args)
completion_args = {
"model": self.model,
"messages": ensure_deepseek_message_format(messages), # Use the new function to process messages
"stream": stream,
# ... other parameters ...
}
Output result:
Debug-completion_args- {'model': 'deepseek/deepseek-chat', 'messages': [{'role': 'developer', 'content': 'You are a helpful weather assistant powered by deepseek-chat. Use the \'get_weather\' tool for city weather requests. Clearly present successful reports or polite error messages based on the tool\'s output status.\n\nYou are an agent. Your internal name is "weather_agent_deepseek".\n\n The description about you is "Provides weather information (using deepseek-chat)."'}, {'role': 'user', 'content': "What's the weather in Tokyo?"}], 'tools': [{'type': 'function', 'function': {'name': 'get_weather', 'description': 'Retrieves the current weather report for a specified city.\n\n Args:\n city (str): The name of the city (e.g., "New York", "London", "Tokyo").\n\n Returns:\n dict: A dictionary containing the weather information.\n Includes a \'status\' key (\'success\' or \'error\').\n If \'success\', includes a \'report\' key with weather details.\n If \'error\', includes an \'error_message\' key.\n ', 'parameters': {'type': 'object', 'properties': {'city': {'type': 'string'}}}}}]}
Agent Response: The current weather in Tokyo is light rain with a temperature of 18°C.
This temporarily resolves the issue, but may not be the optimal solution. Further optimization is needed. Please stay tuned for updates.
Better Solution
https://github.com/google/adk-python/issues/226
pip uninstall -y google-adk
pip install --no-cache-dir git+https://github.com/google/adk-python@main
This solution has been tested and works perfectly!
Thanks a lot @radial-hks for the recommendation. Closing the issue as fixed following your commetn