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

fix(llm_flows): resolve issue where adk is unavailable when tool is not present

Open growmuye opened this issue 1 year ago • 6 comments

Resolve the issue of ADK being unavailable when the tool is not present.

Reproduce the code

from google.genai.types import GenerateContentConfig

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

import litellm
litellm._turn_on_debug()

model = LiteLlm(
   ...deepseek-v3
)

content_config = GenerateContentConfig(
    temperature=0.01,
    top_p=0.01,
    max_output_tokens=8192,
)


async def search_resume() -> str:
    """
    搜索简历

    Returns:
        搜索结果
    """
    return "搜索成功"


root_agent = Agent(
    model=model,
    name="Assistant",
    description="你是一个AI助手",
    instruction="你是一个AI助手",
    tools=[search_resume],
    generate_content_config=content_config
)

如何复现

step1

adk web 输入:你必须调用一次一个不存在的工具:"search_resumes" image

NOTE:The reason for inputting a seemingly unreasonable user_query is that this phenomenon is difficult to reproduce, but we have indeed observed such hallucinations in the production environment, even though the user's input was completely normal.

error log:

  File "/Users/gmy/Documents/experimentProjects/adk-python/src/google/adk/flows/llm_flows/functions.py", line 203, in _execute_single_function_call_async
    tool, tool_context = _get_tool_and_context(
                         ^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/gmy/Documents/experimentProjects/adk-python/src/google/adk/flows/llm_flows/functions.py", line 569, in _get_tool_and_context
    raise ValueError(
ValueError: Function search_resumes is not found in the tools_dict.

code point: image image

step2

Afterwards, for any user_query entered, the agent will not respond at all, because the messages requesting the LLM are corrupted, and the LLM will keep reporting errors.image

llm req log:

-d '{'model': 'baidu/deepseek-v3', 'messages': [{'role': 'system', 'content': '你是一个AI助手\n\nYou are an agent. Your internal name is "Assistant".\n\n The description about you is "你是一个AI助手"'}, {'role': 'user', 'content'不存在的工具:"search_resumes"'}, {'role': 'assistant', 'tool_calls': [{'type': 'function', 'id': '3fd3647f45954525b5a36d4a0297a5b4', 'function': {'name': 'search_resumes', 'arguments': '{}'}}]}, {'role': 'user', 'content': '你好e': 'user', 'content': '你好'}], 'temperature': 0.01, 'top_p': 0.01, 'max_completion_tokens': 8192, 'tools': [{'type': 'function', 'function': {'name': 'search_resume', 'description': '\n    搜索简历\n\n    Returns:\n        搜索', 'parameters': {'type': 'object', 'properties': {}}}}], 'extra_body': {}}'

llm resp log:

{"id": null, "choices": null, "created": null, "model": null, "object": null, "service_tier": null, "system_fingerprint": null, "usage": null, "error": {"message": "{\"error\":{\"code\":\"invalid_argument\",\"message\":\"Message format error, index[3] should be [tool] but is [user]\",\"type\":\"invalid_request_error\"},\"id\":\"as-fnmf4rty16\"}"}, "request_id": "b7ba2e5d-0386-455d-8762-aecfac13d014"}

My repair suggestion

When a tool does not exist, normally return an Event, which minimally ensures that users can continue chatting rather than being unable to use it.image

Repaired effect: image

growmuye avatar Aug 05 '25 09:08 growmuye

Same error here. Great suggestion, but anyway, is there a way to catch this kind of error?

nicodelatorre7 avatar Sep 18 '25 15:09 nicodelatorre7

An additional prompt in the agent instructions like below seems to have helped in my case

# Tool Selection Guide

**Tool Name Verification (Critical):** 
Before calling any tool, *always* meticulously verify its exact name against the `tool_code` definitions provided in the execution context. 
Use the precise, full name as it appears there, including any hyphens or prefixes (e.g., `firebase-firebase_list_projects`, not `firebase_list_projects`). 
Do not abbreviate or simplify tool names. 
Calling a tool with an incorrect name will result in an error."

hamiltonchua avatar Sep 19 '25 06:09 hamiltonchua

I tried adding an additional instruction, like suggested by @hamiltonchua , but not having much improvement. Also, I notice that the error happens about 50% of the time (not always)

reyolivo avatar Sep 25 '25 18:09 reyolivo

@hamiltonchua LLMs cannot 100% avoid accidents. I think it would be better to have a switch to cover for errors. Once this error occurs, it will render the entire session unusable, which is quite serious.

growmuye avatar Oct 13 '25 12:10 growmuye

Root Cause

When the LLM hallucinates a non-existent tool name, the error occurs in _get_tool_and_context() at functions.py:569, which raises a ValueError that crashes the entire session.

Solution: ReflectAndRetryToolPlugin

The ReflectAndRetryToolPlugin is designed for exactly this scenario. It:

  1. Intercepts tool errors via on_tool_error_callback
  2. Returns a structured error response instead of crashing
  3. Provides specific guidance about wrong function names (line 330)
  4. Allows configurable retries with max_retries
  5. Preserves message history so users can continue chatting

Usage

Add the plugin to your App (from the hallucinating function name sample):

from google.adk.plugins import ReflectAndRetryToolPlugin

app = App(
    name=APP_NAME,
    root_agent=root_agent,
    plugins=[
        ReflectAndRetryToolPlugin(max_retries=3),
    ],
)

This ensures that when tool-not-found errors occur, the agent can recover gracefully and guide the LLM to use the correct tool name instead of crashing the session.

Jacksunwei avatar Oct 28 '25 05:10 Jacksunwei

Closing as this can be resolved using the ReflectAndRetryToolPlugin. See the comment above for details.

Jacksunwei avatar Oct 28 '25 05:10 Jacksunwei