using Ollama with ADK
{"error": "litellm.APIConnectionError: Ollama_chatException - {"error":"json: cannot unmarshal array into Go struct field ChatRequest.messages.content of type string"}"}
For Sequential Agent, the first agent creates a json string and stores in output_key and then in second agent picks up the value and confirms to the user.
But when I try to do that I get the above error.
@msbarathraj could you share a minimal agent to repro? better to share which model are you using with ollama.
In the meanwhile, jic, have you checked this sample: https://github.com/google/adk-python/tree/main/contributing/samples/hello_world_ollama
Hi, I am still seeing this issue in ADK 1.3.0.
# @title Define Tools for Greeting and Farewell Agents
from typing import Optional # Make sure to import Optional
# @title Import necessary libraries
import os
import asyncio
from google.adk.agents import Agent
from google.adk.models.lite_llm import LiteLlm # For multi-model support
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.genai import types # For creating message Content/Parts
# Ollama models
QWEN2_5_3b = "qwen2.5:3b"
QWEN2_5_7b = "qwen2.5:7b"
QWEN3_4b = "qwen3:4b"
QWEN3_8b = "qwen3:8b"
LLAMA3_1_8b = "llama3.1:8b"
LLAMA3_2_1b = "llama3.2:1b"
LLAMA3_2_3b = "llama3.2:3b"
MISTRAL_7b = "mistral:7b"
PHI4_MINI_3_8b = "phi4-mini:3.8b"
DEFAULT_MODEL = LLAMA3_1_8b
# @title Define the get_weather Tool
def get_weather(city: str) -> dict:
"""Retrieves the current weather report for a specified city.
Args:
city (str): The name of the city (e.g., "New York", "London", "Tokyo").
Returns:
dict: A dictionary containing the weather information.
Includes a 'status' key ('success' or 'error').
If 'success', includes a 'report' key with weather details.
If 'error', includes an 'error_message' key.
"""
print(f"--- Tool: get_weather called for city: {city} ---") # Log tool execution
city_normalized = city.lower().replace(" ", "") # Basic normalization
# Mock weather data
mock_weather_db = {
"newyork": {"status": "success", "report": "The weather in New York is sunny with a temperature of 25°C."},
"london": {"status": "success", "report": "It's cloudy in London with a temperature of 15°C."},
"tokyo": {"status": "success", "report": "Tokyo is experiencing light rain and a temperature of 18°C."},
}
if city_normalized in mock_weather_db:
return mock_weather_db[city_normalized]
else:
return {"status": "error", "error_message": f"Sorry, I don't have weather information for '{city}'."}
def say_hello(name: Optional[str] = None) -> str:
"""Provides a simple greeting. If a name is provided, it will be used.
Args:
name (str, optional): The name of the person to greet. Defaults to a generic greeting if not provided.
Returns:
str: A friendly greeting message.
"""
if name:
greeting = f"Hello, {name}!"
print(f"--- Tool: say_hello called with name: {name} ---")
else:
greeting = "Hello there!" # Default greeting if name is None or not explicitly passed
print(f"--- Tool: say_hello called without a specific name (name_arg_value: {name}) ---")
return greeting
def say_goodbye() -> str:
"""Provides a simple farewell message to conclude the conversation."""
print(f"--- Tool: say_goodbye called ---")
return "Goodbye! Have a great day."
print("Greeting and Farewell tools defined.")
# --- Greeting Agent ---
greeting_agent = None
try:
greeting_agent = Agent(
model=LiteLlm(model=f"ollama_chat/{DEFAULT_MODEL}"),
# model=LiteLlm(
# api_base='http://localhost:11434/v1',
# model="openai/mistral:7b"
# ),
# model=LiteLlm(model=MODEL_GPT_4O), # If you would like to experiment with other models
name="greeting_agent",
instruction="You are the Greeting Agent. Your ONLY task is to provide a friendly greeting to the user. "
"Use the 'say_hello' tool to generate the greeting. "
"If the user provides their name, make sure to pass it to the tool. "
"Do not engage in any other conversation or tasks.",
description="Handles simple greetings and hellos using the 'say_hello' tool.", # Crucial for delegation
tools=[say_hello],
)
print(f"✅ Agent '{greeting_agent.name}' created using model '{greeting_agent.model}'.")
except Exception as e:
print(f"❌ Could not create Greeting agent. Check API Key ({greeting_agent.model}). Error: {e}")
# --- Farewell Agent ---
farewell_agent = None
try:
farewell_agent = Agent(
model=LiteLlm(model=f"ollama_chat/{DEFAULT_MODEL}"),
# model=LiteLlm(
# api_base='http://localhost:11434/v1',
# model="openai/mistral:7b"
# ),
name="farewell_agent",
instruction="You are the Farewell Agent. Your ONLY task is to provide a polite goodbye message. "
"Use the 'say_goodbye' tool when the user indicates they are leaving or ending the conversation "
"(e.g., using words like 'bye', 'goodbye', 'thanks bye', 'see you'). "
"Do not perform any other actions.",
description="Handles simple farewells and goodbyes using the 'say_goodbye' tool.", # Crucial for delegation
tools=[say_goodbye],
)
print(f"✅ Agent '{farewell_agent.name}' created using model '{farewell_agent.model}'.")
except Exception as e:
print(f"❌ Could not create Farewell agent. Check API Key ({farewell_agent.model}). Error: {e}")
# --- Root Agent ---
root_agent = None
runner_root = None # Initialize runner
if greeting_agent and farewell_agent and 'get_weather' in globals():
# Let's use a capable Gemini model for the root agent to handle orchestration
root_agent_model = "qwen3:8b"
weather_agent_team = Agent(
name="weather_agent_v2", # Give it a new version name
model=LiteLlm(model=f"ollama_chat/{DEFAULT_MODEL}"),
# model=LiteLlm(
# api_base='http://localhost:11434/v1',
# model="openai/mistral:7b"
# ),
# model=LiteLlm(model=f"ollama_chat/{root_agent_model}"),
description="The main coordinator agent. Handles weather requests and delegates greetings/farewells to specialists.",
instruction="You are the main Weather Agent coordinating a team. Your primary responsibility is to provide weather information. "
"Use the 'get_weather' tool ONLY for specific weather requests (e.g., 'weather in London'). "
"You have specialized sub-agents: "
"1. 'greeting_agent': Handles simple greetings like 'Hi', 'Hello'. Delegate to it for these. "
"2. 'farewell_agent': Handles simple farewells like 'Bye', 'See you'. Delegate to it for these. "
"Analyze the user's query. If it's a greeting, delegate to 'greeting_agent'. If it's a farewell, delegate to 'farewell_agent'. "
"If it's a weather request, handle it yourself using 'get_weather'. "
"For anything else, respond appropriately or state you cannot handle it.",
tools=[get_weather], # Root agent still needs the weather tool for its core task
# Key change: Link the sub-agents here!
sub_agents=[greeting_agent, farewell_agent]
)
print(f"✅ Root Agent '{weather_agent_team.name}' created using model '{root_agent_model}' with sub-agents: {[sa.name for sa in weather_agent_team.sub_agents]}")
else:
print("❌ Cannot create root agent because one or more sub-agents failed to initialize or 'get_weather' tool is missing.")
if not greeting_agent: print(" - Greeting Agent is missing.")
if not farewell_agent: print(" - Farewell Agent is missing.")
if 'get_weather' not in globals(): print(" - get_weather function is missing.")
# @title Define Agent Interaction Function
from google.genai import types # For creating message Content/Parts
async def call_agent_async(query: str, runner, user_id, session_id):
"""Sends a query to the agent and prints the final response."""
print(f"\n>>> User Query: {query}")
# Prepare the user's message in ADK format
content = types.Content(role='user', parts=[types.Part(text=query)])
final_response_text = "Agent did not produce a final response." # Default
# Key Concept: run_async executes the agent logic and yields Events.
# We iterate through events to find the final answer.
async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=content):
# You can uncomment the line below to see *all* events during execution
# print(f" [Event] Author: {event.author}, Type: {type(event).__name__}, Final: {event.is_final_response()}, Content: {event.content}")
# Key Concept: is_final_response() marks the concluding message for the turn.
if event.is_final_response():
if event.content and event.content.parts:
# Assuming text response in the first part
final_response_text = event.content.parts[0].text
elif event.actions and event.actions.escalate: # Handle potential errors/escalations
final_response_text = f"Agent escalated: {event.error_message or 'No specific message.'}"
# Add more checks here if needed (e.g., specific error codes)
break # Stop processing events once the final response is found
print(f"<<< Agent Response: {final_response_text}")
# @title Interact with the Agent Team
import asyncio # Ensure asyncio is imported
import litellm
# litellm._turn_on_debug()
# Ensure the root agent (e.g., 'weather_agent_team' or 'root_agent' from the previous cell) is defined.
# Ensure the call_agent_async function is defined.
# Check if the root agent variable exists before defining the conversation function
root_agent_var_name = 'root_agent' # Default name from Step 3 guide
if 'weather_agent_team' in globals(): # Check if user used this name instead
root_agent_var_name = 'weather_agent_team'
elif 'root_agent' not in globals():
print("⚠️ Root agent ('root_agent' or 'weather_agent_team') not found. Cannot define run_team_conversation.")
# Assign a dummy value to prevent NameError later if the code block runs anyway
root_agent = None # Or set a flag to prevent execution
# Only define and run if the root agent exists
if root_agent_var_name in globals() and globals()[root_agent_var_name]:
# Define the main async function for the conversation logic.
# The 'await' keywords INSIDE this function are necessary for async operations.
async def run_team_conversation():
print("\n--- Testing Agent Team Delegation ---")
session_service = InMemorySessionService()
APP_NAME = "weather_tutorial_agent_team"
USER_ID = "user_1_agent_team"
SESSION_ID = "session_001_agent_team"
session = await session_service.create_session(
app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID
)
print(f"Session created: App='{APP_NAME}', User='{USER_ID}', Session='{SESSION_ID}'")
actual_root_agent = globals()[root_agent_var_name]
runner_agent_team = Runner( # Or use InMemoryRunner
agent=actual_root_agent,
app_name=APP_NAME,
session_service=session_service
)
print(f"Runner created for agent '{actual_root_agent.name}'.")
# --- Interactions using await (correct within async def) ---
await call_agent_async(query = "Bye!",
runner=runner_agent_team,
user_id=USER_ID,
session_id=SESSION_ID)
await call_agent_async(query = "What is the weather in New York?",
runner=runner_agent_team,
user_id=USER_ID,
session_id=SESSION_ID)
await call_agent_async(query = "How is it in New Delhi right now?",
runner=runner_agent_team,
user_id=USER_ID,
session_id=SESSION_ID)
await call_agent_async(query = "Thanks, bye!",
runner=runner_agent_team,
user_id=USER_ID,
session_id=SESSION_ID)
import asyncio
if __name__ == "__main__": # Ensures this runs only when script is executed directly
print("Executing using 'asyncio.run()' (for standard Python scripts)...")
try:
# This creates an event loop, runs your async function, and closes the loop.
asyncio.run(run_team_conversation())
except Exception as e:
print(f"An error occurred: {e}")
else:
# This message prints if the root agent variable wasn't found earlier
print("\n⚠️ Skipping agent team conversation execution as the root agent was not successfully defined in a previous step.")
% time python weather_bot_agent.py
Greeting and Farewell tools defined.
✅ Agent 'greeting_agent' created using model 'model='ollama_chat/llama3.1:8b' llm_client=<google.adk.models.lite_llm.LiteLLMClient object at 0x154c6e150>'.
✅ Agent 'farewell_agent' created using model 'model='ollama_chat/llama3.1:8b' llm_client=<google.adk.models.lite_llm.LiteLLMClient object at 0x1057033e0>'.
✅ Root Agent 'weather_agent_v2' created using model 'qwen3:8b' with sub-agents: ['greeting_agent', 'farewell_agent']
Executing using 'asyncio.run()' (for standard Python scripts)...
--- Testing Agent Team Delegation ---
Session created: App='weather_tutorial_agent_team', User='user_1_agent_team', Session='session_001_agent_team'
Runner created for agent 'weather_agent_v2'.
>>> User Query: Bye!
.venv/lib/python3.12/site-packages/pydantic/main.py:463: UserWarning: Pydantic serializer warnings:
PydanticSerializationUnexpectedValue(Expected 9 fields but got 5: Expected `Message` - serialized value may not be as expected [input_value=Message(content='', role=...er_specific_fields=None), input_type=Message])
PydanticSerializationUnexpectedValue(Expected `StreamingChoices` - serialized value may not be as expected [input_value=Choices(finish_reason='st...r_specific_fields=None)), input_type=Choices])
return self.__pydantic_serializer__.to_python(
Give Feedback / Get Help: https://github.com/BerriAI/litellm/issues/new
LiteLLM.Info: If you need to debug this error, use `litellm._turn_on_debug()'.
An error occurred: litellm.APIConnectionError: Ollama_chatException - {"error":"json: cannot unmarshal array into Go struct field ChatRequest.messages.content of type string"}
python weather_bot_agent.py 3.63s user 0.54s system 31% cpu 13.078 total
% pip freeze | grep -e google-adk -e litellm
google-adk==1.3.0
litellm==1.72.6
% ollama --version
ollama version is 0.9.0
I'm getting the same problem with adk 1.10, ollama 0.10.1 and all models that I have tried (llama3.1:8b, deepseek-r1:8b, mistral:7b, qwen2.5:7b) when the agent has subagents.
I believe that problem can be in transfer to agent tool.
Hi @msbarathraj 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!