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

How to handle 'Function is not found in the tools_dict' Error

Open kxcode opened this issue 1 year ago • 19 comments

sometimes Gemini calls function with wrong tool name, will cause a ValueError, how can I handle this Error

line 447, in _run_one_step_async
    async for event in agen:
  File "/python3.12/site-packages/google/adk/flows/llm_flows/base_llm_flow.py", line 539, in _postprocess_async
    async for event in agen:
  File "/python3.12/site-packages/google/adk/flows/llm_flows/base_llm_flow.py", line 632, in _postprocess_handle_function_calls_async
    if function_response_event := await functions.handle_function_calls_async(
                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/python3.12/site-packages/google/adk/flows/llm_flows/functions.py", line 198, in handle_function_calls_async
    return await handle_function_call_list_async(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/python3.12/site-packages/google/adk/flows/llm_flows/functions.py", line 246, in handle_function_call_list_async
    function_response_events = await asyncio.gather(*tasks)
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/python3.12/site-packages/google/adk/flows/llm_flows/functions.py", line 280, in _execute_single_function_call_async
    tool, tool_context = _get_tool_and_context(
                         ^^^^^^^^^^^^^^^^^^^^^^
  File "/python3.12/site-packages/google/adk/flows/llm_flows/functions.py", line 651, in _get_tool_and_context
    raise ValueError(
ValueError: Function add_-plan_step is not found in the tools_dict

kxcode avatar Sep 12 '25 09:09 kxcode

+1

pinkponk avatar Sep 17 '25 15:09 pinkponk

I have the same issue.

I was thinking of using the 'after_model_callback' and creating a custom function that searches for the model's provided function definitions and checks the available functions (stored in the callback context or fetched from the adk context if that is possible. Don't know yet). If no match is found, you can do a closest string match (i.e., Levenshtein distance, or semantic similarity) or correct it with another model.

But to be honest, it would be nice if the adk handles this. At least with a simple retry mechanism, so the model is informed about its mistake.

Drinect avatar Sep 17 '25 16:09 Drinect

yes it is crucial to be able to catch this value error. as the situation is now for me my entire agent flow just stops when this happens. Very annoying. I want to be able to catch this in a plugin.

pinkponk avatar Sep 17 '25 18:09 pinkponk

+1 Same error here using model="gemini-2.5-flash-lite" and model="gemini-2.5-flash".

idk how to catch this LLM errors

nicodelatorre7 avatar Sep 18 '25 14:09 nicodelatorre7

Even I'm facing the same issue:

Image

NikhilKalloli avatar Sep 23 '25 10:09 NikhilKalloli

Try adding this in the agent instructions. It has worked for 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."

NikhilKalloli avatar Sep 23 '25 11:09 NikhilKalloli

This bug appears to have been introduced in version 1.9.0 of google-adk. I reverted to 1.8.0 and it now works fine again. This is not ideal though.

[EDIT] - we are actually seeing this error in older versions as well (1.7.0 and 1.8.0)

reyolivo avatar Sep 25 '25 15:09 reyolivo

This bug appears to have been introduced in version 1.9.0 of google-adk. I reverted to 1.8.0 and it now works fine again. This is not ideal though.

[EDIT] - we are actually seeing this error in older versions as well (1.7.0 and 1.8.0)

Yeah, it's a universal problem from the google adk. Hope they fix it soon

NikhilKalloli avatar Sep 26 '25 03:09 NikhilKalloli

Same here. Would be great if adk can handle this

iamsrinathks avatar Sep 26 '25 13:09 iamsrinathks

any update on this? We were able to reduce the frequency of the error by including tool specific instructions in the system prompt...but still not 100% resolved, and feels like a bad pattern to continue. Is there at least a better way to catch an incorrect tool from being called, and have the agent retry? An example would be very helpful

reyolivo avatar Oct 01 '25 13:10 reyolivo

Try switching to Vertex AI (using project ID and region rather than API key) This helped in my case

NikhilKalloli avatar Oct 01 '25 15:10 NikhilKalloli

facing the same issue. It is interesting that this error happens only sometime

tara012024 avatar Oct 14 '25 00:10 tara012024

I've submitted a PR that directly addresses the "Function is not found in the tools_dict" error handling issue:

PR #3219: https://github.com/google/adk-python/pull/3219

The enhanced error messages now provide:

  • Clear problem description: What went wrong
  • Available tools list: All valid tools formatted for easy scanning
  • Possible causes: LLM hallucination, configuration error, or typo
  • Suggested fixes: Actionable steps to resolve
  • Fuzzy matching: "Did you mean...?" suggestions for typos

Example: Instead of the cryptic error:

ValueError: Function get_wether is not found in the tools_dict: dict_keys(['get_weather', 'calculate_sum'])

You now get:

Function 'get_wether' is not found in available tools.

Available tools: get_weather, calculate_sum

Possible causes:
  1. LLM hallucinated the function name - review agent instruction clarity
  2. Tool not registered - verify agent.tools list
  3. Name mismatch - check for typos

Suggested fixes:
  - Review agent instruction to ensure tool usage is clear
  - Verify tool is included in agent.tools list
  - Check for typos in function name

Did you mean one of these?
  - get_weather

This has been validated in production and reduces debugging time from hours to minutes.

jpantsjoha avatar Oct 18 '25 17:10 jpantsjoha

I've submitted a PR that directly addresses the "Function is not found in the tools_dict" error handling issue:

PR #3219: #3219

The enhanced error messages now provide:

  • Clear problem description: What went wrong
  • Available tools list: All valid tools formatted for easy scanning
  • Possible causes: LLM hallucination, configuration error, or typo
  • Suggested fixes: Actionable steps to resolve
  • Fuzzy matching: "Did you mean...?" suggestions for typos

Example: Instead of the cryptic error:

ValueError: Function get_wether is not found in the tools_dict: dict_keys(['get_weather', 'calculate_sum'])

You now get:

Function 'get_wether' is not found in available tools.

Available tools: get_weather, calculate_sum

Possible causes:
  1. LLM hallucinated the function name - review agent instruction clarity
  2. Tool not registered - verify agent.tools list
  3. Name mismatch - check for typos

Suggested fixes:
  - Review agent instruction to ensure tool usage is clear
  - Verify tool is included in agent.tools list
  - Check for typos in function name

Did you mean one of these?
  - get_weather

This has been validated in production and reduces debugging time from hours to minutes.

After you make this PR, will users be able to catch this 'Function is not found' error?

kxcode avatar Oct 19 '25 00:10 kxcode

Great question @kxcode!

The PR improves the error message but does not change the exception behavior. Users will still receive the ValueError when the LLM hallucinates a function name, but with much better debugging information.

Before the PR:

  • Error occurs and throws ValueError
  • Message is cryptic: Function get_wether is not found in the tools_dict: dict_keys(['get_weather', 'calculate_sum'])
  • Debugging requires manual inspection of agent configuration

After the PR:

  • Error still occurs and throws ValueError (same exception)
  • Message is actionable: Lists available tools, suggests fixes, provides fuzzy matching
  • Debugging is faster: Clear next steps to resolve

To catch the error programmatically, users can already use standard Python exception handling:

try:
    result = await agent.run(user_input)
except ValueError as e:
    if 'not found in available tools' in str(e):
        # Handle hallucinated tool call
        logger.warning(f"LLM hallucinated: {e}")
        # Retry with clearer instructions or fallback logic

The PR makes it easier to diagnose the issue, but the exception flow remains the same. If you need proactive prevention (stopping hallucinations before they throw errors), that would require:

  • Tool verification callbacks (tracked in issue #2050)
  • Pre-execution validation hooks
  • Agent instruction improvements to reduce hallucinations

Does this clarify the scope of the enhancement?

jpantsjoha avatar Oct 19 '25 19:10 jpantsjoha

Great question @kxcode!

The PR improves the error message but does not change the exception behavior. Users will still receive the ValueError when the LLM hallucinates a function name, but with much better debugging information.

Before the PR:

  • Error occurs and throws ValueError
  • Message is cryptic: Function get_wether is not found in the tools_dict: dict_keys(['get_weather', 'calculate_sum'])
  • Debugging requires manual inspection of agent configuration

After the PR:

  • Error still occurs and throws ValueError (same exception)
  • Message is actionable: Lists available tools, suggests fixes, provides fuzzy matching
  • Debugging is faster: Clear next steps to resolve

To catch the error programmatically, users can already use standard Python exception handling:

try: result = await agent.run(user_input) except ValueError as e: if 'not found in available tools' in str(e): # Handle hallucinated tool call logger.warning(f"LLM hallucinated: {e}") # Retry with clearer instructions or fallback logic The PR makes it easier to diagnose the issue, but the exception flow remains the same. If you need proactive prevention (stopping hallucinations before they throw errors), that would require:

Does this clarify the scope of the enhancement?

Okay, but this PR seems doesn’t solve my problem. Users are unable to gracefully catch exceptions and retry at the point where the exception occurred. It would be better if the ADK framework had a built-in retry mechanism.

kxcode avatar Oct 21 '25 03:10 kxcode

Great feedback, @kxcode!

You're absolutely right - and I have excellent news: ADK already has a built-in retry mechanism! 🎉

ReflectAndRetryToolPlugin

ADK includes ReflectAndRetryToolPlugin (available since v1.16.0) that handles EXACTLY what you're requesting, including LLM hallucination retries.

Usage:

from google.adk.plugins import ReflectAndRetryToolPlugin

retry_plugin = ReflectAndRetryToolPlugin(max_retries=3)

app = App(
    name="my_app",
    root_agent=my_agent,
    plugins=[retry_plugin]  # Enable automatic retries
)

What it does:

  • Intercepts tool execution errors (including "Function not found")
  • Provides structured reflection guidance to the LLM
  • Automatically retries up to max_retries
  • Handles hallucinating function calls gracefully
  • Thread-safe for concurrent tool executions

There's even a complete example demonstrating hallucinating tool calls: 📂 contributing/samples/plugin_reflect_tool_retry/hallucinating_func_name/

How This Complements PR #3219

  1. PR #3219 → Better error messages (helps developers debug)
  2. ReflectAndRetryToolPlugin → Built-in retry mechanism (helps LLM self-correct)

Both are valuable:

  • PR #3219 improves DX when errors occur during development
  • ReflectAndRetryToolPlugin handles production runtime hallucinations

I'll update PR #3219 to mention this plugin in the error message, so developers know it exists! 👍

References

  • Plugin source: src/google/adk/plugins/reflect_retry_tool_plugin.py
  • Example: contributing/samples/plugin_reflect_tool_retry/README.md
  • Import: from google.adk.plugins import ReflectAndRetryToolPlugin

Thanks for checking out my PR and your feedback. Hopefully this would be an all rounded improvement, with enhanced message pointing to that retry mechanism. Cheers, JP

jpantsjoha avatar Oct 21 '25 08:10 jpantsjoha

How can I use plugin in AdKApp deployed on VertexAgentEngine because ADKApp has no plug-in input parameter

MonicaRekhaN avatar Nov 01 '25 11:11 MonicaRekhaN

How can I use plugin in AdKApp deployed on VertexAgentEngine because ADKApp has no plug-in input parameter

The support will come soon.

Closing this ticket as the original question is addressed with ReflectRetryPlugin.

hangfei avatar Nov 07 '25 04:11 hangfei