mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-25 17:12:26 +02:00
- control selection of relevant runs (needs langsmith release) - see output of conditional edge function - fix issue with conditional entry point not getting full state values as input
26 KiB
26 KiB
In [1]:
!pip install --quiet -U langchain langchain_openai tavily-python[1m[[0m[34;49mnotice[0m[1;39;49m][0m[39;49m A new release of pip is available: [0m[31;49m23.3.1[0m[39;49m -> [0m[32;49m23.3.2[0m [1m[[0m[34;49mnotice[0m[1;39;49m][0m[39;49m To update, run: [0m[32;49mpip install --upgrade pip[0m
In [2]:
import os
import getpass
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
os.environ["TAVILY_API_KEY"] = getpass.getpass("Tavily API Key:")OpenAI API Key: ········ Tavily API Key: ········
In [ ]:
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = getpass.getpass("LangSmith API Key:")In [1]:
from langchain_community.tools.tavily_search import TavilySearchResults
tools = [TavilySearchResults(max_results=1)]In [2]:
from langgraph.prebuilt import ToolExecutor
tool_executor = ToolExecutor(tools)In [3]:
from langchain_openai import ChatOpenAI
model = ChatOpenAI(temperature=0)In [4]:
from langchain_core.utils.function_calling import convert_to_openai_function
functions = [convert_to_openai_function(t) for t in tools]
model = model.bind_functions(functions)In [5]:
from langgraph.prebuilt import ToolInvocation
import json
from langchain_core.messages import FunctionMessage
# Define the function that determines whether to continue or not
def should_continue(messages):
last_message = messages[-1]
# If there is no function call, then we finish
if "function_call" not in last_message.additional_kwargs:
return "end"
# Otherwise if there is, we continue
else:
return "continue"
# Define the function to execute tools
def call_tool(messages):
# Based on the continue condition
# we know the last message involves a function call
last_message = messages[-1]
# We construct an ToolInvocation from the function_call
action = ToolInvocation(
tool=last_message.additional_kwargs["function_call"]["name"],
tool_input=json.loads(
last_message.additional_kwargs["function_call"]["arguments"]
),
)
# We call the tool_executor and get back a response
response = tool_executor.invoke(action)
# We use the response to create a FunctionMessage
function_message = FunctionMessage(content=str(response), name=action.tool)
# We return a list, because this will get added to the existing list
return function_messageIn [6]:
from langgraph.graph import MessageGraph, END
# Define a new graph
workflow = MessageGraph()
# Define the two nodes we will cycle between
workflow.add_node("agent", model)
workflow.add_node("action", call_tool)
# Set the entrypoint as `agent`
# This means that this node is the first one called
workflow.set_entry_point("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")In [7]:
from langgraph.checkpoint.sqlite import SqliteSaver
memory = SqliteSaver.from_conn_string(":memory:")In [8]:
# 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(checkpointer=memory, interrupt_before=["action"])In [9]:
from langchain_core.messages import HumanMessage
thread = {"configurable": {"thread_id": '3'}}
inputs = HumanMessage(content="hi! I'm bob")
for event in app.stream(inputs, thread):
for v in event.values():
print(v)content='Hello Bob! How can I assist you today?' id='87e8b88a-b28e-4517-a62f-7b9baebd3329'
In [10]:
app.get_state(thread)Out [10]:
StateSnapshot(values=[HumanMessage(content="hi! I'm bob", id='5a84a602-37d9-4903-9c3c-d0f892238580'), AIMessage(content='Hello Bob! How can I assist you today?', id='87e8b88a-b28e-4517-a62f-7b9baebd3329')], next=(), config={'configurable': {'thread_id': '3', 'thread_ts': '2024-04-02T17:13:46.250299+00:00'}}, parent_config=None)In [11]:
inputs = HumanMessage(content="what is the weather in sf currently")
for event in app.stream(inputs, thread):
for v in event.values():
print(v)content='' additional_kwargs={'function_call': {'arguments': '{"query":"current weather in San Francisco"}', 'name': 'tavily_search_results_json'}} id='8e6ae8d5-a258-47aa-9e2c-1ca3e78add90'
In [12]:
current_values = app.get_state(thread)
current_values.values[-1].additional_kwargsOut [12]:
{'function_call': {'arguments': '{"query":"current weather in San Francisco"}',
'name': 'tavily_search_results_json'}}In [13]:
current_values.values[-1].additional_kwargs = {'function_call': {'arguments': '{"query":"weather in San Francisco today"}',
'name': 'tavily_search_results_json'}}In [14]:
app.update_state(thread, current_values.values)Out [14]:
{'configurable': {'thread_id': '3',
'thread_ts': '2024-04-02T16:58:19.692203+00:00'}}In [15]:
app.get_state(thread)Out [15]:
StateSnapshot(values=[HumanMessage(content="hi! I'm bob", id='1493cdf4-b7b5-46c9-a3e7-ad3b661fcb92'), AIMessage(content='Hello Bob! How can I assist you today?', id='028e0185-2ca4-4c1d-8660-93c17b839275'), HumanMessage(content='what is the weather in sf currently', id='76d6a5ff-d400-4edb-a264-b584107e2231'), AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"weather in San Francisco today"}', 'name': 'tavily_search_results_json'}}, id='b143d5f6-5216-4a48-b76a-68b2f3eb6ff2')], next=('action',), config={'configurable': {'thread_id': '3', 'thread_ts': '2024-04-02T16:58:19.692203+00:00'}}, parent_config=None)In [16]:
for event in app.stream(None, thread):
for v in event.values():
print(v)content="[{'url': 'https://forecast.weather.gov/zipcity.php?inputstring=San francisco,CA', 'content': 'Detailed Forecast. Today. Mostly sunny, with a high near 62. Light and variable wind becoming west southwest 5 to 8 mph in the afternoon. Tonight. Mostly clear, with a low around 49. West wind 5 to 8 mph becoming north northwest after midnight. Monday. Sunny, with a high near 67.'}]" name='tavily_search_results_json' id='9b33eb74-b079-4615-9c8a-9f41b4e176ba'
content='The weather in San Francisco today is mostly sunny with a high near 62 degrees Fahrenheit. The wind is light and variable, becoming west-southwest at 5 to 8 mph in the afternoon. Tonight, it will be mostly clear with a low around 49 degrees Fahrenheit. Tomorrow is expected to be sunny with a high near 67 degrees Fahrenheit.' id='18ff870d-5d5d-40d9-9eca-72e345749b51'
In [17]:
for state in app.get_state_history(thread):
print(state)
print('--')
if len(state.values) == 4:
to_replay = stateStateSnapshot(values=[HumanMessage(content="hi! I'm bob", id='1493cdf4-b7b5-46c9-a3e7-ad3b661fcb92'), AIMessage(content='Hello Bob! How can I assist you today?', id='028e0185-2ca4-4c1d-8660-93c17b839275'), HumanMessage(content='what is the weather in sf currently', id='76d6a5ff-d400-4edb-a264-b584107e2231'), AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"weather in San Francisco today"}', 'name': 'tavily_search_results_json'}}, id='b143d5f6-5216-4a48-b76a-68b2f3eb6ff2'), FunctionMessage(content="[{'url': 'https://forecast.weather.gov/zipcity.php?inputstring=San francisco,CA', 'content': 'Detailed Forecast. Today. Mostly sunny, with a high near 62. Light and variable wind becoming west southwest 5 to 8 mph in the afternoon. Tonight. Mostly clear, with a low around 49. West wind 5 to 8 mph becoming north northwest after midnight. Monday. Sunny, with a high near 67.'}]", name='tavily_search_results_json', id='9b33eb74-b079-4615-9c8a-9f41b4e176ba'), AIMessage(content='The weather in San Francisco today is mostly sunny with a high near 62 degrees Fahrenheit. The wind is light and variable, becoming west-southwest at 5 to 8 mph in the afternoon. Tonight, it will be mostly clear with a low around 49 degrees Fahrenheit. Tomorrow is expected to be sunny with a high near 67 degrees Fahrenheit.', id='18ff870d-5d5d-40d9-9eca-72e345749b51')], next=(), config={'configurable': {'thread_id': '3', 'thread_ts': '2024-04-02T16:58:23.633015+00:00'}}, parent_config=None)
--
StateSnapshot(values=[HumanMessage(content="hi! I'm bob", id='1493cdf4-b7b5-46c9-a3e7-ad3b661fcb92'), AIMessage(content='Hello Bob! How can I assist you today?', id='028e0185-2ca4-4c1d-8660-93c17b839275'), HumanMessage(content='what is the weather in sf currently', id='76d6a5ff-d400-4edb-a264-b584107e2231'), AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"weather in San Francisco today"}', 'name': 'tavily_search_results_json'}}, id='b143d5f6-5216-4a48-b76a-68b2f3eb6ff2')], next=('action',), config={'configurable': {'thread_id': '3', 'thread_ts': '2024-04-02T16:58:19.692203+00:00'}}, parent_config=None)
--
StateSnapshot(values=[HumanMessage(content="hi! I'm bob", id='1493cdf4-b7b5-46c9-a3e7-ad3b661fcb92'), AIMessage(content='Hello Bob! How can I assist you today?', id='028e0185-2ca4-4c1d-8660-93c17b839275'), HumanMessage(content='what is the weather in sf currently', id='76d6a5ff-d400-4edb-a264-b584107e2231'), AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"current weather in San Francisco"}', 'name': 'tavily_search_results_json'}}, id='b143d5f6-5216-4a48-b76a-68b2f3eb6ff2')], next=('action',), config={'configurable': {'thread_id': '3', 'thread_ts': '2024-04-02T16:58:18.058645+00:00'}}, parent_config=None)
--
StateSnapshot(values=[HumanMessage(content="hi! I'm bob", id='1493cdf4-b7b5-46c9-a3e7-ad3b661fcb92'), AIMessage(content='Hello Bob! How can I assist you today?', id='028e0185-2ca4-4c1d-8660-93c17b839275')], next=(), config={'configurable': {'thread_id': '3', 'thread_ts': '2024-04-02T16:58:16.834223+00:00'}}, parent_config=None)
--
In [18]:
to_replayOut [18]:
StateSnapshot(values=[HumanMessage(content="hi! I'm bob", id='1493cdf4-b7b5-46c9-a3e7-ad3b661fcb92'), AIMessage(content='Hello Bob! How can I assist you today?', id='028e0185-2ca4-4c1d-8660-93c17b839275'), HumanMessage(content='what is the weather in sf currently', id='76d6a5ff-d400-4edb-a264-b584107e2231'), AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"current weather in San Francisco"}', 'name': 'tavily_search_results_json'}}, id='b143d5f6-5216-4a48-b76a-68b2f3eb6ff2')], next=('action',), config={'configurable': {'thread_id': '3', 'thread_ts': '2024-04-02T16:58:18.058645+00:00'}}, parent_config=None)In [19]:
for event in app.stream(None, to_replay.config):
for v in event.values():
print(v)content="[{'url': 'https://www.accuweather.com/en/us/san-francisco/94103/current-weather/347629', 'content': 'Get the latest weather conditions and forecast for San Francisco, CA. See the temperature, humidity, wind, pressure, cloud cover, and alerts for the current hour and the next few days.'}]" name='tavily_search_results_json' id='73ab98d6-d7cf-4812-9572-f58698394c9f'
content='You can check the current weather conditions and forecast for San Francisco, CA on [AccuWeather](https://www.accuweather.com/en/us/san-francisco/94103/current-weather/347629). This will provide you with information on temperature, humidity, wind, pressure, cloud cover, and alerts for the current hour and the next few days.' id='a54c0531-1683-4d61-87b6-ee7f66971c25'
In [ ]: