1. Building graphs for chatbots
Great job! Now that we're familiar with using LangChain's pre-built agents,
2. Chatbots with LangGraph
we'll learn how to create custom chatbots using LangGraph. We'll first learn about graph and agent states that manage chatbot workflows, before building chatbots using nodes and edges.
3. Graphs and agent states
In LangGraph, the graph state organizes the agent's order of tasks, such as tool usage and LLM calls, into a workflow. The graph uses an agent state to track the agent's progress as text to help determine when a task is complete.
4. Building an agent with LangGraph
Let's start by building an education chatbot that uses an LLM to answer questions.
5. Nodes and edges
We only need three nodes and two edges to get started. In LangGraph, nodes represent functions, like generating a response or calling a tool, while edges define the connections between these nodes. Here, an edge connects
6. Nodes and edges
the Start of the workflow to the Chatbot node, and another edge connects the
7. Nodes and edges
Chatbot node to the End of the workflow.
8. Nodes and edges
The START and END nodes to define the start and end of the workflow will be directly imported from LangGraph. Let's build the full graph!
9. Building graph and agent states
We'll need the following modules. From typing and typing_extensions, the Annotated and TypedDict modules will help organize the chatbot's text data. Next, we'll require the StateGraph, START, END, and add_messages modules from LangGraph to set up our chatbot's workflow and add text messages. ChatOpenAI from langchain_openai will also be imported to help us set up our LLM.
10. Building graph and agent states
To get started, we'll set OpenAI as our llm. Then, we'll create an agent state called State that accepts TypedDict to structure messages. We'll define messages as a list that will store all text interactions with the chatbot. The Annotated type, combined with add_messages, ensures that new messages are added to this list with metadata. Next, we'll initialize a StateGraph() called graph_builder and pass in our State structure. The graph builder will organize the nodes and edges in the chatbot's workflow.
11. Adding nodes and edges
Let's now define the main function node called "chatbot" that accepts the State class. Using the llm.invoke() method, it'll use the "messages" content in the state dictionary to generate a response based on the conversation so far. This chatbot node can then be added to the graph_builder using the .add_node() method, coupled with the label "chatbot".
12. Adding nodes and edges
Next, we'll connect the START node to the chatbot node to begin the conversation, and then connect the chatbot node to the END node to finish it. Now that the graph builder is ready, we can compile the graph as an application using the .compile() method. You're now ready to
13. Let's practice!
build your first graph!