High severity intermediate · Fix: 5-15 min

ToolException

langchain.agents.agent.ToolException

What this error means
LangChain's agent failed to execute a tool due to an error in the tool call or response handling.

Stack trace

traceback
langchain.agents.agent.ToolException: Agent tool execution failed: Tool 'search' returned an error: KeyError: 'results'
  File "/usr/local/lib/python3.10/site-packages/langchain/agents/agent.py", line 345, in _call_tool
    output = tool.run(tool_input)
  File "/usr/local/lib/python3.10/site-packages/langchain/tools/base.py", line 78, in run
    raise ToolException(f"Tool '{self.name}' returned an error: {e}")
langchain.agents.agent.ToolException: Agent tool execution failed: Tool 'search' returned an error: KeyError: 'results'
QUICK FIX
Wrap agent tool calls in try/except ToolException to catch errors and inspect the underlying cause quickly.

Why it happens

This error occurs when an agent tries to run a tool but the tool's internal execution fails, often due to unexpected input, missing keys in the tool's response, or misconfigured tool parameters. The agent wraps the underlying tool error as a ToolException to signal failure in tool execution.

Detection

Catch ToolException around agent tool calls and log the tool name and raw error message to identify which tool failed and why before the agent crashes.

Causes & fixes

1

The tool's response is missing expected keys, causing a KeyError during processing.

✓ Fix

Validate the tool's output format and ensure all expected keys are present before returning the result.

2

The tool was called with incorrect or incomplete input parameters.

✓ Fix

Check the agent's tool input construction logic and ensure all required parameters are correctly passed.

3

The tool's internal API call or logic raised an exception (e.g., network error, parsing failure).

✓ Fix

Add error handling inside the tool's run method to catch and handle API or processing errors gracefully.

4

The tool is not properly registered or initialized in the agent's tool list.

✓ Fix

Verify the tool is correctly instantiated and included in the agent's tools parameter before execution.

Code: broken vs fixed

Broken - triggers the error
python
from langchain.agents import initialize_agent, Tool
from langchain.llms import OpenAI

llm = OpenAI(temperature=0)
tools = [Tool(name="search", func=lambda x: "")]
agent = initialize_agent(tools, llm, agent="zero-shot-react-description")

# This line triggers ToolException if tool fails
result = agent.run("Find the latest news about AI.")
Fixed - works correctly
python
import os
from langchain.agents import initialize_agent, Tool, ToolException
from langchain.llms import OpenAI

llm = OpenAI(temperature=0)

# Define a robust tool with error handling
class SearchTool(Tool):
    name = "search"
    def run(self, query: str) -> str:
        try:
            # Simulate API call or logic
            response = {"results": ["AI news item 1", "AI news item 2"]}
            return response["results"][0]
        except KeyError as e:
            raise ToolException(f"Missing key in search response: {e}")

search_tool = SearchTool()
tools = [search_tool]
agent = initialize_agent(tools, llm, agent="zero-shot-react-description")

try:
    result = agent.run("Find the latest news about AI.")
    print("Agent result:", result)
except ToolException as e:
    print(f"Agent tool execution failed: {e}")
Added a custom Tool subclass with error handling to prevent missing key errors and wrapped agent.run in try/except ToolException to catch and report tool execution failures.

Workaround

Wrap the agent.run call in try/except ToolException, then parse the raw error message to extract partial results or fallback to a default response.

Prevention

Implement thorough input validation and error handling inside each tool's run method, and ensure tools are correctly registered and tested independently before agent integration.

Python 3.9+ · langchain-core >=0.1.0 · tested on 0.2.x
Verified 2026-04
Verify ↗

Community Notes

No notes yetBe the first to share a version-specific fix or tip.