first LangGraph Let's make a simple chatbot using. This chatbot will respond directly to user messages. Although simple, LangGraph It will explain the key concepts you build with. At the end of this section, you will be building a basic chatbot.
StateGraph Start by generating. StateGraph The object defines the structure of the chatbot as a "State Machine".
nodes Chattbot can call by adding llm And functions, edges Add to specify how the bot should switch between these functions.
# Configuration file for managing API keys as environment variablesfrom dotenv import load_dotenv# Load API key informationload_dotenv()
True
# LangSmith set up tracking. https://smith.langchain.com# !pip install -qU langchain-teddynotefrom langchain_teddynote import logging# Enter a project name.logging.langsmith("CH17-LangGraph")
Nodes represent units of work, usually regular Python Function.
STEP 3. Graph definition, add node
Reference
chatbot Node function is currently State Input as input and updated under the key "messages" messages Returns a dictionary (TypedDict) containing a list.
State of add_messages The function adds a llm response message to a message that is already in state.
STEP 4. Add graph edge
next, START Add a branch. START Whenever the graph is executed Where to start working is.
Likewise, END Set the point. This represents the end (end point) of the graph flow.
STEP 5. Graph compilation (compile)
Finally, you should be able to run the graph. For this, in the graph builder" compile() Call ". This can be called from the state" CompiledGraph "Is created.
STEP 6. Graph visualization
Now let's visualize the graph.
STEP 7. Graph execution
Let's run the chatbot now!
character! This was the most basic chatbot building.
Below is the full code that organized the previous process.
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
class State(TypedDict):
# Message definition (list type, add messages using add_messages function)
messages: Annotated[list, add_messages]
from langchain_openai import ChatOpenAI
# LLM definition
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# Defining a chatbot function
def chatbot(state: State):
# Calling and returning messages
return {"messages": [llm.invoke(state["messages"])]}
# Create a graph
graph_builder = StateGraph(State)
# Add a node by taking a node name, function, or callable object as arguments.
graph_builder.add_node("chatbot", chatbot)
# Add an edge from the start node to the chatbot node
graph_builder.add_edge(START, "chatbot")
# Add an edge to the graph
graph_builder.add_edge("chatbot", END)
# Compile the graph
graph = graph_builder.compile()
from langchain_teddynote.graphs import visualize_graph
# Graph visualization
visualize_graph(graph)
question = "Recommend me the top 10 famous restaurants in Seoul"
# Graph Event Streaming
for event in graph.stream({"messages": [("user", question)]}):
# Output event values
for value in event.values():
print("Assistant:", value["messages"][-1].content)
Assistant: There are many different restaurants in Seoul, so it is not easy to choose, but the following recommends the famous restaurant TOP 10 in Seoul. Each restaurant has its own charm, so please refer!
One. **Square market ** -As a traditional market, you can enjoy a variety of street foods such as glutton, narcotic rice, and rice cake.
2. **Bulmok Cafe Street** -A place with lots of pretty cafes and delicious desserts, especially the raw fruit ice water of'Cafe de Paris'.
3. **Itaiwon Antic Furniture Street** -A place where you can enjoy a variety of international cuisine, especially'Burito' and'Thai Food' are popular.
4. **Nominalists** -A restaurant famous for kalodu and dumplings, always waiting for many people to line up.
5. ** Trident Handmade **-A place offering traditional handmade and a variety of Chinese meals, you can enjoy your meal in a cozy atmosphere.
6. **Shrine Street Road ** -A place with a variety of trendy cafes and restaurants, especially the'Broch' menu is popular.
7. **Kyong Tongin Market**-A market where you can taste a variety of traditional foods, especially'Kimbab' and'Tok' are famous.
8. **Red ** -A region with a wide variety of restaurants and cafes,'burger' and'fusion Korean' are popular.
9. **Overview Rodeo Street**-Luxury restaurants and cafés, especially'Sushi' and'French Restaurant' are famous.
10. ** Yeouido Han Gang Park**-A place where you can enjoy picnics and taste a variety of street food, especially'chicken' and'beer' is popular.
Each region has a distinctive food and atmosphere, so I recommend you visit!
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langchain_openai import ChatOpenAI
from langchain_teddynote.graphs import visualize_graph
###### STEP 1. State Definition ######
class State(TypedDict):
# Message definition (list type, add messages using add_messages function)
messages: Annotated[list, add_messages]
###### STEP 2. Node Definition ######
# LLM definition
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# Defining a chatbot function
def chatbot(state: State):
# Calling and returning messages
return {"messages": [llm.invoke(state["messages"])]}
###### STEP 3. Define a graph, add nodes ######
# 그래프 생성
graph_builder = StateGraph(State)
# Add a node by taking a node name, function, or callable object as arguments.
graph_builder.add_node("chatbot", chatbot)
###### STEP 4. Add a graph edge ######
# Add an edge from the start node to the chatbot node
graph_builder.add_edge(START, "chatbot")
# Add an edge to the graph
graph_builder.add_edge("chatbot", END)
###### STEP 5. Compile the graph ######
# Compile the graph
graph = graph_builder.compile()
###### STEP 6. Graph visualization ######
# Graph visualization
visualize_graph(graph)
###### STEP 7. Running the graph ######
question = "Recommend me the top 10 famous restaurants in Seoul"
# Graph Event Streaming
for event in graph.stream({"messages": [("user", question)]}):
# Output event values
for value in event.values():
print(value["messages"][-1].content)
There are many different restaurants in Seoul, making it difficult to choose, but the following recommends the famous restaurant TOP 10 in Seoul. Each restaurant has a unique menu and atmosphere, so please refer!
One. **Square market ** -As a traditional market, you can enjoy a variety of street foods such as glutton, narcotic rice, and rice cake.
2. **Etagwon Gucci **- Famous for his buoyancy, this place is loved by its fuzzy sheep and deep taste.
3. **Motorist** -A place famous for kalodu and dumplings, a popular restaurant that many people always wait in line.
4. ** Trident Handmade **-A cozy restaurant where you can enjoy handmade and traditional Chinese meals.
5. ** South and South Korean Meaty Makchang**-A place that serves fresh barracks and a variety of meat dishes, recommended for meat lovers.
6. ** Hongdong Donburi**- Japanese cover shop, you can enjoy delicious cover with a variety of toppings.
7. ** Cafe de Paris on the street of the estuary rodeo **-a cafe famous for desserts and brunch, offering a variety of menus with pretty interiors.
8. ** Shrine's crossroads sushi**-A place where you can taste high-end sushi, featuring fresh ingredients and hearty service.
9. **Kyong-ro's herbal medicine **-A place that provides healthy tricycle, which is popular as a nostalgic diet.
10. ** Cafe in Buamdong Mas**- A cafe famous for brunch and desserts, you can have a relaxing time with pretty scenery.
In addition to this, there are many restaurants in Seoul, so look for new places every time you visit!