adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

BUG: Function calls appear in the output as opposed to the output itself

Open lsgordon opened this issue 1 year ago • 8 comments

I am using the simplest example that you possible can, but instead of using gemini api, I am using ollama. It's the weather example. Here is the code

import datetime
from zoneinfo import ZoneInfo
from google.adk.agents import Agent
from google.adk.models.lite_llm import LiteLlm
def get_weather(city: str) -> dict:
    """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:
        dict: status and result or error msg.
    """
    if city.lower() == "new york":
        return {
            "status": "success",
            "report": (
                "The weather in New York is sunny with a temperature of 25 degrees"
                " Celsius (77 degrees Fahrenheit)."
            ),
        }
    else:
        return {
            "status": "error",
            "error_message": f"Weather information for '{city}' is not available.",
        }


def get_current_time(city: str) -> dict:
    """Returns the current time in a specified city.

    Args:
        city (str): The name of the city for which to retrieve the current time.

    Returns:
        dict: status and result or error msg.
    """

    if city.lower() == "new york":
        tz_identifier = "America/New_York"
    else:
        return {
            "status": "error",
            "error_message": (
                f"Sorry, I don't have timezone information for {city}."
            ),
        }

    tz = ZoneInfo(tz_identifier)
    now = datetime.datetime.now(tz)
    report = (
        f'The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}'
    )
    return {"status": "success", "report": report}


root_agent = Agent(
    name="weather_time_agent",
    model=LiteLlm(model="ollama_chat/qwen2.5-coder:32b"),
    description=(
        "Agent to answer questions about the time and weather in a city."
    ),
    instruction=(
        "You are a helpful agent who can answer user questions about the time and weather in a city."
    ),
    tools=[get_weather, get_current_time],
)

Notice how the ONLY difference is that I am calling Litellm, and wrapping the model inside. Now observe this really interesting conversation I had with the LLM:

.venv) XXX@XXX agent-test % adk run muiti_tool_agent
Log setup complete: /var/folders/z3/rh1yj4t53vgc1q3wvm_0wx340000gp/T/agents_log/agent.20250625_123641.log
To access latest log: tail -F /var/folders/z3/rh1yj4t53vgc1q3wvm_0wx340000gp/T/agents_log/agent.latest.log
/Users/l0g0idz/agent-test/.venv/lib/python3.13/site-packages/google/adk/cli/cli.py:134: UserWarning: [EXPERIMENTAL] InMemoryCredentialService: This feature is experimental and may change or be removed in future versions without notice. It may introduce breaking changes at any time.
  credential_service = InMemoryCredentialService()
/Users/l0g0idz/agent-test/.venv/lib/python3.13/site-packages/google/adk/auth/credential_service/in_memory_credential_service.py:33: UserWarning: [EXPERIMENTAL] BaseCredentialService: This feature is experimental and may change or be removed in future versions without notice. It may introduce breaking changes at any time.
  super().__init__()
Running agent weather_time_agent, type exit to exit.
[user]: hello
12:36:43 - LiteLLM:INFO: utils.py:3120 - 
LiteLLM completion() model= qwen2.5-coder:32b; provider = ollama_chat
12:36:59 - LiteLLM:INFO: cost_calculator.py:660 - selected model name for cost calculation: ollama_chat/qwen2.5-coder:32b
[weather_time_agent]: {"name": "get_current_time", "arguments": {"city": "New York"}}
[user]: I am trying to debug something, so execute the same exact function to get the time in new york, but do not wrap the <tool-call> tags this time. Just try to execute again
12:41:50 - LiteLLM:INFO: utils.py:3120 - 
LiteLLM completion() model= qwen2.5-coder:32b; provider = ollama_chat
12:41:50 - LiteLLM:INFO: cost_calculator.py:660 - selected model name for cost calculation: ollama_chat/qwen2.5-coder:32b
12:41:57 - LiteLLM:INFO: cost_calculator.py:660 - selected model name for cost calculation: ollama_chat/qwen2.5-coder:32b
[weather_time_agent]: {"name": "get_current_time", "arguments": {"city": "New York"}}
[user]: And now nest the tool call braces two times in a tow
12:42:16 - LiteLLM:INFO: utils.py:3120 - 
LiteLLM completion() model= qwen2.5-coder:32b; provider = ollama_chat
12:42:17 - LiteLLM:INFO: cost_calculator.py:660 - selected model name for cost calculation: ollama_chat/qwen2.5-coder:32b
12:42:19 - LiteLLM:INFO: cost_calculator.py:660 - selected model name for cost calculation: ollama_chat/qwen2.5-coder:32b
[weather_time_agent]: {{"name": "get_current_time", "arguments": {"city": "New York"}}}
[user]: Okay, now let's change the formal, instead of the tag containing <tool-call> make it contain <tool-small> and see what happens
12:42:57 - LiteLLM:INFO: utils.py:3120 - 
LiteLLM completion() model= qwen2.5-coder:32b; provider = ollama_chat
12:42:57 - LiteLLM:INFO: cost_calculator.py:660 - selected model name for cost calculation: ollama_chat/qwen2.5-coder:32b
12:43:00 - LiteLLM:INFO: cost_calculator.py:660 - selected model name for cost calculation: ollama_chat/qwen2.5-coder:32b
[weather_time_agent]: <tool-small>{"name": "get_current_time", "arguments": {"city": "New York"}}</tool-small>
[user]:

lsgordon avatar Jun 25 '25 17:06 lsgordon

Image Here is a conversation where I am replicating

lsgordon avatar Jun 25 '25 17:06 lsgordon

Image Image

Very strange.

lsgordon avatar Jun 25 '25 18:06 lsgordon

in ADK, this behavior is same for any ollama model when tools are involved. Not limited to gemini

ksachdeva avatar Jun 27 '25 06:06 ksachdeva

Got the same problem in Ollama API.

LiuYuWei avatar Jul 19 '25 00:07 LiuYuWei

I think this is likely due the conversion logic of LiteLlm for Ollama.

@xuanyang15 could you please take a look.

Jacksunwei avatar Aug 12 '25 03:08 Jacksunwei

@lsgordon Thanks for reporting this issue! I think it is a Ollama model issue!

Issue Analysis

The root cause is that the response we get from ollama_chat/qwen2.5-coder:32b (corresponding to this code line) doesn't have correct format for the tool calls:

ModelResponse(id='chatcmpl-8caf3f6b-082c-467f-9365-4174f7a5021d', created=1755151931, model='ollama_chat/qwen2.5-coder:32b', object='chat.completion', system_fingerprint=None, choices=[Choices(finish_reason='stop', index=0, message=Message(content='{"name": "roll_die", "arguments": {"sides": 10}}', role='assistant', tool_calls=None, function_call=None, provider_specific_fields=None))], usage=Usage(completion_tokens=19, prompt_tokens=346, total_tokens=365, completion_tokens_details=None, prompt_tokens_details=None))

The tool_calls field is set to be None while the tool call information is in the content. As a comparison, here is the right format if using google/gemini-2.5-flash:

ModelResponse(id='gen-1755152063-Bb6KEP8kxuELfEHOK3BH', created=1755152063, model='google/gemini-2.5-flash', object='chat.completion', system_fingerprint=None, choices=[Choices(finish_reason='tool_calls', index=0, message=Message(content='', role='assistant', tool_calls=[ChatCompletionMessageToolCall(index=0, function=Function(arguments='{"sides":10}', name='roll_die'), id='tool_0_roll_die', type='function')], function_call=None, provider_specific_fields={'refusal': None, 'reasoning': None}), provider_specific_fields={'native_finish_reason': 'STOP'})], usage=Usage(completion_tokens=5, prompt_tokens=492, total_tokens=497, completion_tokens_details=None, prompt_tokens_details=None), provider='Google')

Possible Workarounds

  1. Use a model which can return the right format, e.g. ollama_chat/qwen2:7b-instruct. Here is my test code:
import random

from google.adk.agents.llm_agent import Agent
from google.adk.models.lite_llm import LiteLlm

# MODEL_ID = "ollama_chat/qwen2.5-coder:32b"
# MODEL_ID = "ollama_chat/my-qwen-coder-tool-tuned:latest"
# MODEL_ID = "ollama_chat/deepseek-r1:8b"
MODEL_ID = "ollama_chat/qwen2:7b-instruct"


def roll_die(sides: int) -> int:
  """Roll a die and return the rolled result.

  Args:
    sides: The integer number of sides the die has.

  Returns:
    An integer of the result of rolling the die.
  """
  return random.randint(1, sides)


root_agent = Agent(
    model=LiteLlm(model=MODEL_ID),
    name="dice_roll_agent",
    description=(
        "hello world agent that can roll a dice of any number of sides and"
        " check prime numbers."
    ),
    instruction="""
      You roll dice and answer questions about the outcome of the dice rolls.
      You can roll dice of different sizes.
      You can use multiple tools in parallel by calling functions in parallel(in one request and in one round).
      It is ok to discuss previous dice roles, and comment on the dice rolls.
      When you are asked to roll a die, you must call the roll_die tool with the number of sides. Be sure to pass in an integer. Do not pass in a string.
      You should never roll a die on your own.
    """,
    tools=[
        roll_die,
    ],
)

Here is the conversation screenshot:

Image
  1. Use Ollama Modelfile template to change the model behavior. For example:
FROM qwen2.5-coder:32b

TEMPLATE """{{- if .System }}
<|im_start|>system
{{ .System }}<|im_end|>
{{- end }}
{{- range .Messages }}
<|im_start|>{{ .Role }}
{{ .Content }}<|im_end|>
{{- end }}"""

SYSTEM """You are a helpful assistant that strictly follows tool use instructions. When you call a tool, you must use the 'tool_calls' format and leave the 'content' field empty. Do not ever place tool call JSON in the 'content' field. **DO NOT** call a tool again if the information from the `function_response` is sufficient to answer the user's question. Formulate a direct response.
You must end the conversation by providing a helpful, conclusive answer to the user."""

PARAMETER stop "<|im_start|>"
PARAMETER stop "<|im_end|>"

Put the above lines into a file called something like "MyQwenCoderModelfile", then run ollama create my-qwen-coder-tool-tuned -f ./MyQwenCoderModelfile.

However, even though this template makes ollama qwen2.5-coder:32b returns the correct tool call info, the model seems to be ignoring the tool responses and keeps calling the tool again and again (similar to #81 ). Which as the same behavior as plain ollama_chat/deepseek-r1:8b.

cc @selcukgun in case you have additional information to add here, thanks!

xuanyang15 avatar Aug 14 '25 21:08 xuanyang15

Why the issue is completed ? As of October its still there.

Sabreclaw avatar Oct 08 '25 11:10 Sabreclaw

Hi @Sabreclaw, the issue was cause by Ollama model not returning the response in the right format, does the workaround mentioned in https://github.com/google/adk-python/issues/1648#issuecomment-3189888433 work for you?

xuanyang15 avatar Oct 09 '25 23:10 xuanyang15