주뇽's 저장소

Part 4: LangGraph의 Human-in-the-Loop 구현하기 - AI와 사람의 협업 🤝 본문

LangGraph

Part 4: LangGraph의 Human-in-the-Loop 구현하기 - AI와 사람의 협업 🤝

뎁쭌 2025. 1. 18. 22:25
728x90
반응형

Part 4: LangGraph의 Human-in-the-Loop 구현하기 - AI와 사람의 협업 🤝

LangGraph를 활용하여 AI와 사람이 효과적으로 협업하는 시스템을 구현하는 방법을 알아본다. 이번 글에서는 중요한 결정이나 검토가 필요할 때 사람의 승인을 받는 워크플로우를 구현한다.

1. Human-in-the-Loop란? 🎯

AI 시스템에서 Human-in-the-Loop는 AI의 판단이나 작업에 사람이 개입하여 검토하고 승인하는 프로세스를 말한다. 이를 통해:

  • 중요한 결정에 대한 안전성 확보
  • AI의 실수 방지
  • 품질 관리 강화

2. 코드 구현하기 💻

2.1 기본 설정

import os
from dotenv import load_dotenv
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langchain_openai import ChatOpenAI
from langchain_community.tools.tavily_search import TavilySearchResults
from langgraph.prebuilt import ToolNode, tools_condition
from langgraph.checkpoint.memory import MemorySaver
from langgraph.types import Command, interrupt
from langchain_core.tools import tool

load_dotenv()

class State(TypedDict):
    messages: Annotated[list, add_messages]

2.2 사람 도움 요청 도구 구현

@tool
def human_assistance(query: str) -> str:
    """사람의 도움을 요청하는 도구"""
    human_response = interrupt({"query": query})
    return human_response["data"]

2.3 그래프 설정

def setup_graph():
    memory = MemorySaver()
    graph_builder = StateGraph(State)

    # 도구 설정
    search_tool = TavilySearchResults(max_results=2)
    tools = [search_tool, human_assistance]

    # AI 모델 설정
    llm = ChatOpenAI(
        model="gpt-4",
        temperature=0.7,
        streaming=True
    )
    llm_with_tools = llm.bind_tools(tools)

    # 노드와 엣지 설정
    ...

    return graph_builder.compile(checkpointer=memory)

3. 주요 사용 사례 📱

3.1 코드 안전성 검토

test_chatbot(graph, "이 코드가 안전한지 검토해주세요: import os; os.system('rm -rf /')")

실행 결과:

😀 사용자: 이 코드가 안전한지 검토해주세요
🤖 AI: 코드를 검토하기 위해 전문가의 확인이 필요합니다.
👋 사람의 확인이 필요합니다!

3.2 중요 데이터 작업 승인

test_chatbot(graph, "중요한 데이터베이스를 삭제하려고 합니다")

3.3 금융 거래 승인

test_chatbot(graph, "이 거래를 승인해도 될까요? 금액: $10,000")

4. 작동 원리 설명 ⚙️

  1. AI의 판단
    • AI가 중요한 결정이 필요한 상황 감지
    • human_assistance 도구 호출
  2. 워크플로우 중단
    • interrupt 함수로 실행 일시 중지
    • 사람의 입력 대기
  3. 사람의 개입
    • 상황 검토 및 판단
    • 승인 또는 거절 결정
  4. 처리 재개
    • 사람의 결정을 반영
    • 워크플로우 계속 진행

5. 주요 특징 🌟

  1. 안전성
    • 중요 결정에 대한 이중 확인
    • 실수 방지 메커니즘
  2. 유연성
    • 다양한 상황에 대한 대응 가능
    • 커스터마이징 용이
  3. 추적성
    • 모든 결정 과정 기록
    • 검토 및 감사 가능

6. 활용 방안 💡

  1. 보안 시스템
    • 코드 검토
    • 접근 권한 승인
  2. 금융 시스템
    • 대규모 거래 승인
    • 위험 거래 감지
  3. 콘텐츠 관리
    • 콘텐츠 검수
    • 게시물 승인

7. 발전 방향 🚀

  1. 웹 인터페이스 추가
  2. # 예시 코드 def web_interface(): from flask import Flask, request app = Flask(__name__) @app.route('/approve', methods=['POST']) def approve(): # 승인 로직 구현 pass
  3. 승인 프로세스 다각화
    • 다중 승인자 시스템
    • 단계별 승인 프로세스

이렇게 LangGraph의 Human-in-the-Loop 기능을 활용하면 AI와 사람이 효과적으로 협업하는 시스템을 구축할 수 있다. 다음 글에서는 상태 관리를 수동으로 제어하는 방법에 대해 알아본다. 🎯

 

참고 : https://github.com/junyong1111/LangGraph/tree/main/example4

 

LangGraph/example4 at main · junyong1111/LangGraph

Contribute to junyong1111/LangGraph development by creating an account on GitHub.

github.com

참고 : https://langchain-ai.github.io/langgraph/tutorials/introduction/#part-4-human-in-the-loop

 

Learn the basics

Home Guides Tutorials Quick Start 🚀 LangGraph Quickstart In this tutorial, we will build a support chatbot in LangGraph that can: ✅ Answer common questions by searching the web ✅ Maintain conversation state across calls ✅ Route complex queries to

langchain-ai.github.io