LangGraph StateGraph คืออะไร
LangGraph StateGraph เป็นเครื่องมือจาก LangChain ที่ช่วยให้เราสร้าง "เครื่องสถานะ" (State Machine) สำหรับ AI Agent ได้ง่ายๆ โดยหลักการคือการกำหนด "สถานะ" (State) ของโปรแกรม แล้วบอกว่าในแต่ละสถานะจะไปสถานะไหนต่อ เหมาะมากสำหรับสร้างแชทบอทที่ต้องจำข้อมูล หรือระบบที่มีหลายขั้นตอน
เตรียมเครื่องมือก่อนเริ่มต้น
เราต้องติดตั้งโปรแกรม 2 อย่าง:
- Python — ภาษาที่ใช้เขียนโค้ด
- pip — โปรแกรมติดตั้งไลบรารี
วิธีติดตั้งไลบรารี
pip install langchain-core langchain-holysheep langgraph
หลังติดตั้งเสร็จ ให้สร้างไฟล์ชื่อ app.py แล้วเขียนโค้ดตามด้านล่าง
ตัวอย่างแรก: แชทบอททักทายง่ายๆ
เราจะสร้างโปรแกรมที่มี 2 สถานะ:
- greeting — ทักทายผู้ใช้
- chatting — คุยต่อ
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
กำหนดโครงสร้างข้อมูลที่จะเก็บ
class ChatState(TypedDict):
messages: list # เก็บข้อความทั้งหมด
step: str # เก็บว่าตอนนี้อยู่ขั้นไหน
ฟังก์ชันสำหรับสถานะทักทาย
def greeting_node(state: ChatState) -> ChatState:
state["messages"].append("สวัสดีครับ! ยินดีต้อนรับ")
state["step"] = "chatting"
return state
ฟังก์ชันสำหรับสถานะคุย
def chatting_node(state: ChatState) -> ChatState:
last_message = state["messages"][-1] if state["messages"] else ""
state["messages"].append(f"คุณพูดว่า: {last_message}")
return state
สร้างกราฟ
graph = StateGraph(ChatState)
เพิ่มโหนด (จุดทำงาน)
graph.add_node("greeting", greeting_node)
graph.add_node("chatting", chatting_node)
เพิ่มเส้นเชื่อมระหว่างจุด
graph.add_edge(START, "greeting")
graph.add_edge("greeting", "chatting")
graph.add_edge("chatting", END)
คอมไพล์กราฟ
app = graph.compile()
ทดสอบ
result = app.invoke({"messages": [], "step": "start"})
print(result["messages"])
ตัวอย่างที่สอง: เชื่อมต่อกับ HolySheep AI
ในตัวอย่างนี้เราจะเชื่อมต่อกับ HolySheep AI ซึ่งมีความเร็วต่ำกว่า 50 มิลลิวินาที และราคาประหยัดกว่า 85% เมื่อเทียบกับบริการอื่น โดยใช้โมเดล Claude Sonnet 4.5 ที่ราคาเพียง $15 ต่อล้านโทเค็น
from typing import TypedDict
from langchain_holysheep import ChatHolySheep
from langgraph.graph import StateGraph, START, END
เชื่อมต่อกับ HolySheep API
llm = ChatHolySheep(
model="claude-sonnet-4.5",
api_key="YOUR_HOLYSHEEP_API_KEY",
base_url="https://api.holysheep.ai/v1"
)
class AgentState(TypedDict):
user_input: str
ai_response: str
history: list
def think_node(state: AgentState) -> AgentState:
# ส่งข้อความไปถาม AI
messages = [{"role": "user", "content": state["user_input"]}]
response = llm.invoke(messages)
state["ai_response"] = response.content
state["history"].append({"user": state["user_input"], "ai": response.content})
return state
graph = StateGraph(AgentState)
graph.add_node("think", think_node)
graph.add_edge(START, "think")
graph.add_edge("think", END)
app = graph.compile()
ทดสอบถาม AI
result = app.invoke({
"user_input": "อธิบายเรื่อง AI Agent แบบง่ายๆ",
"ai_response": "",
"history": []
})
print(result["ai_response"])
ตัวอย่างที่สาม: State Machine หลายเส้นทาง
ตัวอย่างนี้จะสอนให้โปรแกรมตัดสินใจเองว่าจะไปสถานะไหน โดยดูจากคำตอบของผู้ใช้ เหมาะสำหรับสร้างระบบตอบคำถามอัตโนมัติ
from typing import Literal
from langchain_holysheep import ChatHolySheep
from langgraph.graph import StateGraph, START
llm = ChatHolySheep(
model="claude-sonnet-4.5",
api_key="YOUR_HOLYSHEEP_API_KEY",
base_url="https://api.holysheep.ai/v1"
)
class MultiState(TypedDict):
question: str
category: str
answer: str
def classify_node(state: MultiState) -> MultiState:
prompt = f"จำแนกคำถามนี้เป็น 'price', 'tech', หรือ 'support': {state['question']}"
result = llm.invoke([{"role": "user", "content": prompt}])
state["category"] = result.content.strip().lower()
return state
def price_node(state: MultiState) -> MultiState:
state["answer"] = "ราคาของเราเริ่มต้นที่ $0.42 ต่อล้านโทเค็นสำหรับ DeepSeek V3.2"
return state
def tech_node(state: MultiState) -> MultiState:
state["answer"] = "เราใช้เทคโนโลยี AI ล่าสุด รองรับ GPT-4.1, Claude Sonnet 4.5, Gemini 2.5 Flash"
return state
def support_node(state: MultiState) -> MultiState:
state["answer"] = "ทีมงานของเราพร้อมช่วยเหลือ 24 ชั่วโมง ติดต่อได้ทาง WeChat หรือ Alipay"
return state
def route_after_classify(state: MultiState) -> Literal["price", "tech", "support"]:
return state["category"]
graph = StateGraph(MultiState)
graph.add_node("classify", classify_node)
graph.add_node("price", price_node)
graph.add_node("tech", tech_node)
graph.add_node("support", support_node)
graph.add_edge(START, "classify")
graph.add_conditional_edges("classify", route_after_classify)
app = graph.compile()
ทดสอบ
result = app.invoke({"question": "ราคาเท่าไหร่?", "category": "", "answer": ""})
print(f"คำตอบ: {result['answer']}")
ข้อแนะนำเพิ่มเติม
หลังจากเข้าใจพื้นฐานแล้ว ลองประยุกต์ใช้กับงานจริง เช่น ระบบรีวิวสินค้าที่ต้องเก็บข้อมูลหลายอย่าง หรือแชทบอทที่ต้องจำบทสนทนายาวๆ สิ่งสำคัญคือออกแบบ State ให้เหมาะกับงาน และทดสอบให้ละเอียดก่อนใช้งานจริง
ข้อผิดพลาดที่พบบ่อยและวิธีแก้ไข
กรณีที่ 1: API Key ไม่ถูกต้อง
# ❌ ผิด - ลืมใส่ API Key
llm = ChatHolySheep(
model="claude-sonnet-4.5",
api_key="YOUR_HOLYSHEEP_API_KEY", # ยังเป็นตัวอย่างอยู่
base_url="https://api.holysheep.ai/v1"
)
✅ ถูกต้อง - แทนที่ด้วย API Key จริง
llm = ChatHolySheep(
model="claude-sonnet-4.5",
api_key="sk-xxxx-your-real-key-here",
base_url="https://api.holysheep.ai/v1"
)
กรณีที่ 2: base_url ผิดพลาด
# ❌ ผิด - ใช้ URL ของ OpenAI
llm = ChatHolySheep(
model="claude-sonnet-4.5",
api_key="YOUR_API_KEY",
base_url="https://api.openai.com/v1" # ผิด!
)
✅ ถูกต้อง - ใช้ URL ของ HolySheep
llm = ChatHolySheep(
model="claude-sonnet-4.5",
api_key="YOUR_API_KEY",
base_url="https://api.holysheep.ai/v1" # ถูกต้อง
)
กรณีที่ 3: State ไม่ตรงกับที่กำหนด
# ❌ ผิด - เพิ่ม key ที่ไม่มีใน TypedDict
class ChatState(TypedDict):
messages: list
state = {"messages": [], "extra_key": "value"} # extra_key ไม่มีใน ChatState
✅ ถูกต้อง - กำหนด key ให้ครบ
class ChatState(TypedDict):
messages: list
step: str
history: list
state = {"messages": [], "step": "start", "history": []}
กรณีที่ 4: Node ซ้ำกัน
# ❌ ผิด - เพิ่ม node ชื่อซ้ำ
graph.add_node("chat", node_a)
graph.add_node("chat", node_b) # ซ้ำ!
✅ ถูกต้อง - ใช้ชื่อต่างกัน
graph.add_node("chat_first", node_a)
graph.add_node("chat_followup", node_b)
สรุป
การใช้ LangGraph StateGraph ช่วยให้เราสร้าง AI Agent ที่มีลำดับขั้นตอนชัดเจน ไม่ว่าจะเป็นแชทบอทง่ายๆ หรือระบบซับซ้อน โดยใช้ HolySheep AI ที่มีความเร็วต่ำกว่า 50 มิลลิวินาที รองรับหลายโมเดลทั้ง GPT-4.1 ($8/MTok), Claude Sonnet 4.5 ($15/MTok), Gemini 2.5 Flash ($2.50/MTok) และ DeepSeek V3.2 ($0.42/MTok) พร้อมรองรับการชำระเงินผ่าน WeChat และ Alipay
👉 สมัคร HolySheep AI — รับเครดิตฟรีเมื่อลงทะเบียน