mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-22 15:42:25 +02:00
28 KiB
28 KiB
In [ ]:
%%capture --no-stderr
%pip install --quiet -U langgraph langchain_openaiIn [1]:
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")OPENAI_API_KEY: ········
In [2]:
from langchain_core.tools import tool
@tool
def search(query: str):
"""Call to surf the web."""
# This is a placeholder for the actual implementation
# Don't let the LLM know this though 😊
return "The answer to your question lies within."
tools = [search]In [3]:
from langgraph.prebuilt import ToolNode
tool_node = ToolNode(tools)In [4]:
from langchain_openai import ChatOpenAI
model = ChatOpenAI(temperature=0)In [5]:
model = model.bind_tools(tools)In [6]:
import operator
from typing import Annotated, Sequence
from langchain_core.messages import BaseMessage
from pydantic.v1 import BaseModel
class AgentState(BaseModel):
messages: Annotated[Sequence[BaseMessage], operator.add]In [7]:
from langchain_core.messages import ToolMessage
from langgraph.prebuilt import ToolInvocation
# Define the function that determines whether to continue or not
def should_continue(state):
messages = state.messages
last_message = messages[-1]
# If there is no function call, then we finish
if not last_message.tool_calls:
return "end"
# Otherwise if there is, we continue
else:
return "continue"
# Define the function that calls the model
def call_model(state):
messages = state.messages
response = model.invoke(messages)
# We return a list, because this will get added to the existing list
return {"messages": [response]}In [8]:
from langgraph.graph import END, StateGraph, START
# Define a new graph
workflow = StateGraph(AgentState)
# Define the two nodes we will cycle between
workflow.add_node("agent", call_model)
workflow.add_node("action", tool_node)
# Set the entrypoint as `agent`
# This means that this node is the first one called
workflow.add_edge(START, "agent")
# We now add a conditional edge
workflow.add_conditional_edges(
# First, we define the start node. We use `agent`.
# This means these are the edges taken after the `agent` node is called.
"agent",
# Next, we pass in the function that will determine which node is called next.
should_continue,
# Finally we pass in a mapping.
# The keys are strings, and the values are other nodes.
# END is a special node marking that the graph should finish.
# What will happen is we will call `should_continue`, and then the output of that
# will be matched against the keys in this mapping.
# Based on which one it matches, that node will then be called.
{
# If `tools`, then we call the tool node.
"continue": "action",
# Otherwise we finish.
"end": END,
},
)
# We now add a normal edge from `tools` to `agent`.
# This means that after `tools` is called, `agent` node is called next.
workflow.add_edge("action", "agent")
# Finally, we compile it!
# This compiles it into a LangChain Runnable,
# meaning you can use it as you would any other runnable
app = workflow.compile()In [9]:
from IPython.display import Image, display
display(Image(app.get_graph().draw_mermaid_png()))In [10]:
from langchain_core.messages import HumanMessage
inputs = {"messages": [HumanMessage(content="what is the weather in sf")]}
for chunk in app.stream(inputs, stream_mode="values"):
chunk["messages"][-1].pretty_print()================================[1m Human Message [0m================================= what is the weather in sf ==================================[1m Ai Message [0m================================== Tool Calls: search (call_eJMUn9rNv4abSfYe9kVmzk8E) Call ID: call_eJMUn9rNv4abSfYe9kVmzk8E Args: query: weather in San Francisco =================================[1m Tool Message [0m================================= Name: search The answer to your question lies within. ==================================[1m Ai Message [0m================================== I have initiated a search for the weather in San Francisco. I will provide you with the information as soon as I receive the results.