Add a tool to a graph
You've got your Wikipedia tool ready to go. Now it's time to incorporate it into your chatbot's graph workflow! You'll modify the nodes and edges in the graph workflow to incorporate the tool as an additional node. You'll set up the graph so that the chatbot can use the tool only when needed depending on the user's query. To manage your tool node and its associated edges, the following modules have been imported for you. The wikipedia_tool you built is also available in your environment. Once the graph build is complete, your graph will be visualized for you as a LangGraph diagram.
from langgraph.prebuilt import ToolNode, tools_condition
This exercise is part of the course
Designing Agentic Systems with LangChain
Exercise instructions
- Use
.add_node()to add the"chatbot"node to the graph, linking it to thechatbotfunction. - Create a
ToolNode()withwikipedia_toolastoolsand use.add_node()to add it to the graph as"tools". - Apply
.add_conditional_edges()to route from"chatbot"based on thetools_condition. - Use
.add_edge()to connect"tools"back to"chatbot",STARTto"chatbot", and"chatbot"toENDto complete the workflow.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Add chatbot node to the graph
graph_builder.____("____", ____)
# Create a ToolNode to handle tool calls and add it to the graph
tool_node = ____(tools=[____])
graph_builder.____("tools", ____)
# Set up a condition to direct from chatbot to tool or END node
graph_builder.____("____", ____)
# Connect tools back to chatbot and connect START and END nodes
graph_builder.add_edge("____", "____")
graph_builder.add_edge(____, "chatbot")
graph_builder.add_edge("chatbot", ____)
graph = graph_builder.compile()
try:
display(Image(graph.get_graph().draw_mermaid_png()))
except Exception:
print("Plot generation failed... falling back to cached asset.")
display_fallback()