पाठ 4 / 29
State Reducers: बदलें या जमा करें
नियंत्रित करें कि node अद्यतन state में कैसे मिलें।
आख़िरी-लिखा-जीतता है बनाम जोड़ना
डिफ़ॉल्ट रूप से node का लौटाया मान उस state key को अधिलेखित करता है। जिन keys को जमा होना चाहिए (संदेश सूची, log, जुटाए परिणाम) उन पर Annotated[list, operator.add] से reducer लगाते हैं: अद्यतन बदलने की जगह reducer से जोड़े जाते हैं। LangGraph का अपना add_messages reducer chat messages के लिए यही करता है और message ID से भी मिलाता है। Reducers समानांतर शाखाओं के साथ सबसे ज़्यादा मायने रखते हैं: एक चरण में एक ही key लिखने वाले कई nodes को मिलाने की विधि चाहिए, वरना error आता है। हर key के लिए तय करें कि वह "नवीनतम मान" है या "जोड़ना"।
Reducer बनाम अधिलेखन, चलाकर
मैंने यह Python virtual environment में langgraph 1.2.12 और langchain-core 1.6.6 के साथ ऑफ़लाइन चलाया। किसी API key या मॉडल की ज़रूरत नहीं क्योंकि मॉडल की जगह सादे Python functions हैं, इसलिए आउटपुट दोहराने योग्य है। दोनों nodes log प्रविष्टि और score लौटाते हैं। log key पर operator.add reducer है, इसलिए दोनों प्रविष्टियाँ जमा होती हैं; score पर कोई नहीं, इसलिए आख़िरी लिखा (2) जीतता है।
import operator
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
log: Annotated[list, operator.add] # reducer: updates are appended, not replaced
score: int # no reducer: last write wins
def a(state): return {"log": ["a ran"], "score": 1}
def b(state): return {"log": ["b ran"], "score": 2}
g = StateGraph(State)
g.add_node("a", a); g.add_node("b", b)
g.add_edge(START, "a"); g.add_edge("a", "b"); g.add_edge("b", END)
print(g.compile().invoke({"log": [], "score": 0}))
Output:
{'log': ['a ran', 'b ran'], 'score': 2}Chat के लिए add_messages उपयोग करें
बातचीत इतिहास के लिए Annotated[list, add_messages] नए messages जोड़ता है और ID से मौजूदा अद्यतन करता है।
त्वरित जाँच: State key पर reducer क्या करता है?
- Key हटाता है
- तय करता है कि नए अद्यतन मौजूदा मान से कैसे मिलें
- Graph compile करता है
- GPU तेज़ करता है
Answer
तय करता है कि नए अद्यतन मौजूदा मान से कैसे मिलें — Reducer के बिना नवीनतम लिखा पुराने मान को बदल देता है।