mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-17 21:25:46 +02:00
8.8 KiB
8.8 KiB
In [1]:
%%capture --no-stderr
%pip install -U langgraph langchain-openaiIn [ ]:
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")In [3]:
# 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]
# We can add "chat memory" to the graph with LangGraph's checkpointer
# to retain the chat context between interactions
from langgraph.checkpoint.memory import MemorySaver
memory = MemorySaver()
# Define the graph
from langgraph.prebuilt import create_react_agent
graph = create_react_agent(model, tools=tools, checkpointer=memory)In [4]:
def print_stream(stream):
for s in stream:
message = s["messages"][-1]
if isinstance(message, tuple):
print(message)
else:
message.pretty_print()In [5]:
config = {"configurable": {"thread_id": "1"}}
inputs = {"messages": [("user", "What's the weather in NYC?")]}
print_stream(graph.stream(inputs, config=config, stream_mode="values"))================================[1m Human Message [0m================================= What's the weather in NYC? ==================================[1m Ai Message [0m================================== Tool Calls: get_weather (call_mdovy4yXSSYrmSlnlVSUacVn) Call ID: call_mdovy4yXSSYrmSlnlVSUacVn Args: city: nyc =================================[1m Tool Message [0m================================= Name: get_weather It might be cloudy in nyc ==================================[1m Ai Message [0m================================== The weather in NYC might be cloudy.
In [6]:
inputs = {"messages": [("user", "What's it known for?")]}
print_stream(graph.stream(inputs, config=config, stream_mode="values"))================================[1m Human Message [0m================================= What's it known for? ==================================[1m Ai Message [0m================================== New York City (NYC) is known for many things, including: 1. **Landmarks and Attractions**: The Statue of Liberty, Times Square, Central Park, Empire State Building, and Brooklyn Bridge. 2. **Cultural Institutions**: Broadway theaters, Metropolitan Museum of Art, Museum of Modern Art (MoMA), and the American Museum of Natural History. 3. **Diverse Neighborhoods**: Areas like Chinatown, Little Italy, Harlem, and Greenwich Village. 4. **Financial Hub**: Wall Street and the New York Stock Exchange. 5. **Cuisine**: A melting pot of global cuisines, famous for its pizza, bagels, and street food. 6. **Media and Entertainment**: Home to major media companies, TV networks, and film studios. 7. **Fashion**: A global fashion capital, hosting New York Fashion Week. 8. **Sports**: Teams like the New York Yankees, New York Mets, New York Knicks, and New York Rangers. 9. **Public Transportation**: An extensive subway system and iconic yellow taxis. 10. **Events**: New Year's Eve celebration in Times Square, Macy's Thanksgiving Day Parade, and various cultural festivals.