पाठ 3 / 29

आपका पहला Graph

दो-node graph बनाएँ, compile करें और चलाएँ।

परिभाषित करें, जोड़ें, compile करें, चलाएँ

नुस्ख़ा चार चरणों का है: state schema परिभाषित करें; node functions लिखें; StateGraph(State) बनाएँ, nodes और edges जोड़ें, START से शुरू और END पर समाप्त; compile करें और प्रारंभिक state के साथ invoke करें। Nodes एक काम करें, सिर्फ़ वही लौटाएँ जो बदला, और छिपी वैश्विक state से बचें। Nodes के स्पष्ट नाम traces और error संदेशों में मदद करते हैं। प्रवाह का आरेख दस्तावेज़ के लिए पाने को app.get_graph().draw_mermaid() भी बुला सकते हैं।

दो-node graph, चलाकर

मैंने यह Python virtual environment में langgraph 1.2.12 और langchain-core 1.6.6 के साथ ऑफ़लाइन चलाया। किसी API key या मॉडल की ज़रूरत नहीं क्योंकि मॉडल की जगह सादे Python functions हैं, इसलिए आउटपुट दोहराने योग्य है। Graph clean फिर count चलाता है। State पाठ और उठाए चरणों की सूची रखती है, और अंतिम state दिखाती है कि दोनों nodes क्रम से चले।

from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    text: str
    steps: list

def clean(state: State):
    return {"text": state["text"].strip().lower(), "steps": state["steps"] + ["clean"]}

def count(state: State):
    return {"text": f"{state['text']} ({len(state['text'].split())} words)", "steps": state["steps"] + ["count"]}

g = StateGraph(State)
g.add_node("clean", clean)
g.add_node("count", count)
g.add_edge(START, "clean")
g.add_edge("clean", "count")
g.add_edge("count", END)
app = g.compile()

print(app.invoke({"text": "  Hello Big WORLD  ", "steps": []}))

Output:

{'text': 'hello big world (3 words)', 'steps': ['clean', 'count']}

Nodes के नाम इंसानों के लिए रखें

classify, draft_reply और send_reply जैसे नाम traces और error संदेश पठनीय बनाते हैं।

त्वरित जाँच: compile() क्या लौटाता है?

  • Database
  • प्रशिक्षित मॉडल
  • JSON फ़ाइल
  • invoke और stream वाला runnable app
Answer

invoke और stream वाला runnable app — Compile graph को validate करके चलने योग्य application बनाता है।