mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-17 21:25:46 +02:00
27 KiB
27 KiB
In [1]:
%%capture --no-stderr
%pip install --quiet -U langgraph langchain langchain_openai tavily-pythonIn [ ]:
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
os.environ["TAVILY_API_KEY"] = getpass.getpass("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 langchain_openai import ChatOpenAI
model = ChatOpenAI(temperature=0)In [3]:
model = model.bind_tools(tools)In [4]:
import operator
from typing import Annotated, Sequence, TypedDict
from langchain_core.messages import BaseMessage
class AgentState(TypedDict):
messages: Annotated[Sequence[BaseMessage], operator.add]In [10]:
from langgraph.prebuilt import ToolNode
# Define the function that determines whether to continue or not
def should_continue(state):
messages = state["messages"]
last_message = messages[-1]
# If there are no tool calls, 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]}
# Define the function to execute tools
tool_node = ToolNode(tools)In [6]:
from langgraph.graph import END, StateGraph
# 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.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")
# 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 [7]:
from langchain_core.messages import HumanMessage
inputs = {"messages": [HumanMessage(content="what is the weather in sf")]}
app.invoke(inputs)Out [7]:
{'messages': [HumanMessage(content='what is the weather in sf'),
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_HGOi2cCxKKVWnz8WMuOCWnZx', 'function': {'arguments': '{"query":"weather in San Francisco"}', 'name': 'tavily_search_results_json'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 21, 'prompt_tokens': 87, 'total_tokens': 108}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_b28b39ffa8', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-df061477-a815-432b-a69f-9951d4c6edfa-0', tool_calls=[{'name': 'tavily_search_results_json', 'args': {'query': 'weather in San Francisco'}, 'id': 'call_HGOi2cCxKKVWnz8WMuOCWnZx'}]),
ToolMessage(content='[{"url": "https://www.weatherapi.com/", "content": "{\'location\': {\'name\': \'San Francisco\', \'region\': \'California\', \'country\': \'United States of America\', \'lat\': 37.78, \'lon\': -122.42, \'tz_id\': \'America/Los_Angeles\', \'localtime_epoch\': 1712852407, \'localtime\': \'2024-04-11 9:20\'}, \'current\': {\'last_updated_epoch\': 1712852100, \'last_updated\': \'2024-04-11 09:15\', \'temp_c\': 15.0, \'temp_f\': 59.0, \'is_day\': 1, \'condition\': {\'text\': \'Partly cloudy\', \'icon\': \'//cdn.weatherapi.com/weather/64x64/day/116.png\', \'code\': 1003}, \'wind_mph\': 3.8, \'wind_kph\': 6.1, \'wind_degree\': 350, \'wind_dir\': \'N\', \'pressure_mb\': 1015.0, \'pressure_in\': 29.97, \'precip_mm\': 0.0, \'precip_in\': 0.0, \'humidity\': 78, \'cloud\': 25, \'feelslike_c\': 15.8, \'feelslike_f\': 60.4, \'vis_km\': 16.0, \'vis_miles\': 9.0, \'uv\': 4.0, \'gust_mph\': 8.3, \'gust_kph\': 13.3}}"}]', name='tavily_search_results_json', tool_call_id='call_HGOi2cCxKKVWnz8WMuOCWnZx'),
AIMessage(content='The current weather in San Francisco is as follows:\n- Temperature: 15.0°C (59.0°F)\n- Condition: Partly cloudy\n- Wind: 3.8 mph from the North\n- Humidity: 78%\n- Visibility: 16.0 km (9.0 miles)\n- UV Index: 4.0\n\nFor more details, you can visit [Weather API](https://www.weatherapi.com/).', response_metadata={'token_usage': {'completion_tokens': 93, 'prompt_tokens': 465, 'total_tokens': 558}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_b28b39ffa8', 'finish_reason': 'stop', 'logprobs': None}, id='run-923bcbd2-3c79-4696-8f9e-5142b50b20cf-0')]}In [8]:
inputs = {"messages": [HumanMessage(content="what is the weather in sf")]}
for output in app.stream(inputs):
# stream() yields dictionaries with output keyed by node name
for key, value in output.items():
print(f"Output from node '{key}':")
print("---")
print(value)
print("\n---\n")Output from node 'agent':
---
{'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_3QXwm9UTKcfN2BuFhTDlLgIN', 'function': {'arguments': '{"query":"weather in San Francisco"}', 'name': 'tavily_search_results_json'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 21, 'prompt_tokens': 87, 'total_tokens': 108}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_b28b39ffa8', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-9a2d6e22-873a-4afc-8ae2-0adf8176b1b2-0', tool_calls=[{'name': 'tavily_search_results_json', 'args': {'query': 'weather in San Francisco'}, 'id': 'call_3QXwm9UTKcfN2BuFhTDlLgIN'}])]}
---
Output from node 'action':
---
{'messages': [ToolMessage(content='[{"url": "https://www.weatherapi.com/", "content": "{\'location\': {\'name\': \'San Francisco\', \'region\': \'California\', \'country\': \'United States of America\', \'lat\': 37.78, \'lon\': -122.42, \'tz_id\': \'America/Los_Angeles\', \'localtime_epoch\': 1712852407, \'localtime\': \'2024-04-11 9:20\'}, \'current\': {\'last_updated_epoch\': 1712852100, \'last_updated\': \'2024-04-11 09:15\', \'temp_c\': 15.0, \'temp_f\': 59.0, \'is_day\': 1, \'condition\': {\'text\': \'Partly cloudy\', \'icon\': \'//cdn.weatherapi.com/weather/64x64/day/116.png\', \'code\': 1003}, \'wind_mph\': 3.8, \'wind_kph\': 6.1, \'wind_degree\': 350, \'wind_dir\': \'N\', \'pressure_mb\': 1015.0, \'pressure_in\': 29.97, \'precip_mm\': 0.0, \'precip_in\': 0.0, \'humidity\': 78, \'cloud\': 25, \'feelslike_c\': 15.8, \'feelslike_f\': 60.4, \'vis_km\': 16.0, \'vis_miles\': 9.0, \'uv\': 4.0, \'gust_mph\': 8.3, \'gust_kph\': 13.3}}"}]', name='tavily_search_results_json', tool_call_id='call_3QXwm9UTKcfN2BuFhTDlLgIN')]}
---
Output from node 'agent':
---
{'messages': [AIMessage(content='The current weather in San Francisco is partly cloudy with a temperature of 59°F (15°C). The wind speed is 6.1 km/h coming from the north. The humidity is at 78%, and the visibility is 16.0 km.', response_metadata={'token_usage': {'completion_tokens': 53, 'prompt_tokens': 465, 'total_tokens': 518}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_b28b39ffa8', 'finish_reason': 'stop', 'logprobs': None}, id='run-8875456d-e31e-42b0-b2af-bdc1a9cfccfe-0')]}
---
In [9]:
inputs = {"messages": [HumanMessage(content="what is the weather in sf?")]}
async for output in app.astream_log(inputs, include_types=["llm"]):
# astream_log() yields the requested logs (here LLMs) in JSONPatch format
for op in output.ops:
if op["path"] == "/streamed_output/-":
# this is the output from .stream()
...
elif op["path"].startswith("/logs/") and op["path"].endswith(
"/streamed_output/-"
):
# because we chose to only include LLMs, these are LLM tokens
print(op["value"])content='' additional_kwargs={'tool_calls': [{'index': 0, 'id': 'call_EdTLEVxQKMLRNv82Yqdcugdy', 'function': {'arguments': '', 'name': 'tavily_search_results_json'}, 'type': 'function'}]} id='run-acf76f4b-c5d0-46a1-a114-75021091719b' invalid_tool_calls=[{'name': 'tavily_search_results_json', 'args': '', 'id': 'call_EdTLEVxQKMLRNv82Yqdcugdy', 'error': 'Malformed args.'}] tool_call_chunks=[{'name': 'tavily_search_results_json', 'args': '', 'id': 'call_EdTLEVxQKMLRNv82Yqdcugdy', 'index': 0}]
content='' additional_kwargs={'tool_calls': [{'index': 0, 'id': None, 'function': {'arguments': '{"', 'name': None}, 'type': None}]} id='run-acf76f4b-c5d0-46a1-a114-75021091719b' tool_calls=[{'name': '', 'args': {}, 'id': None}] tool_call_chunks=[{'name': None, 'args': '{"', 'id': None, 'index': 0}]
content='' additional_kwargs={'tool_calls': [{'index': 0, 'id': None, 'function': {'arguments': 'query', 'name': None}, 'type': None}]} id='run-acf76f4b-c5d0-46a1-a114-75021091719b' invalid_tool_calls=[{'name': None, 'args': 'query', 'id': None, 'error': 'Malformed args.'}] tool_call_chunks=[{'name': None, 'args': 'query', 'id': None, 'index': 0}]
content='' additional_kwargs={'tool_calls': [{'index': 0, 'id': None, 'function': {'arguments': '":"', 'name': None}, 'type': None}]} id='run-acf76f4b-c5d0-46a1-a114-75021091719b' invalid_tool_calls=[{'name': None, 'args': '":"', 'id': None, 'error': 'Malformed args.'}] tool_call_chunks=[{'name': None, 'args': '":"', 'id': None, 'index': 0}]
content='' additional_kwargs={'tool_calls': [{'index': 0, 'id': None, 'function': {'arguments': 'weather', 'name': None}, 'type': None}]} id='run-acf76f4b-c5d0-46a1-a114-75021091719b' invalid_tool_calls=[{'name': None, 'args': 'weather', 'id': None, 'error': 'Malformed args.'}] tool_call_chunks=[{'name': None, 'args': 'weather', 'id': None, 'index': 0}]
content='' additional_kwargs={'tool_calls': [{'index': 0, 'id': None, 'function': {'arguments': ' in', 'name': None}, 'type': None}]} id='run-acf76f4b-c5d0-46a1-a114-75021091719b' invalid_tool_calls=[{'name': None, 'args': ' in', 'id': None, 'error': 'Malformed args.'}] tool_call_chunks=[{'name': None, 'args': ' in', 'id': None, 'index': 0}]
content='' additional_kwargs={'tool_calls': [{'index': 0, 'id': None, 'function': {'arguments': ' San', 'name': None}, 'type': None}]} id='run-acf76f4b-c5d0-46a1-a114-75021091719b' invalid_tool_calls=[{'name': None, 'args': ' San', 'id': None, 'error': 'Malformed args.'}] tool_call_chunks=[{'name': None, 'args': ' San', 'id': None, 'index': 0}]
content='' additional_kwargs={'tool_calls': [{'index': 0, 'id': None, 'function': {'arguments': ' Francisco', 'name': None}, 'type': None}]} id='run-acf76f4b-c5d0-46a1-a114-75021091719b' invalid_tool_calls=[{'name': None, 'args': ' Francisco', 'id': None, 'error': 'Malformed args.'}] tool_call_chunks=[{'name': None, 'args': ' Francisco', 'id': None, 'index': 0}]
content='' additional_kwargs={'tool_calls': [{'index': 0, 'id': None, 'function': {'arguments': '"}', 'name': None}, 'type': None}]} id='run-acf76f4b-c5d0-46a1-a114-75021091719b' invalid_tool_calls=[{'name': None, 'args': '"}', 'id': None, 'error': 'Malformed args.'}] tool_call_chunks=[{'name': None, 'args': '"}', 'id': None, 'index': 0}]
content='' response_metadata={'finish_reason': 'tool_calls'} id='run-acf76f4b-c5d0-46a1-a114-75021091719b'
content='' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='The' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' current' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' weather' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' in' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' San' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' Francisco' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' is' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' partly' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' cloudy' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' with' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' a' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' temperature' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' of' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' ' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='59' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='°F' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' (' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='15' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='°C' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=').' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' The' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' wind' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' speed' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' is' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' ' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='3' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='.' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='8' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' mph' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' (' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='6' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='.' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='1' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' k' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='ph' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=')' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' coming' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' from' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' the' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' north' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='.' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' The' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' humidity' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' is' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' at' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' ' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='78' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='%' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' with' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' a' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' visibility' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' of' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' ' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='9' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content=' miles' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='.' id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
content='' response_metadata={'finish_reason': 'stop'} id='run-bd561aa4-2af3-4d44-a110-b7991ec0d930'
In [ ]: