mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-09-25 11:05:12 +02:00
19 KiB
19 KiB
In [ ]:
%%capture --no-stderr
%pip install -U langgraphIn [5]:
from typing_extensions import TypedDict
from langgraph.graph import StateGraph
from langgraph.graph import START, END
class State(TypedDict):
value: str
action_result: str
def router(state: State):
if state["value"] == "end":
return END
else:
return "action"
def decision_node(state):
return {"value": "keep going!"}
def action_node(state: State):
# Do your action here ...
return {"action_result": "what a great result!"}
workflow = StateGraph(State)
workflow.add_node("decision", decision_node)
workflow.add_node("action", action_node)
workflow.add_edge(START, "decision")
workflow.add_conditional_edges("decision", router, ["action", END])
workflow.add_edge("action", "decision")
app = workflow.compile()In [4]:
from IPython.display import Image, display
display(Image(app.get_graph().draw_mermaid_png()))In [9]:
from langgraph.errors import GraphRecursionError
try:
app.invoke({"value": "hi!"})
except GraphRecursionError:
print("Recursion Error")Recursion Error
In [23]:
from typing_extensions import TypedDict
from langgraph.graph import StateGraph
from typing import Annotated
from langgraph.managed.base import ManagedValue
class IsLastOrSecondToLastStepManager(ManagedValue[bool]):
def __call__(self, step: int) -> bool:
limit = self.config.get("recursion_limit", 0)
return step >= limit - 2
class State(TypedDict):
value: str
action_result: str
is_last_step: Annotated[bool, IsLastOrSecondToLastStepManager]
def router(state: State):
# Force the agent to end if it is on the last step
if state["is_last_step"]:
return END
if state["value"] == "end":
return END
else:
return "action"
def decision_node(state):
return {"value": "keep going!"}
def action_node(state: State):
# Do your action here ...
return {"action_result": "what a great result!"}
workflow = StateGraph(State)
workflow.add_node("decision", decision_node)
workflow.add_node("action", action_node)
workflow.add_edge(START, "decision")
workflow.add_conditional_edges("decision", router, ["action", END])
workflow.add_edge("action", "decision")
app = workflow.compile()In [25]:
app.invoke({"value": "hi!"})Out [25]:
{'value': 'keep going!', 'action_result': 'what a great result!'}