पाठ 5 / 29
Conditional Edges और Routing
State से अगला node चुनें।
Function रास्ता चुनता है
add_conditional_edges(source, router, mapping) source के बाद router(state) चलाता है और उसके लौटाए मान से अगला node चुनता है। Router सादा Python (keyword जाँच, सीमाएँ) हो सकता है या पहले के classifier node द्वारा बनाया label पढ़ सकता है, अक्सर छोटी LLM call से। Routers pure और सस्ते रखें, सिर्फ़ ज्ञात labels लौटाएँ और default मामला हमेशा कवर करें। Routing हर node को सरल रखती है: classifier निर्णय लेता है, विशेषज्ञ nodes कार्य करते हैं, और graph संरचना एक नज़र में दिखाता है।
निर्णय, दोहराव, हस्तांतरण, विभाजन
Conditional edges, सीमा वाले loops, Command हस्तांतरण और Send fan-out अधिकांश agent प्रवाह कवर करते हैं।
Category से routing, चलाकर
मैंने यह Python virtual environment में langgraph 1.2.12 और langchain-core 1.6.6 के साथ ऑफ़लाइन चलाया। किसी API key या मॉडल की ज़रूरत नहीं क्योंकि मॉडल की जगह सादे Python functions हैं, इसलिए आउटपुट दोहराने योग्य है। classify node route सेट करता है; conditional edge refund और invoice सवाल billing को और बाक़ी सब other को भेजती है।
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
question: str
route: str
answer: str
def classify(state):
q = state["question"].lower()
return {"route": "billing" if "refund" in q or "invoice" in q else "other"}
def billing(state): return {"answer": "Routed to the billing team."}
def other(state): return {"answer": "Routed to general support."}
g = StateGraph(State)
g.add_node("classify", classify); g.add_node("billing", billing); g.add_node("other", other)
g.add_edge(START, "classify")
g.add_conditional_edges("classify", lambda s: s["route"], {"billing": "billing", "other": "other"})
g.add_edge("billing", END); g.add_edge("other", END)
app = g.compile()
for q in ("I want a refund", "Where is your office?"):
print(q, "->", app.invoke({"question": q})["answer"])
Output:
I want a refund -> Routed to the billing team. Where is your office? -> Routed to general support.
Routers को pure रखें
Router सिर्फ़ state पढ़े और label लौटाए। काम nodes में करें ताकि routing परखना आसान रहे।
त्वरित जाँच: Router को हमेशा क्या कवर करना चाहिए?
- सिर्फ़ पहला label
- अनपेक्षित labels के लिए default रास्ता
- कुछ नहीं
- GPU
Answer
अनपेक्षित labels के लिए default रास्ता — अनसँभाले labels errors या बंद गलियाँ पैदा करते हैं।