A node that validates all tools requests from the last AIMessage.
It can be used either in StateGraph with a 'messages' key.
This node does not actually run the tools, it only validates the tool calls, which is useful for extraction and other use cases where you need to generate structured output that conforms to a complex schema without losing the original messages and tool IDs (for use in multi-turn conversations).
ValidationNode(
self,
schemas: Sequence[BaseTool | type[BaseModel] | Callable],
*,
format_error: Callable[[BaseException, ToolCall, type[BaseModel]], str] | None = None,
name: str = 'validation',
tags: list[str] | None = None
)Example:
from typing import Literal, Annotated
from typing_extensions import TypedDict
from langchain_anthropic import ChatAnthropic
from pydantic import BaseModel, field_validator
from langgraph.graph import END, START, StateGraph
from langgraph.prebuilt import ValidationNode
from langgraph.graph.message import add_messages
class SelectNumber(BaseModel):
a: int
@field_validator("a")
def a_must_be_meaningful(cls, v):
if v != 37:
raise ValueError("Only 37 is allowed")
return v
builder = StateGraph(Annotated[list, add_messages])
llm = ChatAnthropic(model="claude-3-5-haiku-latest").bind_tools([SelectNumber])
builder.add_node("model", llm)
builder.add_node("validation", ValidationNode([SelectNumber]))
builder.add_edge(START, "model")
def should_validate(state: list) -> Literal["validation", "__end__"]:
if state[-1].tool_calls:
return "validation"
return END
builder.add_conditional_edges("model", should_validate)
def should_reprompt(state: list) -> Literal["model", "__end__"]:
for msg in state[::-1]:
# None of the tool calls were errors
if msg.type == "ai":
return END
if msg.additional_kwargs.get("is_error"):
return "model"
return END
builder.add_conditional_edges("validation", should_reprompt)
graph = builder.compile()
res = graph.invoke(("user", "Select a number, any number"))
# Show the retry logic
for msg in res:
msg.pretty_print()| Name | Type | Description |
|---|---|---|
schemas* | Sequence[BaseTool | type[BaseModel] | Callable] | A list of schemas to validate the tool calls with. These can be any of the following:
|
format_error | Callable[[BaseException, ToolCall, type[BaseModel]], str] | None | Default: NoneA function that takes an exception, a ToolCall, and a schema and returns a formatted error string. By default, it returns the exception repr and a message to respond after fixing validation errors. |
name | str | Default: 'validation'The name of the node. |
tags | list[str] | None | Default: NoneA list of tags to add to the node. |