How to handle 'Function is not found in the tools_dict' Error
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
+1
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.
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.
+1 Same error here using model="gemini-2.5-flash-lite" and model="gemini-2.5-flash".
idk how to catch this LLM errors
Even I'm facing the same issue:
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."
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)
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
Same here. Would be great if adk can handle this
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
Try switching to Vertex AI (using project ID and region rather than API key) This helped in my case
facing the same issue. It is interesting that this error happens only sometime
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.
I've submitted a PR that directly addresses the "Function is not found in the tools_dict" error handling issue:
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_weatherThis 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?
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?
Great question @kxcode!
The PR improves the error message but does not change the exception behavior. Users will still receive the
ValueErrorwhen 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 Function Tool verification callback before throwing "Tool xxxx is not found in the tools_dict" exception #2050)
- Pre-execution validation hooks
- Agent instruction improvements to reduce hallucinations
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.
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
- PR #3219 → Better error messages (helps developers debug)
- 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
How can I use plugin in AdKApp deployed on VertexAgentEngine because ADKApp has no plug-in input parameter
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.