12.2 Chain, Agent, Memory의 실전 예제
Chapter 12.2 Chain, Agent, Memory의 실전 예제
이번 절에서는 LangChain의 핵심 구성요소 중 하나인 Chain, Agent, Memory의 원리를 실제 예제와 함께 자세히 설명합니다. 앞선 절(12.1)에서 LangChain의 전체 아키텍처를 다뤘다면, 본 절에서는 코드 기반의 실습을 통해 이 개념들이 실제 애플리케이션에 어떻게 활용되는지를 체감할 수 있도록 구성했습니다.
📘 주요 학습 키포인트:
Chain과 PromptTemplate, LLMChain의 기본 구조와 동작방식
Agent이 외부 도구와 협업하며 문제를 해결하는 방식
Memory를 활용한 대화를 유지하는 챗봇 설계
실전 예제를 통한 전체 흐름 파악 및 코드 구현
12.2.1 Basic Chain 사용 예제: LLMChain으로 간단한 변환기 만들기
LangChain의 핵심 모듈은 Chain입니다. 가장 널리 활용되는 기본 Chain은 LLMChain으로, LLM + PromptTemplate의 결합체입니다.
🧪 예제: 사용자가 입력한 영어 문장을 프랑스어로 번역해주는 LLMChain
목표: "How are you today?" → "Comment allez-vous aujourd'hui ?"
먼저 필요한 패키지를 설치합니다.
pip install openai langchain
🔧 코드 예제:
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
# 1. LLM 준비
llm = OpenAI(temperature=0, model_name='gpt-3.5-turbo-instruct')
# 2. 프롬프트 템플릿
prompt = PromptTemplate(
input_variables=["english_sentence"],
template="Translate the following English sentence to French:\n{english_sentence}"
)
# 3. LLMChain 생성
chain = LLMChain(llm=llm, prompt=prompt)
# 4. 실행
result = chain.run("How are you today?")
print(result)
📌 설명:
PromptTemplate은 사용자의 입력을 LLM에 전달할 프롬프트 형태로 템플릿화합니다.
LLMChain은 LLM + PromptTemplate을 결합해 실행 가능한 체인을 만듭니다.
run() 메서드를 통해 입력값을 넣으면, GPT 모델이 결과를 반환합니다.
12.2.2 Agent 예제: 계산기와 검색을 함께 사용하는 지능형 에이전트
Chain은 고정된 흐름을 따르지만, Agent는 툴에 따라 유동적으로 행동 방식을 결정합니다. 에이전트는 질문을 받고, 작동에 적절한 도구(tool)를 스스로 선택하여 작업을 수행합니다.
LangChain에서 Agent는 다음과 같은 툴을 사용할 수 있습니다:
계산기(Calculator)
검색(Search)
외부 API 호출기
코드 실행기(Python REPL)
🧪 예제: 수식 계산 + 위키 검색이 가능한 Agent 구현
목표: "뉴턴이 태어난 해에 루트 256은 얼마인가?"
🔧 코드 예제:
from langchain.agents import initialize_agent, Tool
from langchain.agents.agent_types import AgentType
from langchain.tools import SerpAPIWrapper, Calculator
from langchain.llms import OpenAI
# LLM 설정
llm = OpenAI(temperature=0)
# 사용할 도구 설정
search = SerpAPIWrapper() # 서치 툴 (SerpAPI 키 필요)
calculator = Calculator()
tools = [
Tool(name="Search", func=search.run, description="Useful for current events or historical facts"),
Tool(name="Calculator", func=calculator.run, description="Useful for math calculations")
]
# 에이전트 초기화
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
# 실행
response = agent.run("What is the square root of 256 in the year Newton was born?")
print(response)
📌 설명:
Agent는 사용자의 질문을 분석한 후 필요한 도구(계산기, 검색 등)를 조합해 작업을 수행합니다.
LangChain은 REAct 방식의 추론(express reasoning and acting) 기반으로 동작하며, 각 단계의 reasoning 과정을 출력합니다.
🧠 작동 과정 예시 출력:
Thought: I need to find the year Newton was born
Action: Search
Observation: Isaac Newton was born in 1643
Thought: Now I calculate √256
Action: Calculator
Observation: 16
Final Answer: Isaac Newton was born in 1643 and the square root of 256 is 16.
12.2.3 Memory 예제: 대화형 챗봇 만들기
이전 예제에서 에이전트와 체인은 각각 개별 응답에 대해 작동하지만, 사용자의 대화 맥락을 기억하지 못합니다. Memory를 사용하면 사용자와의 이전 대화를 유지할 수 있으며, 더 자연스러운 챗봇 인터페이스 구현이 가능합니다.
LangChain은 다양한 Memory 클래스를 제공합니다:
ConversationBufferMemory: 대화의 전체 히스토리를 유지
ConversationSummaryMemory: 대화 내용을 요약 형태로 보관
ConversationBufferWindowMemory: 최근 N개 대화만 유지
🧪 예제: 대화 상태를 기억하는 챗봇
🔧 코드 예제:
from langchain.chains import ConversationChain
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
# GPT-3.5 turbo 기반 Chat LLM
chat_llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo")
# 메모리 설정
memory = ConversationBufferMemory()
# 대화형 체인 생성
conversation = ConversationChain(
llm=chat_llm,
memory=memory,
verbose=True
)
# 대화 시뮬레이션
print(conversation.predict(input="Hello, my name is John."))
print(conversation.predict(input="What is my name?"))
📌 결과 예시:
> Hello, my name is John.
Hi John, how can I assist you today?
> What is my name?
Your name is John.
📌 설명 및 주요 포인트:
Memory는 이전 대화 내용을 LLM에게 넣어줌으로써 맥락을 유지하게 합니다.
ConversationBufferMemory는 대화를 누적하고 prompt에 함께 포함합니다.
사용자마다 세션 ID 등으로 메모리를 분리하면 멀티유저 환경에 적합합니다.
📌 확장 아이디어:
ConversationSummaryMemory 사용: 긴 대화를 요약하여 프롬프트에 과도하게 긴 기록이 포함되는 것을 방지
사용자 프로파일 기억: "내 생일은 3월 3일이야" → "내 생일까지 며칠 남았지?"
✍️ 마무리 정리
Chain
고정된 프롬프트와 처리 흐름
LLMChain, ConversationChain
번역기
Agent
외부 도구와의 조율
initialize_agent, Tool, AgentType
계산 + 검색
Memory
대화 컨텍스트 저장 및 활용
ConversationBufferMemory, ...
사용자 이름 기억
LangChain의 Chain, Agent, Memory는 조합하여 훨씬 강력하고 유연한 AI 기능을 구현할 수 있습니다. 다음 절에서는 이러한 구성요소를 하나로 통합하여 실제 업무에서 활용 가능한 RAG(Retrieval-Augmented Generation) 시스템을 만들어보겠습니다.
Last updated