पाठ 14 / 29
Checkpointers और Threads
Runs के बीच state बनाए रखें ताकि बातचीत जारी रह सके।
Thread सहेजी हुई बातचीत है
Checkpointer हर चरण के बाद graph state सहेजता है। Checkpointer के साथ compile करने और config में thread_id के साथ invoke करने पर LangGraph उस thread की सहेजी state लोड करता है, आपका नया इनपुट reducers से मिलाता है, चलता है और फिर सहेजता है। अलग thread IDs पूरी तरह अलग बातचीतें हैं। यह अल्पकालिक स्मृति है। InMemorySaver विकास और tests के लिए है; production में टिकाऊ backend (जैसे SQLite या Postgres savers) चलता है। Thread IDs को संवेदनशील मानें: उन्हें प्रमाणित users और sessions से बनाएँ ताकि एक user दूसरे की thread कभी लोड न कर सके।
हर चरण पर state सहेजें
Checkpointers प्रति thread state सहेजते हैं, जिससे बातचीत, विफलता के बाद बहाली और replay संभव होते हैं।
दो users, दो threads, चलाकर
मैंने यह Python virtual environment में langgraph 1.2.12 और langchain-core 1.6.6 के साथ ऑफ़लाइन चलाया। किसी API key या मॉडल की ज़रूरत नहीं क्योंकि मॉडल की जगह सादे Python functions हैं, इसलिए आउटपुट दोहराने योग्य है। Alice की दूसरी call उसका पहला संदेश और bot का उत्तर देखती है (तब तक 3 संदेश), क्योंकि thread याद रखी जाती है। Bob की thread नई शुरू होती है।
import operator
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
class State(TypedDict):
messages: Annotated[list, operator.add] # reducer: new messages are appended to the stored ones
def reply(state):
return {"messages": [f"bot: I have seen {len(state['messages'])} message(s)"]}
g = StateGraph(State)
g.add_node("reply", reply); g.add_edge(START, "reply"); g.add_edge("reply", END)
app = g.compile(checkpointer=InMemorySaver())
alice = {"configurable": {"thread_id": "alice"}}
bob = {"configurable": {"thread_id": "bob"}}
print(app.invoke({"messages": ["alice: hi"]}, alice)["messages"])
print(app.invoke({"messages": ["alice: again"]}, alice)["messages"]) # same thread: history is remembered
print(app.invoke({"messages": ["bob: hello"]}, bob)["messages"]) # new thread: starts fresh
Output:
['alice: hi', 'bot: I have seen 1 message(s)'] ['alice: hi', 'bot: I have seen 1 message(s)', 'alice: again', 'bot: I have seen 3 message(s)'] ['bob: hello', 'bot: I have seen 1 message(s)']
त्वरित जाँच: Checkpointer के लिए बातचीत की पहचान क्या है?
- GPU id
- मॉडल का नाम
- Node का नाम
- Run config का thread_id
Answer
Run config का thread_id — हर thread_id का अपना सहेजा state इतिहास होता है।