慣性聚合 高效追蹤和閱讀你感興趣的部落格、新聞、科技資訊
閱讀原文 在慣性聚合中打開

推薦訂閱源

博客园 - 司徒正美
V
V2EX
T
Tailwind CSS Blog
有赞技术团队
有赞技术团队
aimingoo的专栏
aimingoo的专栏
Apple Machine Learning Research
Apple Machine Learning Research
IT之家
IT之家
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
月光博客
月光博客
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
V
Visual Studio Blog
WordPress大学
WordPress大学
酷 壳 – CoolShell
酷 壳 – CoolShell
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python)
LangGraph 工作流程模板 (v6)
matias yoon · 2026-05-24 · via DEV Community

matias yoon

LangGraph 工作流程模板 (v6)

LangGraph 是為現代 AI 代理開發而設計的強大框架,專為實現基於狀態的工作流程而優化。在本指南中,我們提供了解決開發者常見問題的五種核心模板。

1. LangGraph 架構概覽

LangGraph 由以下核心組成部分構成:

from langgraph.graph import StateGraph, END
from langgraph.checkpoint.memory import MemorySaver
from typing import TypedDict, Annotated
import operator

# 상태 정의
class AgentState(TypedDict):
    messages: Annotated[list, operator.add]
    # 기타 상태 필드

# 노드 정의
def retrieve_node(state):
    # 문서 검색 로직
    pass

def generate_node(state):
    # 생성 로직
    pass

# 엣지 정의
def route_to_next(state):
    # 다음 노드 결정 로직
    pass

# 워크플로우 정의
workflow = StateGraph(AgentState)
workflow.add_node("retrieve", retrieve_node)
workflow.add_node("generate", generate_node)
workflow.add_edge("retrieve", "generate")
workflow.add_conditional_edges("generate", route_to_next)
workflow.set_entry_point("retrieve")
workflow.set_finish_point(END)

# 체크포인팅 설정
memory = MemorySaver()
app = workflow.compile(checkpointer=memory)

Enter fullscreen mode Exit fullscreen mode

2. 模板 1: 簡單的 RAG 代理 (搜索 → 創建 → 驗證)

此範本結合了文件搜尋與創建的基本 RAG 工作流程。

from langchain_core.messages import HumanMessage, AIMessage
from langchain_openai import ChatOpenAI
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain_core.prompts import ChatPromptTemplate
import operator
from typing import Annotated, List
from langgraph.graph import StateGraph, END

class RAGState(TypedDict):
    query: str
    retrieved_docs: List[str]
    generated_response: str
    validation_result: bool

# 검색 노드
def retrieve_node(state: RAGState):
    # Chroma에서 문서 검색
    vectorstore = Chroma(
        persist_directory="./chroma_db",
        embedding_function=OpenAIEmbeddings()
    )

    docs = vectorstore.similarity_search(state["query"], k=3)
    return {"retrieved_docs": [doc.page_content for doc in docs]}

# 생성 노드
def generate_node(state: RAGState):
    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are a helpful assistant that answers questions based on provided context."),
        ("human", """Context: {context}
Question: {question}
Answer:""")
    ])

    model = ChatOpenAI(model="gpt-4")
    chain = prompt | model

    response = chain.invoke({
        "context": "\n".join(state["retrieved_docs"]),
        "question": state["query"]
    })

    return {"generated_response": response.content}

# 검증 노드
def validate_node(state: RAGState):
    # 생성된 응답 검증
    if len(state["generated_response"]) < 10:
        return {"validation_result": False}

    # 간단한 키워드 기반 검증
    keywords = ["answer", "question", "context", "response"]
    valid = any(keyword in state["generated_response"].lower() for keyword in keywords)
    return {"validation_result": valid}

# 워크플로우 정의
def create_rag_workflow():
    workflow = StateGraph(RAGState)

    workflow.add_node("retrieve", retrieve_node)
    workflow.add_node("generate", generate_node)
    workflow.add_node("validate", validate_node)

    workflow.add_edge("retrieve", "generate")
    workflow.add_edge("generate", "validate")

    # 검증 결과에 따라 처리
    def route_validation(state: RAGState):
        if not state["validation_result"]:
            return "retry"
        return "end"

    workflow.add_conditional_edges(
        "validate",
        route_validation,
        {
            "retry": "retrieve",
            "end": END
        }
    )

    workflow.set_entry_point("retrieve")
    return workflow.compile()

# 사용 예시
# app = create_rag_workflow()
# result = app.invoke({"query": "Python 디자인 패턴에 대해 설명해주세요"})

Enter fullscreen mode Exit fullscreen mode

3. 範本 2:多工器代理(計劃 → 執行 → 觀察 → 決定)

此範本適用於可使用多個工具的複雜代理的流程。

from typing import Literal
from langgraph.graph import StateGraph, END
from langchain_core.messages import ToolMessage

class ToolAgentState(TypedDict):
    messages: Annotated[list, operator.add]
    plan: List[str]
    current_tool: str
    tool_result: str

# 계획 노드
def plan_node(state: ToolAgentState):
    # 도구 사용 계획 생성
    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are a task planner. Analyze the following request and create a plan of actions."),
        ("human", "Request: {request}\nPlan:")

    ])

    model = ChatOpenAI(model="gpt-4")
    chain = prompt | model

    response = chain.invoke({"request": state["messages"][-1].content})

    return {"plan": response.content.split('\n')}

# 실행 노드
def execute_node(state: ToolAgentState):
    # 도구 실행
    tool_name = state["plan"][0]  # 첫 번째 계획 항목

    # 실제 도구 실행 로직 (예: 파일 시스템 조작)
    if tool_name == "file_search":
        # 파일 검색 로직
        result = "Found files matching criteria"
    elif tool_name == "code_analysis":
        # 코드 분석 로직
        result = "Code analysis complete"
    else:
        result = "Tool not recognized"

    return {"current_tool": tool_name, "tool_result": result}

# 관찰 노드
def observe_node(state: ToolAgentState):
    # 도구 결과 관찰
    messages = state["messages"]
    tool_message = ToolMessage(
        content=state["tool_result"],
        tool_call_id=state["current_tool"]
    )

    return {"messages": [tool_message]}

# 결정 노드
def decide_node(state: ToolAgentState):
    # 다음 단계 결정
    if len(state["plan"]) > 1:
        return "continue"
    return "end"

# 워크플로우 정의
def create_tool_workflow():
    workflow = StateGraph(ToolAgentState)

    workflow.add_node("plan", plan_node)
    workflow.add_node("execute", execute_node)
    workflow.add_node("observe", observe_node)
    workflow.add_node("decide", decide_node)

    workflow.add_edge("plan", "execute")
    workflow.add_edge("execute", "observe")
    workflow.add_edge("observe", "decide")

    def route_decision(state: ToolAgentState):
        if state["plan"] and len(state["plan"]) > 1:
            return "plan"
        return "end"

    workflow.add_conditional_edges(
        "decide",
        route_decision,
        {
            "plan": "plan",
            "end": END
        }
    )

    workflow.set_entry_point("plan")
    return workflow.compile()

# 사용 예시
# app = create_tool_workflow()
# result = app.invoke({"messages": [HumanMessage(content="파일 시스템에서 모든 Python 파일을 검색해주세요")]})

Enter fullscreen mode Exit fullscreen mode

4. 範本 3:人類中介流程(暫停 → 审核 → 繼續)

此範本是用於處理需要人類介入的任務的流程。


python
from langgraph.graph import StateGraph, END, START
from langchain_core.messages import AIMessage

class HumanInLoopState(TypedDict):
    messages: Annotated[list, operator.add]
    action_needed: bool
    user_feedback: str
    processed_result: str

# 작업 생성 노드
def create_task_node(state: HumanInLoopState):
    # 작업 생성 및 인간 개입 필요성 판단
    prompt = ChatPromptTemplate.from_messages([
        ("system", "Generate task based on user request and determine if human review is needed."),
        ("human", "Request: {request}\nGenerate task:")
    ])

    model = ChatOpenAI(model="gpt-4")
    chain = prompt | model

    response = chain.invoke({"request": state["messages"][-1].content})

    # 간단한 규칙으로 인간 개입 필요성 판단
    needs_review = "review" in response.content.lower() or "approve" in response.content.lower()

    return {
        "messages": [AIMessage(content=response.content)],
        "action_needed":

---

📥 **Get the full guide on Gumroad**: https://gumroad.com/l/auto ($5)

進入全螢幕模式 退出全螢幕模式