惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
T
ThreatConnect
SecWiki News
SecWiki News
F
Future of Privacy Forum
AWS News Blog
AWS News Blog
C
Cisco Blogs
A
Arctic Wolf
Vercel News
Vercel News
The GitHub Blog
The GitHub Blog
Scott Helme
Scott Helme
V
V2EX
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
K
Kaspersky official blog
G
Google Developers Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
P
Privacy International News Feed
C
Cyber Attacks, Cyber Crime and Cyber Security
N
News | PayPal Newsroom
Schneier on Security
Schneier on Security
NISL@THU
NISL@THU
Microsoft Azure Blog
Microsoft Azure Blog
量子位
The Hacker News
The Hacker News
Stack Overflow Blog
Stack Overflow Blog
Security Latest
Security Latest
M
Microsoft Research Blog - Microsoft Research
Google Online Security Blog
Google Online Security Blog
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
I
InfoQ
Google DeepMind News
Google DeepMind News
Y
Y Combinator Blog
The Cloudflare Blog
Microsoft Security Blog
Microsoft Security Blog
Martin Fowler
Martin Fowler
Cisco Talos Blog
Cisco Talos Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Troy Hunt's Blog
F
Fox-IT International blog
S
Security @ Cisco Blogs
博客园 - 司徒正美
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
Comments on: Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
L
LINUX DO - 最新话题
GbyAI
GbyAI
Project Zero
Project Zero
腾讯CDC
T
Tailwind CSS Blog

DEV Community

The git Commands You Forgot Exist (And Why AI Workflows Make Them Relevant Again) Six Levels of MCP Servers One container to replace Grafana + Loki + Tempo + Prometheus The Request/Response Cycle, HTTP, Auth, JWT, OAuth & Sessions — Explained Properly Python Week 3: We Stopped Repeating Ourselves (Loops!) Creating a Custom Grid Editor tool in Unreal Engine 我做了个付费 Telegram bot。Telegram Stars 实际给开发者多少钱,我算了一笔账。 I Got 96% Recall on LLM Hallucination Detection With No ML Model – Just 50 Lines of Python A practitioner's guide to getting more value out of AI coding: agent quality & token optimization How to Handle Telegram Albums in Telegraf I Built a Multilingual Spam Detection Dataset with 149K+ Messages Across 23 Languages How to Handle Telegram Albums in grammY RAG 시스템 실전 구축 (v38) Beyond Pip Install: Why Your AI Agent Needs a "Hermetic" Life-Support System to Survive Resume Building using HTML & CSS SpecFlow: Multi-Agent SDD in Cursor (4 phases, /approve, single code writer) Running ASR for smart homes in the NPU of Intel processors "Building a CI/CD Pipeline From Scratch: A Practical Guide for Developers (with GitHub Actions)" SpecFlow: SDD multi-agente en Cursor (4 fases, /approve, un solo escritor de código) How to Extract Your Full Team Hierarchy from HubSpot (the API doesn't expose it) Adobe Commerce Cloud now costs $40k/year. We migrated from Adobe Commerce to Magento Open Source — here's the honest breakdown .klickd v4.0.0 — Portable AI memory with constraints, strict schemas, and test vectors We Trust Third Party Code, It’s Time to Trust AI Generated Code LangGraph 워크플로우 템플릿 (v38) Sustainable AI Starts with Efficient AI Find Remove duplicated files in Google Drive How to Detect GPU Waste in a Kubernetes Cluster The Privacy Bug in My First Chrome Extension (And How to Avoid It) Serverless Mental Models: What They Don't Tell You Before You Build Preventing GPT hallucination in automated content pipelines: how I structure Make.com flows with data injection Hmm, where were we? AI Visibility Tools, Math Proofs, and Stripped Guardrails Shape Developer Landscape How AI and Electronics Are Changing Healthcare Devices: The Future of Smart Healthcare Author: Shivam Wakade | Founder, PrivSR Making Claude Sound Like Optimus Prime Understanding Reinforcement Learning with Human Feedback Part 5: Training the Reward Model with Loss Functions Learning Progress Pt.20 How Secure LoRa Communication Devices Work: Building the Future of Private and Long-Range Connectivity Author: Shivam Wakade | Founder, PrivSR How I Rebuilt an RPG Map Editor with Rust, React, and WASM Building a System That Automates YouTube Post-Production Building a 100% Serverless Digital Asset Packager in the Browser Game Recommended AI What is Human-In-The-Loop (HITL)? Deep Dive: React Server Components in TanStack Start Migrating off Google Analytics: Umami vs Plausible vs Fathom Building a Portfolio That Actually Demonstrates Software Engineering Async/Await in JavaScript: From Callbacks to Clean Code (2026) Benchmarking LLM Structured Outputs Angular 21 Multiselect Dropdown: A Migration-Friendly Component with Live Functional Tests ShareBox v5 — GPU transcoding, Netflix-style grid, and why I don't need Plex anymore TOML Schema is live Handling Duplicate Shopify Webhook Events (And Why You Must) Original Kubernetes Dashboard — retired upstream, upgraded to Angular 21. لماذا أسست ترينافو للتجار العرب الذين تتجاهلهم المنصات الغربية Construyendo un recomendador de películas en Python: de los datos al modelo When APIs Lie: A Lesson in Defensive Debugging Pope Leo XIV's AI Encyclical: What Builders Must Know (2026) Donna v0.3.0 HTB — MonitorsFour | Writeup The Free Tool You Trust Is the One You Should Fear the Most HTB — MonitorsFour | Writeup Fr 97. Embeddings and Vector Search: Semantic Search That Works Deep Dive: Building "Gravity Paint" - A Tactile Physics Instrument with React, Matter.js, and p5.js ABAP Unit Testing with Test Doubles and Mocking Frameworks: A Senior Architects Guide to Isolating Dependencies in SAP S/4HANA LeetCode Solution: 5. Longest Palindromic Substring kovax-react 0.8: Tailwind v4 preset, FormField adapters, ColorModeScript, and Storybook I built an AI résumé tool that refuses to lie about your experience The hat Azure Entra ID User & Role Management — Step-by-Step Practical Guide With A Simple Excercise The AI-Native Company: How a Single Founder Can Build Global Organizations Powered by AWS and an Ecosystem of Artificial Intelligences Building a Lightweight Remote MCP Knowledge Base on Cloudflare Workers Why I built Trinavo for the MENA merchants Western platforms ignore The N+1 Query That Killed Our Database, And How I Fixed It Docstrings vs Markdown Docs: What Should Developers Actually Write? Training Data Provenance: The Manifest Diff That Explains the Hash Add SVGIcons MCP to Claude Code and Find SVG Icons from Your Terminal 3 CLI Tools You Can Buy with Crypto — No KYC, No Subscriptions COSS Weekly: OpenClaw competitor NanoClaw Raises $12M, Dust Raises $40M, Sonar Acquires Gitar, and more How to know if you actually need mobile proxies (without buying any) Building Cursor for Community: A Buildathon Built on Time Pressure How we built a PII masking layer for LLM APIs — local detection, reversible tokens, one line to integrate Why MLFQ Was Way Ahead of Its Time Add Runtime Limits to Claude Agent Workflows I Built a Prompt Injection Detector with 98% Recall on Unseen Attacks. Here's Why Data Beat Architecture. 8 Vite Config Options Every Developer Should Know (Vite 8) Feature Flags That Forgot to Leave Why Trust Infrastructure Is Becoming the Hidden Layer of Donation Platforms XyPriss: Rethinking Core Performance and Zero-Trust Architecture in Modern Backends Designing Configuration for Scalable Treasure Hunts SSH Login Delays: The 10-Second Wait That Drives Us Crazy Building Production Multi-Agent Workflows in n8n: What 50 Deployments Taught Us A 3-layer memory system that gives Claude Code persistent context across sessions. Trishul SNMP Suite 2.0.1: Better MIBs, Traps, and SNMP Labs How I built a production AI SaaS as a solo developer Auto-labelling 1.2M robotics frames with VLMs: a failover story India’s Laws Were Not Built for AI — And Courts Are Filling the Gap skill-insp: A Skill That Scores Other Skills Clprolf Minimalist Messaging in the Age of AI What's actually in a good .cursorrules file? I built 10 of them — here's what I learned Building Strong Python Basics – Loops, Functions and Logic
LangGraph 워크플로우 템플릿 (v39)
matias yoon · 2026-05-26 · via DEV Community

LangGraph 워크플로우 템플릿 (v39)

LangGraph 아키텍처 개요

LangGraph는 상태 기반 워크플로우를 구현하기 위한 프레임워크로, 다음과 같은 핵심 구성 요소로 작동합니다:

Nodes (노드): 워크플로우의 각 단계. 각 노드는 특정 작업을 수행하고 상태를 업데이트합니다.

Edges (엣지): 노드 간의 전이 조건을 정의합니다.

State (상태): 워크플로우의 현재 상태를 유지합니다. 노드가 상태를 읽고 변경할 수 있습니다.

Checkpointing (체크포인팅): 상태를 저장하고 복원할 수 있어 중단 후 복구가 가능합니다.

from langgraph.graph import StateGraph
from typing import TypedDict, Annotated
import operator

class AgentState(TypedDict):
    messages: Annotated[list, operator.add]

# 기본 워크플로우 구성
workflow = StateGraph(AgentState)

Enter fullscreen mode Exit fullscreen mode

템플릿 1: 단순 RAG 에이전트

문서 검색 후 생성하고 검증하는 단순한 RAG 워크플로우입니다:

from langchain_core.messages import HumanMessage, AIMessage
from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplate

class RAGState(TypedDict):
    query: str
    documents: list
    response: str
    validated: bool

def retrieve(state: RAGState):
    # 문서 검색 로직
    documents = vector_store.similarity_search(state["query"])
    return {"documents": documents}

def generate(state: RAGState):
    # 생성 로직
    prompt = PromptTemplate.from_template(
        "Context: {context}\n\nQuestion: {query}\n\nAnswer:"
    )
    llm = ChatOpenAI(model="gpt-4")
    response = llm.invoke([
        ("system", "You are a helpful assistant."),
        ("user", prompt.format(
            context="\n".join([doc.page_content for doc in state["documents"]]),
            query=state["query"]
        ))
    ])
    return {"response": response.content}

def validate(state: RAGState):
    # 응답 검증
    # 간단한 예: 응답이 질문과 관련된 내용인지 확인
    return {"validated": True}

# 워크플로우 생성
rag_workflow = StateGraph(RAGState)
rag_workflow.add_node("retrieve", retrieve)
rag_workflow.add_node("generate", generate)
rag_workflow.add_node("validate", validate)

rag_workflow.add_edge("retrieve", "generate")
rag_workflow.add_edge("generate", "validate")
rag_workflow.set_entry_point("retrieve")
rag_workflow.set_finish_point("validate")

rag_app = rag_workflow.compile()

Enter fullscreen mode Exit fullscreen mode

템플릿 2: 다중 도구 에이전트

계획 → 실행 → 관찰 → 결정의 반복적인 루프:

from typing import List
import json

class ToolAgentState(TypedDict):
    task: str
    plan: List[str]
    execution_history: List[dict]
    final_answer: str

def plan(state: ToolAgentState):
    # 작업 계획 생성
    llm = ChatOpenAI(model="gpt-4")
    plan_prompt = PromptTemplate.from_template(
        "Break down the task '{task}' into specific steps. Format as JSON array of strings."
    )
    response = llm.invoke([
        ("system", "You are a task planning assistant."),
        ("user", plan_prompt.format(task=state["task"]))
    ])

    try:
        steps = json.loads(response.content)
        return {"plan": steps}
    except:
        return {"plan": [state["task"]]}

def execute(state: ToolAgentState):
    # 도구 실행
    execution_results = []

    for step in state["plan"]:
        # 예시: 각 단계에 대한 도구 실행 로직
        result = {"step": step, "status": "completed", "output": f"Result for {step}"}
        execution_results.append(result)

    return {"execution_history": execution_results}

def observe(state: ToolAgentState):
    # 실행 결과 관찰
    # 예: 성공/실패 여부 확인
    failed_steps = [
        step for step in state["execution_history"] 
        if step.get("status") == "failed"
    ]
    return {"execution_history": state["execution_history"]}

def decide(state: ToolAgentState):
    # 결정 로직
    if not state["execution_history"]:
        return {"final_answer": "No execution history available"}

    all_success = all(step.get("status") == "completed" 
                     for step in state["execution_history"])

    if all_success:
        return {"final_answer": "All tasks completed successfully"}
    else:
        return {"final_answer": "Some tasks failed"}

# 워크플로우 구성
tool_workflow = StateGraph(ToolAgentState)
tool_workflow.add_node("plan", plan)
tool_workflow.add_node("execute", execute)
tool_workflow.add_node("observe", observe)
tool_workflow.add_node("decide", decide)

tool_workflow.add_edge("plan", "execute")
tool_workflow.add_edge("execute", "observe")
tool_workflow.add_edge("observe", "decide")
tool_workflow.set_entry_point("plan")
tool_workflow.set_finish_point("decide")

tool_app = tool_workflow.compile()

Enter fullscreen mode Exit fullscreen mode

템플릿 3: 인간-중개 워크플로우

사용자 검토 후 진행하는 인간 인터페이스:

from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import MessagesState
import asyncio

class HumanReviewState(MessagesState):
    review_status: str
    review_comment: str

def pause_for_review(state: HumanReviewState):
    # 사용자 검토를 위한 일시정지
    return {"review_status": "pending"}

def review_process(state: HumanReviewState):
    # 검토 프로세스
    return {"review_status": "approved"}  # 또는 "rejected"

def continue_with_review(state: HumanReviewState):
    # 검토 후 진행
    if state["review_status"] == "rejected":
        return {"messages": [{"role": "assistant", "content": "Process rejected by human review"}]}
    return {"messages": [{"role": "assistant", "content": "Process continues after review"}]}

# 인간 검토 워크플로우
review_workflow = StateGraph(HumanReviewState)
review_workflow.add_node("pause", pause_for_review)
review_workflow.add_node("review", review_process)
review_workflow.add_node("continue", continue_with_review)

review_workflow.add_edge("pause", "review")
review_workflow.add_edge("review", "continue")
review_workflow.set_entry_point("pause")
review_workflow.set_finish_point("continue")

review_app = review_workflow.compile(checkpointer=MemorySaver())

Enter fullscreen mode Exit fullscreen mode

템플릿 5: 병렬 실행 에이전트

파이프라인에서 병렬 처리 후 집계:

from concurrent.futures import ThreadPoolExecutor
import time

class ParallelAgentState(TypedDict):
    data: List[str]
    processed_results: List[dict]
    aggregated_result: dict

def fan_out(state: ParallelAgentState):
    # 데이터를 병렬로 분할
    return {"processed_results": []}

def process_item(item: dict):
    # 각 항목 처리
    time.sleep(0.1)  # 시뮬레이션
    return {
        "id": item["id"],
        "processed": True,
        "result": f"Processed {item['data']}"
    }

def aggregate_results(state: ParallelAgentState):
    # 결과 집계
    results = state["processed_results"]
    total = len(results)
    successful = sum(1 for r in results if r.get("processed"))

    return {
        "aggregated_result": {
            "total_items": total,
            "successful": successful,
            "failed": total - successful
        }
    }

# 병렬 처리 워크플로우
parallel_workflow = StateGraph(ParallelAgentState)
parallel_workflow.add_node("fan_out", fan_out)
parallel_workflow.add_node("aggregate", aggregate_results)

parallel_workflow.add_edge("fan_out", "aggregate")
parallel_workflow.set_entry_point("fan_out")
parallel_workflow.set_finish_point("aggregate")

parallel_app = parallel_workflow.compile()

Enter fullscreen mode Exit fullscreen mode

상태 관리 패턴

1. 상태 초기화

def initialize_state():
    return {
        "messages": [],
        "timestamp": time.time(),
        "version": "v39",
        "metadata": {}
    }

# 상태 초기화 및 체크포인트
initial_state = initialize_state()

Enter fullscreen mode Exit fullscreen mode

2. 상태 병합

def merge_state(current_state, new_state):
    merged = current_state.copy()
    for key, value in new_state.items():
        if key in merged and isinstance(merged[key], list):
            merged[key].extend(value)
        else:
            merged[key] = value
    return merged

Enter fullscreen mode Exit fullscreen mode

3. 상태 유효성 검사


python
def validate_state(state):
    required_fields = ["messages", "timestamp"]
    for field in required_fields:
        if field not in state:
            raise ValueError(f"Missing required field: {field}")


---

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

Enter fullscreen mode Exit fullscreen mode