पाठ 8 / 29
Command: State अद्यतन और Route साथ
Node को state अद्यतन करते हुए तय करने दें कि आगे कहाँ जाना है।
Node के भीतर routing
Node सादे dict की जगह Command(update=..., goto=...) लौटा सकता है: वह state अद्यतन करता है और अगले node का नाम भी देता है। यह तब उपयोगी है जब काम करने वाला node ही सबसे अच्छी स्थिति में हो तय करने के लिए कि आगे क्या हो, और यह agents के बीच हस्तांतरण का आधार है (एक agent जुटाए डेटा के साथ दूसरे agent को route करता है)। Return type annotate करें, जैसे Command[Literal["writer", "__end__"]], ताकि graph खींचा और validate किया जा सके। Conditional edges और Command साथ रह सकते हैं; गतिशील हस्तांतरण के लिए Command, निश्चित संरचना के लिए edges।
Command से supervisor routing, चलाकर
मैंने यह Python virtual environment में langgraph 1.2.12 और langchain-core 1.6.6 के साथ ऑफ़लाइन चलाया। किसी API key या मॉडल की ज़रूरत नहीं क्योंकि मॉडल की जगह सादे Python functions हैं, इसलिए आउटपुट दोहराने योग्य है। supervisor शोध कार्य researcher को और बाक़ी writer को भेजता है; हर worker result अद्यतन करके नियंत्रण लौटाता है, और result बनने पर supervisor run समाप्त करता है।
from typing import Literal, TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command
class State(TypedDict):
task: str
result: str
def supervisor(state) -> Command[Literal["researcher", "writer", "__end__"]]:
if not state.get("result"):
return Command(goto="researcher" if "find" in state["task"] else "writer")
return Command(goto=END)
def researcher(state) -> Command[Literal["supervisor"]]:
return Command(update={"result": "facts about " + state["task"]}, goto="supervisor")
def writer(state) -> Command[Literal["supervisor"]]:
return Command(update={"result": "draft for " + state["task"]}, goto="supervisor")
g = StateGraph(State)
g.add_node("supervisor", supervisor); g.add_node("researcher", researcher); g.add_node("writer", writer)
g.add_edge(START, "supervisor")
app = g.compile()
for task in ("find the 2025 leave policy", "write a welcome note"):
print(task, "->", app.invoke({"task": task, "result": ""})["result"])
Output:
find the 2025 leave policy -> facts about find the 2025 leave policy write a welcome note -> draft for write a welcome note
Command return type annotate करें
Annotation में Literal node नाम LangGraph को संभावित गंतव्य खींचने और validate करने देते हैं।
त्वरित जाँच: Command(update=..., goto=...) लौटाने से क्या होता है?
- मॉडल दो बार बुलाता है
- Graph हटाता है
- एक ही चरण में state अद्यतन करता है और अगला node चुनता है
- Recursion limit सेट करता है
Answer
एक ही चरण में state अद्यतन करता है और अगला node चुनता है — यह state लिखने को routing निर्णय के साथ जोड़ता है।