How to exit the langgraph and raise exception if any one of the nodes fail? #24695
Replies: 1 comment 4 replies
-
To exit the workflow completely if you encounter an unexpected error in any of the nodes and print out the error message of the node that fails, you can use the
Here is a code example: from langchain_core.tools import ToolException
from langchain.tools import StructuredTool
# Define a custom error handler function
def _handle_error(error: ToolException) -> str:
error_message = f"Error in tool: {error.args[0]}"
print(error_message) # Print the error message
raise SystemExit(error_message) # Exit the workflow completely
# Define a tool that raises a ToolException
def search_tool1(s: str):
raise ToolException("The search tool1 is not available.")
# Create the tool with the custom error handler
search = StructuredTool.from_function(
func=search_tool1,
name="Search_tool1",
description="A bad tool",
handle_tool_error=_handle_error,
)
# Run the tool
search.run("test") In this example, if Additionally, you can use conditional edges in LangChain workflows to handle error states and redirect the workflow to an error handling node. Here is an example of how you might add an error handling node: from langgraph.graph import END, StateGraph
# Define a new graph
workflow = StateGraph(AgentState)
# Define the nodes we will cycle between
workflow.add_node("agent", call_model) # agent
workflow.add_node("action", call_tool) # retrieval
workflow.add_node("error_handler", handle_error) # error handling
# Call agent node to decide to retrieve or not
workflow.set_entry_point("agent")
# Decide whether to retrieve
workflow.add_conditional_edges(
"agent",
# Assess agent decision
should_retrieve,
{
# Call tool node
"continue": "action",
"end": END,
},
)
# Edges taken after the `action` node is called.
workflow.add_conditional_edges(
"action",
# Assess agent decision
check_relevance,
{
# Call agent node
"yes": "agent",
"no": END, # placeholder
},
)
# Example of adding an error condition
def check_for_error(state):
# Implement your error checking logic here
if "error" in state:
return "error"
return "no_error"
workflow.add_conditional_edges(
"agent",
check_for_error,
{
"error": "error_handler",
"no_error": "action",
},
)
# Compile
app = workflow.compile() In this example, |
Beta Was this translation helpful? Give feedback.
-
Checked other resources
Commit to Help
Example Code
Description
I have some nodes in my langgraph and I will stream out the results of each LLM call in some of the nodes, how can I exit the workflow completely if I encounter some unexpected error in any of the nodes and print out the error message of that node which fail? Do I need to wrap the code in a try catch in all of my nodes and add a conditional edge for each nodes?
System Info
langchain==0.2.1
linux
python 3.11
Beta Was this translation helpful? Give feedback.
All reactions