Graphs Demo
Open the empty graphs-demo.ipynb notebook in the Starter folder. If you haven’t already, install LangGraph by running:
!pip install langgraph
Since you’re running the command directly in JupyterLab here, you need the exclamation mark at the beginning. You can leave that off if you’re in a terminal. Press Shift+Enter. You can see that LangGraph is already installed on this machine.
Define two functions that you’ll use as nodes. Name the first function greet. It’ll say “Hello” to whatever the input is. Then, name the second function enthusiastic. It’ll add an exclamation point to the input.
def greet(name):
return f"Hello, {name}"
def enthusiastic(message):
return f"{message}!"
Now, import langgraph and create a graph:
from langgraph.graph import Graph
graph = Graph()
Use the functions you defined earlier to create two nodes. Use the add_node method to add them to the graph. The first parameter is the node name, which in this case is greeting. It’s a string, so wrap it with quotation marks. The second parameter is the function, so write greet here.
For the second node, the node and the function have the same name. The only difference is the use of quotation marks for the node name.
graph.add_node("greeting", greet)
graph.add_node("enthusiastic", enthusiastic)
Next, connect those two nodes with an edge:
graph.add_edge("greeting", "enthusiastic")
Since greeting is first, it’ll run before enthusiastic when you execute the graph. The output of greeting is the input to enthusiastic.
To finish the graph structure, you must set the START and END nodes. You’ve only defined two nodes in the graph, so that’ll be easy:
from langgraph.graph import START, END
graph.add_edge(START, "greeting")
graph.add_edge("enthusiastic", END)
There are shortcut methods to do the same thing, so try them out. Replace the lines you just wrote with:
graph.set_entry_point("greeting")
graph.set_finish_point("enthusiastic")
A __start__ node is already defined from when you added the START edge, so you must recreate the graph for your new syntax to work. Now, compile the graph:
app = graph.compile()
Finally, run the graph using the invoke method. The input is “World”.
app.invoke("World")
And you see the result: “Hello, World!” with an exclamation point.