mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-17 21:25:46 +02:00
20 KiB
20 KiB
In [1]:
%%capture --no-stderr
%pip install -U langgraph langchain-openaiIn [2]:
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")
# Recommended
_set_env("LANGCHAIN_API_KEY")
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_PROJECT"] = "Create ReAct Agent Tutorial"OPENAI_API_KEY: ········
In [1]:
# First we initialize the model we want to use.
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0)
# For this tutorial we will use custom tool that returns pre-defined values for weather in two cities (NYC & SF)
from typing import Literal
from langchain_core.tools import tool
@tool
def get_weather(city: Literal["nyc", "sf"]):
"""Use this to get weather information."""
if city == "nyc":
return "It might be cloudy in nyc"
elif city == "sf":
return "It's always sunny in sf"
else:
raise AssertionError("Unknown city")
tools = [get_weather]
# Define the graph
from langgraph.prebuilt import create_react_agent
graph = create_react_agent(model, tools=tools)In [4]:
from IPython.display import Image, display
display(Image(graph.get_graph().draw_mermaid_png()))In [5]:
def print_stream(stream):
for s in stream:
message = s["messages"][-1]
if isinstance(message, tuple):
print(message)
else:
message.pretty_print()In [6]:
inputs = {"messages": [("user", "what is the weather in sf")]}
print_stream(graph.stream(inputs, stream_mode="values"))================================[1m Human Message [0m================================= what is the weather in sf ==================================[1m Ai Message [0m================================== Tool Calls: get_weather (call_jgO5OOUnugRkhRi3wAOHl8Et) Call ID: call_jgO5OOUnugRkhRi3wAOHl8Et Args: city: sf =================================[1m Tool Message [0m================================= Name: get_weather It's always sunny in sf ==================================[1m Ai Message [0m================================== The weather in San Francisco is currently sunny.
In [7]:
inputs = {"messages": [("user", "who built you?")]}
print_stream(graph.stream(inputs, stream_mode="values"))================================[1m Human Message [0m================================= who built you? ==================================[1m Ai Message [0m================================== I was created by OpenAI, a research organization focused on developing and advancing artificial intelligence technology.