mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-09-03 05:08:42 +02:00
16 KiB
16 KiB
In [1]:
%%capture --no-stderr
%pip install --quiet -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")OPENAI_API_KEY: ········
In [3]:
from typing import TypedDict
from langgraph.graph import StateGraph, START
class State(TypedDict):
topic: str
joke: str
def refine_topic(state: State):
return {"topic": state["topic"] + " and cats"}
def generate_joke(state: State):
return {"joke": f"This is a joke about {state['topic']}"}
graph = (
StateGraph(State)
.add_node(refine_topic)
.add_node(generate_joke)
.add_edge(START, "refine_topic")
.add_edge("refine_topic", "generate_joke")
.compile()
)In [4]:
for chunk in graph.stream(
{"topic": "ice cream"},
# highlight-next-line
stream_mode="values",
):
print(chunk){'topic': 'ice cream'}
{'topic': 'ice cream and cats'}
{'topic': 'ice cream and cats', 'joke': 'This is a joke about ice cream and cats'}
In [5]:
for chunk in graph.stream(
{"topic": "ice cream"},
# highlight-next-line
stream_mode="updates",
):
print(chunk){'refine_topic': {'topic': 'ice cream and cats'}}
{'generate_joke': {'joke': 'This is a joke about ice cream and cats'}}
In [6]:
for chunk in graph.stream(
{"topic": "ice cream"},
# highlight-next-line
stream_mode="debug",
):
print(chunk){'type': 'task', 'timestamp': '2025-01-28T22:06:34.789803+00:00', 'step': 1, 'payload': {'id': 'eb305d74-3460-9510-d516-beed71a63414', 'name': 'refine_topic', 'input': {'topic': 'ice cream'}, 'triggers': ['start:refine_topic']}}
{'type': 'task_result', 'timestamp': '2025-01-28T22:06:34.790013+00:00', 'step': 1, 'payload': {'id': 'eb305d74-3460-9510-d516-beed71a63414', 'name': 'refine_topic', 'error': None, 'result': [('topic', 'ice cream and cats')], 'interrupts': []}}
{'type': 'task', 'timestamp': '2025-01-28T22:06:34.790165+00:00', 'step': 2, 'payload': {'id': '74355cb8-6284-25e0-579f-430493c1bdab', 'name': 'generate_joke', 'input': {'topic': 'ice cream and cats'}, 'triggers': ['refine_topic']}}
{'type': 'task_result', 'timestamp': '2025-01-28T22:06:34.790337+00:00', 'step': 2, 'payload': {'id': '74355cb8-6284-25e0-579f-430493c1bdab', 'name': 'generate_joke', 'error': None, 'result': [('joke', 'This is a joke about ice cream and cats')], 'interrupts': []}}
In [7]:
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini")
def generate_joke(state: State):
# highlight-next-line
llm_response = llm.invoke(
# highlight-next-line
[
# highlight-next-line
{"role": "user", "content": f"Generate a joke about {state['topic']}"}
# highlight-next-line
]
# highlight-next-line
)
return {"joke": llm_response.content}
graph = (
StateGraph(State)
.add_node(refine_topic)
.add_node(generate_joke)
.add_edge(START, "refine_topic")
.add_edge("refine_topic", "generate_joke")
.compile()
)In [8]:
for message_chunk, metadata in graph.stream(
{"topic": "ice cream"},
# highlight-next-line
stream_mode="messages",
):
if message_chunk.content:
print(message_chunk.content, end="|", flush=True)Why| did| the| cat| sit| on| the| ice| cream| cone|? |Because| it| wanted| to| be| a| "|p|urr|-f|ect|"| scoop|!| 🍦|🐱|
In [9]:
metadataOut [9]:
{'langgraph_step': 2,
'langgraph_node': 'generate_joke',
'langgraph_triggers': ['refine_topic'],
'langgraph_path': ('__pregel_pull', 'generate_joke'),
'langgraph_checkpoint_ns': 'generate_joke:568879bc-8800-2b0d-a5b5-059526a4bebf',
'checkpoint_ns': 'generate_joke:568879bc-8800-2b0d-a5b5-059526a4bebf',
'ls_provider': 'openai',
'ls_model_name': 'gpt-4o-mini',
'ls_model_type': 'chat',
'ls_temperature': 0.7}In [10]:
from langgraph.types import StreamWriter
# highlight-next-line
def generate_joke(state: State, writer: StreamWriter):
# highlight-next-line
writer({"custom_key": "Writing custom data while generating a joke"})
return {"joke": f"This is a joke about {state['topic']}"}
graph = (
StateGraph(State)
.add_node(refine_topic)
.add_node(generate_joke)
.add_edge(START, "refine_topic")
.add_edge("refine_topic", "generate_joke")
.compile()
)In [11]:
for chunk in graph.stream(
{"topic": "ice cream"},
# highlight-next-line
stream_mode="custom",
):
print(chunk){'custom_key': 'Writing custom data while generating a joke'}
In [12]:
for stream_mode, chunk in graph.stream(
{"topic": "ice cream"},
# highlight-next-line
stream_mode=["updates", "custom"],
):
print(f"Stream mode: {stream_mode}")
print(chunk)
print("\n")Stream mode: updates
{'refine_topic': {'topic': 'ice cream and cats'}}
Stream mode: custom
{'custom_key': 'Writing custom data while generating a joke'}
Stream mode: updates
{'generate_joke': {'joke': 'This is a joke about ice cream and cats'}}