Step-by-Step Guide to Build a Customizable Multi-Tool AI Agent with LangGraph and Claude for Dynamic Agent Creation
In this comprehensive tutorial, we guide users through creating a powerful multi-tool AI agent using LangGraph and Claude, optimized for diverse tasks including mathematical computations, web searches, weather inquiries, text analysis, and real-time information retrieval. It begins by simplifying dependency installations to ensure effortless setup, even for beginners. Users are then introduced to structured implementations of specialized tools, such as a safe calculator, an efficient web-search utility leveraging DuckDuckGo, a mock weather information provider, a detailed text analyzer, and a time-fetching function. The tutorial also clearly delineates the integration of these tools within a sophisticated agent architecture built using LangGraph, illustrating practical usage through interactive examples and clear explanations, facilitating both beginners and advanced developers to deploy custom multi-functional AI agents rapidly.
import subprocess
import sys
def install_packages:
packages =for package in packages:
try:
subprocess.check_callprintexcept subprocess.CalledProcessError:
printprintinstall_packagesprintWe automate the installation of essential Python packages required for building a LangGraph-based multi-tool AI agent. It leverages a subprocess to run pip commands silently and ensures each package, ranging from long-chain components to web search and environment handling tools, is installed successfully. This setup streamlines the environment preparation process, making the notebook portable and beginner-friendly.
import os
import json
import math
import requests
from typing import Dict, List, Any, Annotated, TypedDict
from datetime import datetime
import operator
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, ToolMessage
from langchain_core.tools import tool
from langchain_anthropic import ChatAnthropic
from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import ToolNode
from langgraph.checkpoint.memory import MemorySaver
from duckduckgo_search import DDGS
We import all the necessary libraries and modules for constructing the multi-tool AI agent. It includes Python standard libraries such as os, json, math, and datetime for general-purpose functionality and external libraries like requests for HTTP calls and duckduckgo_search for implementing web search. The LangChain and LangGraph ecosystems bring in message types, tool decorators, state graph components, and checkpointing utilities, while ChatAnthropic enables integration with the Claude model for conversational intelligence. These imports form the foundational building blocks for defining tools, agent workflows, and interactions.
os.environ= "Use Your API Key Here"
ANTHROPIC_API_KEY = os.getenvWe set and retrieve the Anthropic API key required to authenticate and interact with Claude models. The os.environ line assigns your API key, while os.getenv securely retrieves it for later use in model initialization. This approach ensures the key is accessible throughout the script without hardcoding it multiple times.
from typing import TypedDict
class AgentState:
messages: Annotated, operator.add]
@tool
def calculator-> str:
"""
Perform mathematical calculations. Supports basic arithmetic, trigonometry, and more.
Args:
expression: Mathematical expression as a string")
Returns:
Result of the calculation as a string
"""
try:
allowed_names = {
'abs': abs, 'round': round, 'min': min, 'max': max,
'sum': sum, 'pow': pow, 'sqrt': math.sqrt,
'sin': math.sin, 'cos': math.cos, 'tan': math.tan,
'log': math.log, 'log10': math.log10, 'exp': math.exp,
'pi': math.pi, 'e': math.e
}
expression = expression.replaceresult = evalreturn f"Result: {result}"
except Exception as e:
return f"Error in calculation: {str}"
We define the agent’s internal state and implement a robust calculator tool. The AgentState class uses TypedDict to structure agent memory, specifically tracking messages exchanged during the conversation. The calculator function, decorated with @tool to register it as an AI-usable utility, securely evaluates mathematical expressions. It allows for safe computation by limiting available functions to a predefined set from the math module and replacing common syntax like ^ with Python’s exponentiation operator. This ensures the tool can handle simple arithmetic and advanced functions like trigonometry or logarithms while preventing unsafe code execution.
@tool
def web_search-> str:
"""
Search the web for information using DuckDuckGo.
Args:
query: Search query string
num_results: Number of results to returnReturns:
Search results as formatted string
"""
try:
num_results = min, 10)
with DDGSas ddgs:
results = list)
if not results:
return f"No search results found for: {query}"
formatted_results = f"Search results for '{query}':\n\n"
for i, result in enumerate:
formatted_results += f"{i}. **{result}**\n"
formatted_results += f" {result}\n"
formatted_results += f" Source: {result}\n\n"
return formatted_results
except Exception as e:
return f"Error performing web search: {str}"
We define a web_search tool that enables the agent to fetch real-time information from the internet using the DuckDuckGo Search API via the duckduckgo_search Python package. The tool accepts a search query and an optional num_results parameter, ensuring that the number of results returned is between 1 and 10. It opens a DuckDuckGo search session, retrieves the results, and formats them neatly for user-friendly display. If no results are found or an error occurs, the function handles it gracefully by returning an informative message. This tool equips the agent with real-time search capabilities, enhancing responsiveness and utility.
@tool
def weather_info-> str:
"""
Get current weather information for a city using OpenWeatherMap API.
Note: This is a mock implementation for demo purposes.
Args:
city: Name of the city
Returns:
Weather information as a string
"""
mock_weather = {
"new york": {"temp": 22, "condition": "Partly Cloudy", "humidity": 65},
"london": {"temp": 15, "condition": "Rainy", "humidity": 80},
"tokyo": {"temp": 28, "condition": "Sunny", "humidity": 70},
"paris": {"temp": 18, "condition": "Overcast", "humidity": 75}
}
city_lower = city.lowerif city_lower in mock_weather:
weather = mock_weatherreturn f"Weather in {city}:\n" \
f"Temperature: {weather}°C\n" \
f"Condition: {weather}\n" \
f"Humidity: {weather}%"
else:
return f"Weather data not available for {city}."
We define a weather_info tool that simulates retrieving current weather data for a given city. While it does not connect to a live weather API, it uses a predefined dictionary of mock data for major cities like New York, London, Tokyo, and Paris. Upon receiving a city name, the function normalizes it to lowercase and checks for its presence in the mock dataset. It returns temperature, weather condition, and humidity in a readable format if found. Otherwise, it notifies the user that weather data is unavailable. This tool serves as a placeholder and can later be upgraded to fetch live data from an actual weather API.
@tool
def text_analyzer-> str:
"""
Analyze text and provide statistics like word count, character count, etc.
Args:
text: Text to analyze
Returns:
Text analysis results
"""
if not text.strip:
return "Please provide text to analyze."
words = text.splitsentences = text.split+ text.split+ text.splitsentences =analysis = f"Text Analysis Results:\n"
analysis += f"• Characters: {len}\n"
analysis += f"• Characters: {len)}\n"
analysis += f"• Words: {len}\n"
analysis += f"• Sentences: {len}\n"
analysis += f"• Average words per sentence: {len/ max, 1):.1f}\n"
analysis += f"• Most common word: {max, key=words.count) if words else 'N/A'}"
return analysis
The text_analyzer tool provides a detailed statistical analysis of a given text input. It calculates metrics such as character count, word count, sentence count, and average words per sentence, and it identifies the most frequently occurring word. The tool handles empty input gracefully by prompting the user to provide valid text. It uses simple string operations and Python’s set and max functions to extract meaningful insights. It is a valuable utility for language analysis or content quality checks in the AI agent’s toolkit.
@tool
def current_time-> str:
"""
Get the current date and time.
Returns:
Current date and time as a formatted string
"""
now = datetime.nowreturn f"Current date and time: {now.strftime}"
The current_time tool provides a straightforward way to retrieve the current system date and time in a human-readable format. Using Python’s datetime module, it captures the present moment and formats it as YYYY-MM-DD HH:MM:SS. This utility is particularly useful for time-stamping responses or answering user queries about the current date and time within the AI agent’s interaction flow.
tools =def create_llm:
if ANTHROPIC_API_KEY:
return ChatAnthropicelse:
class MockLLM:
def invoke:
last_message = messages.content if messages else ""
if anyfor word in):
import re
numbers = re.findall\s\w]+', last_message)
expr = numbersif numbers else "2+2"
return AIMessage}, "id": "calc1"}])
elif anyfor word in):
query = last_message.replace.replace.replace.stripif not query or len< 3:
query = "python programming"
return AIMessageelif anyfor word in):
city = "New York"
words = last_message.lower.splitfor i, word in enumerate:
if word == 'in' and i + 1 < len:
city = words.titlebreak
return AIMessageelif anyfor word in):
return AIMessageelif anyfor word in):
text = last_message.replace.replace.stripif not text:
text = "Sample text for analysis"
return AIMessageelse:
return AIMessagedef bind_tools:
return self
printreturn MockLLMllm = create_llmllm_with_tools = llm.bind_toolsWe initialize the language model that powers the AI agent. If a valid Anthropic API key is available, it uses the Claude 3 Haiku model for high-quality responses. Without an API key, a MockLLM is defined to simulate basic tool-routing behavior based on keyword matching, allowing the agent to function offline with limited capabilities. The bind_tools method links the defined tools to the model, enabling it to invoke them as needed.
def agent_node-> Dict:
"""Main agent node that processes messages and decides on tool usage."""
messages = stateresponse = llm_with_tools.invokereturn {"messages":}
def should_continue-> str:
"""Determine whether to continue with tool calls or end."""
last_message = stateif hasattrand last_message.tool_calls:
return "tools"
return END
We define the agent’s core decision-making logic. The agent_node function handles incoming messages, invokes the language model, and returns the model’s response. The should_continue function then evaluates whether the model’s response includes tool calls. If so, it routes control to the tool execution node; otherwise, it directs the flow to end the interaction. These functions enable dynamic and conditional transitions within the agent’s workflow.
def create_agent_graph:
tool_node = ToolNodeworkflow = StateGraphworkflow.add_nodeworkflow.add_nodeworkflow.add_edgeworkflow.add_conditional_edgesworkflow.add_edgememory = MemorySaverapp = workflow.compilereturn app
printagent = create_agent_graphprintWe construct the LangGraph-powered workflow that defines the AI agent’s operational structure. It initializes a ToolNode to handle tool executions and uses a StateGraph to organize the flow between agent decisions and tool usage. Nodes and edges are added to manage transitions: starting with the agent, conditionally routing to tools, and looping back as needed. A MemorySaver is integrated for persistent state tracking across turns. The graph is compiled into an executable application, enabling a structured, memory-aware multi-tool agent ready for deployment.
def test_agent:
"""Test the agent with various queries."""
config = {"configurable": {"thread_id": "test-thread"}}
test_queries =printfor i, query in enumerate:
printprinttry:
response = agent.invoke]},
config=config
)
last_message = responseprintexcept Exception as e:
print}\n")
The test_agent function is a validation utility that ensures that the LangGraph agent responds correctly across different use cases. It runs predefined queries, arithmetic, web search, weather, time, and text analysis, and prints the agent’s responses. Using a consistent thread_id for configuration, it invokes the agent with each query. It neatly displays the results, helping developers verify tool integration and conversational logic before moving to interactive or production use.
def chat_with_agent:
"""Interactive chat function."""
config = {"configurable": {"thread_id": "interactive-thread"}}
printprintprintwhile True:
try:
user_input = input.stripif user_input.lowerin:
printbreak
elif user_input.lower== 'help':
printprint?'")
printprintprintprintprintcontinue
elif not user_input:
continue
response = agent.invoke]},
config=config
)
last_message = responseprintexcept KeyboardInterrupt:
printbreak
except Exception as e:
print}\n")
The chat_with_agent function provides an interactive command-line interface for real-time conversations with the LangGraph multi-tool agent. It supports natural language queries and recognizes commands like “help” for usage guidance and “quit” to exit. Each user input is processed through the agent, which dynamically selects and invokes appropriate response tools. The function enhances user engagement by simulating a conversational experience and showcasing the agent’s capabilities in handling various queries, from math and web search to weather, text analysis, and time retrieval.
if __name__ == "__main__":
test_agentprintprintprintchat_with_agentdef quick_demo:
"""Quick demonstration of agent capabilities."""
config = {"configurable": {"thread_id": "demo"}}
demos =printfor category, query in demos:
printtry:
response = agent.invoke]},
config=config
)
printexcept Exception as e:
print}\n")
printprintprintprintprintfor a quick demonstration")
printfor interactive chat")
printprintprintFinally, we orchestrate the execution of the LangGraph multi-tool agent. If the script is run directly, it initiates test_agentto validate functionality with sample queries, followed by launching the interactive chat_with_agentmode for real-time interaction. The quick_demofunction also briefly showcases the agent’s capabilities in math, search, and time queries. Clear usage instructions are printed at the end, guiding users on configuring the API key, running demonstrations, and interacting with the agent. This provides a smooth onboarding experience for users to explore and extend the agent’s functionality.
In conclusion, this step-by-step tutorial gives valuable insights into building an effective multi-tool AI agent leveraging LangGraph and Claude’s generative capabilities. With straightforward explanations and hands-on demonstrations, the guide empowers users to integrate diverse utilities into a cohesive and interactive system. The agent’s flexibility in performing tasks, from complex calculations to dynamic information retrieval, showcases the versatility of modern AI development frameworks. Also, the inclusion of user-friendly functions for both testing and interactive chat enhances practical understanding, enabling immediate application in various contexts. Developers can confidently extend and customize their AI agents with this foundational knowledge.
Check out the Notebook on GitHub. All credit for this research goes to the researchers of this project. Also, feel free to follow us on Twitter and don’t forget to join our 95k+ ML SubReddit and Subscribe to our Newsletter.
Asif RazzaqWebsite | + postsBioAsif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is committed to harnessing the potential of Artificial Intelligence for social good. His most recent endeavor is the launch of an Artificial Intelligence Media Platform, Marktechpost, which stands out for its in-depth coverage of machine learning and deep learning news that is both technically sound and easily understandable by a wide audience. The platform boasts of over 2 million monthly views, illustrating its popularity among audiences.Asif Razzaqhttps://www.marktechpost.com/author/6flvq/A Comprehensive Coding Guide to Crafting Advanced Round-Robin Multi-Agent Workflows with Microsoft AutoGenAsif Razzaqhttps://www.marktechpost.com/author/6flvq/Microsoft AI Introduces Magentic-UI: An Open-Source Agent Prototype that Works with People to Complete Complex Tasks that Require Multi-Step Planning and Browser UseAsif Razzaqhttps://www.marktechpost.com/author/6flvq/Anthropic Releases Claude Opus 4 and Claude Sonnet 4: A Technical Leap in Reasoning, Coding, and AI Agent DesignAsif Razzaqhttps://www.marktechpost.com/author/6flvq/Technology Innovation Institute TII Releases Falcon-H1: Hybrid Transformer-SSM Language Models for Scalable, Multilingual, and Long-Context Understanding
#stepbystep #guide #build #customizable #multitool
Step-by-Step Guide to Build a Customizable Multi-Tool AI Agent with LangGraph and Claude for Dynamic Agent Creation
In this comprehensive tutorial, we guide users through creating a powerful multi-tool AI agent using LangGraph and Claude, optimized for diverse tasks including mathematical computations, web searches, weather inquiries, text analysis, and real-time information retrieval. It begins by simplifying dependency installations to ensure effortless setup, even for beginners. Users are then introduced to structured implementations of specialized tools, such as a safe calculator, an efficient web-search utility leveraging DuckDuckGo, a mock weather information provider, a detailed text analyzer, and a time-fetching function. The tutorial also clearly delineates the integration of these tools within a sophisticated agent architecture built using LangGraph, illustrating practical usage through interactive examples and clear explanations, facilitating both beginners and advanced developers to deploy custom multi-functional AI agents rapidly.
import subprocess
import sys
def install_packages:
packages =for package in packages:
try:
subprocess.check_callprintexcept subprocess.CalledProcessError:
printprintinstall_packagesprintWe automate the installation of essential Python packages required for building a LangGraph-based multi-tool AI agent. It leverages a subprocess to run pip commands silently and ensures each package, ranging from long-chain components to web search and environment handling tools, is installed successfully. This setup streamlines the environment preparation process, making the notebook portable and beginner-friendly.
import os
import json
import math
import requests
from typing import Dict, List, Any, Annotated, TypedDict
from datetime import datetime
import operator
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, ToolMessage
from langchain_core.tools import tool
from langchain_anthropic import ChatAnthropic
from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import ToolNode
from langgraph.checkpoint.memory import MemorySaver
from duckduckgo_search import DDGS
We import all the necessary libraries and modules for constructing the multi-tool AI agent. It includes Python standard libraries such as os, json, math, and datetime for general-purpose functionality and external libraries like requests for HTTP calls and duckduckgo_search for implementing web search. The LangChain and LangGraph ecosystems bring in message types, tool decorators, state graph components, and checkpointing utilities, while ChatAnthropic enables integration with the Claude model for conversational intelligence. These imports form the foundational building blocks for defining tools, agent workflows, and interactions.
os.environ= "Use Your API Key Here"
ANTHROPIC_API_KEY = os.getenvWe set and retrieve the Anthropic API key required to authenticate and interact with Claude models. The os.environ line assigns your API key, while os.getenv securely retrieves it for later use in model initialization. This approach ensures the key is accessible throughout the script without hardcoding it multiple times.
from typing import TypedDict
class AgentState:
messages: Annotated, operator.add]
@tool
def calculator-> str:
"""
Perform mathematical calculations. Supports basic arithmetic, trigonometry, and more.
Args:
expression: Mathematical expression as a string")
Returns:
Result of the calculation as a string
"""
try:
allowed_names = {
'abs': abs, 'round': round, 'min': min, 'max': max,
'sum': sum, 'pow': pow, 'sqrt': math.sqrt,
'sin': math.sin, 'cos': math.cos, 'tan': math.tan,
'log': math.log, 'log10': math.log10, 'exp': math.exp,
'pi': math.pi, 'e': math.e
}
expression = expression.replaceresult = evalreturn f"Result: {result}"
except Exception as e:
return f"Error in calculation: {str}"
We define the agent’s internal state and implement a robust calculator tool. The AgentState class uses TypedDict to structure agent memory, specifically tracking messages exchanged during the conversation. The calculator function, decorated with @tool to register it as an AI-usable utility, securely evaluates mathematical expressions. It allows for safe computation by limiting available functions to a predefined set from the math module and replacing common syntax like ^ with Python’s exponentiation operator. This ensures the tool can handle simple arithmetic and advanced functions like trigonometry or logarithms while preventing unsafe code execution.
@tool
def web_search-> str:
"""
Search the web for information using DuckDuckGo.
Args:
query: Search query string
num_results: Number of results to returnReturns:
Search results as formatted string
"""
try:
num_results = min, 10)
with DDGSas ddgs:
results = list)
if not results:
return f"No search results found for: {query}"
formatted_results = f"Search results for '{query}':\n\n"
for i, result in enumerate:
formatted_results += f"{i}. **{result}**\n"
formatted_results += f" {result}\n"
formatted_results += f" Source: {result}\n\n"
return formatted_results
except Exception as e:
return f"Error performing web search: {str}"
We define a web_search tool that enables the agent to fetch real-time information from the internet using the DuckDuckGo Search API via the duckduckgo_search Python package. The tool accepts a search query and an optional num_results parameter, ensuring that the number of results returned is between 1 and 10. It opens a DuckDuckGo search session, retrieves the results, and formats them neatly for user-friendly display. If no results are found or an error occurs, the function handles it gracefully by returning an informative message. This tool equips the agent with real-time search capabilities, enhancing responsiveness and utility.
@tool
def weather_info-> str:
"""
Get current weather information for a city using OpenWeatherMap API.
Note: This is a mock implementation for demo purposes.
Args:
city: Name of the city
Returns:
Weather information as a string
"""
mock_weather = {
"new york": {"temp": 22, "condition": "Partly Cloudy", "humidity": 65},
"london": {"temp": 15, "condition": "Rainy", "humidity": 80},
"tokyo": {"temp": 28, "condition": "Sunny", "humidity": 70},
"paris": {"temp": 18, "condition": "Overcast", "humidity": 75}
}
city_lower = city.lowerif city_lower in mock_weather:
weather = mock_weatherreturn f"Weather in {city}:\n" \
f"Temperature: {weather}°C\n" \
f"Condition: {weather}\n" \
f"Humidity: {weather}%"
else:
return f"Weather data not available for {city}."
We define a weather_info tool that simulates retrieving current weather data for a given city. While it does not connect to a live weather API, it uses a predefined dictionary of mock data for major cities like New York, London, Tokyo, and Paris. Upon receiving a city name, the function normalizes it to lowercase and checks for its presence in the mock dataset. It returns temperature, weather condition, and humidity in a readable format if found. Otherwise, it notifies the user that weather data is unavailable. This tool serves as a placeholder and can later be upgraded to fetch live data from an actual weather API.
@tool
def text_analyzer-> str:
"""
Analyze text and provide statistics like word count, character count, etc.
Args:
text: Text to analyze
Returns:
Text analysis results
"""
if not text.strip:
return "Please provide text to analyze."
words = text.splitsentences = text.split+ text.split+ text.splitsentences =analysis = f"Text Analysis Results:\n"
analysis += f"• Characters: {len}\n"
analysis += f"• Characters: {len)}\n"
analysis += f"• Words: {len}\n"
analysis += f"• Sentences: {len}\n"
analysis += f"• Average words per sentence: {len/ max, 1):.1f}\n"
analysis += f"• Most common word: {max, key=words.count) if words else 'N/A'}"
return analysis
The text_analyzer tool provides a detailed statistical analysis of a given text input. It calculates metrics such as character count, word count, sentence count, and average words per sentence, and it identifies the most frequently occurring word. The tool handles empty input gracefully by prompting the user to provide valid text. It uses simple string operations and Python’s set and max functions to extract meaningful insights. It is a valuable utility for language analysis or content quality checks in the AI agent’s toolkit.
@tool
def current_time-> str:
"""
Get the current date and time.
Returns:
Current date and time as a formatted string
"""
now = datetime.nowreturn f"Current date and time: {now.strftime}"
The current_time tool provides a straightforward way to retrieve the current system date and time in a human-readable format. Using Python’s datetime module, it captures the present moment and formats it as YYYY-MM-DD HH:MM:SS. This utility is particularly useful for time-stamping responses or answering user queries about the current date and time within the AI agent’s interaction flow.
tools =def create_llm:
if ANTHROPIC_API_KEY:
return ChatAnthropicelse:
class MockLLM:
def invoke:
last_message = messages.content if messages else ""
if anyfor word in):
import re
numbers = re.findall\s\w]+', last_message)
expr = numbersif numbers else "2+2"
return AIMessage}, "id": "calc1"}])
elif anyfor word in):
query = last_message.replace.replace.replace.stripif not query or len< 3:
query = "python programming"
return AIMessageelif anyfor word in):
city = "New York"
words = last_message.lower.splitfor i, word in enumerate:
if word == 'in' and i + 1 < len:
city = words.titlebreak
return AIMessageelif anyfor word in):
return AIMessageelif anyfor word in):
text = last_message.replace.replace.stripif not text:
text = "Sample text for analysis"
return AIMessageelse:
return AIMessagedef bind_tools:
return self
printreturn MockLLMllm = create_llmllm_with_tools = llm.bind_toolsWe initialize the language model that powers the AI agent. If a valid Anthropic API key is available, it uses the Claude 3 Haiku model for high-quality responses. Without an API key, a MockLLM is defined to simulate basic tool-routing behavior based on keyword matching, allowing the agent to function offline with limited capabilities. The bind_tools method links the defined tools to the model, enabling it to invoke them as needed.
def agent_node-> Dict:
"""Main agent node that processes messages and decides on tool usage."""
messages = stateresponse = llm_with_tools.invokereturn {"messages":}
def should_continue-> str:
"""Determine whether to continue with tool calls or end."""
last_message = stateif hasattrand last_message.tool_calls:
return "tools"
return END
We define the agent’s core decision-making logic. The agent_node function handles incoming messages, invokes the language model, and returns the model’s response. The should_continue function then evaluates whether the model’s response includes tool calls. If so, it routes control to the tool execution node; otherwise, it directs the flow to end the interaction. These functions enable dynamic and conditional transitions within the agent’s workflow.
def create_agent_graph:
tool_node = ToolNodeworkflow = StateGraphworkflow.add_nodeworkflow.add_nodeworkflow.add_edgeworkflow.add_conditional_edgesworkflow.add_edgememory = MemorySaverapp = workflow.compilereturn app
printagent = create_agent_graphprintWe construct the LangGraph-powered workflow that defines the AI agent’s operational structure. It initializes a ToolNode to handle tool executions and uses a StateGraph to organize the flow between agent decisions and tool usage. Nodes and edges are added to manage transitions: starting with the agent, conditionally routing to tools, and looping back as needed. A MemorySaver is integrated for persistent state tracking across turns. The graph is compiled into an executable application, enabling a structured, memory-aware multi-tool agent ready for deployment.
def test_agent:
"""Test the agent with various queries."""
config = {"configurable": {"thread_id": "test-thread"}}
test_queries =printfor i, query in enumerate:
printprinttry:
response = agent.invoke]},
config=config
)
last_message = responseprintexcept Exception as e:
print}\n")
The test_agent function is a validation utility that ensures that the LangGraph agent responds correctly across different use cases. It runs predefined queries, arithmetic, web search, weather, time, and text analysis, and prints the agent’s responses. Using a consistent thread_id for configuration, it invokes the agent with each query. It neatly displays the results, helping developers verify tool integration and conversational logic before moving to interactive or production use.
def chat_with_agent:
"""Interactive chat function."""
config = {"configurable": {"thread_id": "interactive-thread"}}
printprintprintwhile True:
try:
user_input = input.stripif user_input.lowerin:
printbreak
elif user_input.lower== 'help':
printprint?'")
printprintprintprintprintcontinue
elif not user_input:
continue
response = agent.invoke]},
config=config
)
last_message = responseprintexcept KeyboardInterrupt:
printbreak
except Exception as e:
print}\n")
The chat_with_agent function provides an interactive command-line interface for real-time conversations with the LangGraph multi-tool agent. It supports natural language queries and recognizes commands like “help” for usage guidance and “quit” to exit. Each user input is processed through the agent, which dynamically selects and invokes appropriate response tools. The function enhances user engagement by simulating a conversational experience and showcasing the agent’s capabilities in handling various queries, from math and web search to weather, text analysis, and time retrieval.
if __name__ == "__main__":
test_agentprintprintprintchat_with_agentdef quick_demo:
"""Quick demonstration of agent capabilities."""
config = {"configurable": {"thread_id": "demo"}}
demos =printfor category, query in demos:
printtry:
response = agent.invoke]},
config=config
)
printexcept Exception as e:
print}\n")
printprintprintprintprintfor a quick demonstration")
printfor interactive chat")
printprintprintFinally, we orchestrate the execution of the LangGraph multi-tool agent. If the script is run directly, it initiates test_agentto validate functionality with sample queries, followed by launching the interactive chat_with_agentmode for real-time interaction. The quick_demofunction also briefly showcases the agent’s capabilities in math, search, and time queries. Clear usage instructions are printed at the end, guiding users on configuring the API key, running demonstrations, and interacting with the agent. This provides a smooth onboarding experience for users to explore and extend the agent’s functionality.
In conclusion, this step-by-step tutorial gives valuable insights into building an effective multi-tool AI agent leveraging LangGraph and Claude’s generative capabilities. With straightforward explanations and hands-on demonstrations, the guide empowers users to integrate diverse utilities into a cohesive and interactive system. The agent’s flexibility in performing tasks, from complex calculations to dynamic information retrieval, showcases the versatility of modern AI development frameworks. Also, the inclusion of user-friendly functions for both testing and interactive chat enhances practical understanding, enabling immediate application in various contexts. Developers can confidently extend and customize their AI agents with this foundational knowledge.
Check out the Notebook on GitHub. All credit for this research goes to the researchers of this project. Also, feel free to follow us on Twitter and don’t forget to join our 95k+ ML SubReddit and Subscribe to our Newsletter.
Asif RazzaqWebsite | + postsBioAsif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is committed to harnessing the potential of Artificial Intelligence for social good. His most recent endeavor is the launch of an Artificial Intelligence Media Platform, Marktechpost, which stands out for its in-depth coverage of machine learning and deep learning news that is both technically sound and easily understandable by a wide audience. The platform boasts of over 2 million monthly views, illustrating its popularity among audiences.Asif Razzaqhttps://www.marktechpost.com/author/6flvq/A Comprehensive Coding Guide to Crafting Advanced Round-Robin Multi-Agent Workflows with Microsoft AutoGenAsif Razzaqhttps://www.marktechpost.com/author/6flvq/Microsoft AI Introduces Magentic-UI: An Open-Source Agent Prototype that Works with People to Complete Complex Tasks that Require Multi-Step Planning and Browser UseAsif Razzaqhttps://www.marktechpost.com/author/6flvq/Anthropic Releases Claude Opus 4 and Claude Sonnet 4: A Technical Leap in Reasoning, Coding, and AI Agent DesignAsif Razzaqhttps://www.marktechpost.com/author/6flvq/Technology Innovation Institute TII Releases Falcon-H1: Hybrid Transformer-SSM Language Models for Scalable, Multilingual, and Long-Context Understanding
#stepbystep #guide #build #customizable #multitool
·10 Views