Fork Coding
Blog/February 25, 2026

LangChain으로 AI 기반 앱 구축하기

LangChain으로 AI 기반 앱 구축하기

LangChain과 Claude API를 활용하여 실용적인 AI 애플리케이션을 처음부터 구축하는 방법을 단계별로 알아봅니다.

Fork Coding·2026년 2월 25일
AILangChainClaudePython

AI 애플리케이션의 새로운 표준

LLM(Large Language Model)의 등장으로 AI 애플리케이션 개발이 크게 변화했습니다. 하지만 프로덕션 레벨의 AI 앱을 만들기 위해서는 단순한 API 호출 이상의 것이 필요합니다. LangChain은 이러한 복잡성을 추상화하여 개발자가 비즈니스 로직에 집중할 수 있게 해줍니다.

프로젝트 셋업

환경 구성

# 프로젝트 초기화
mkdir ai-assistant && cd ai-assistant
python -m venv .venv
source .venv/bin/activate

# 의존성 설치
pip install langchain langchain-anthropic python-dotenv

API 키 설정

# .env
ANTHROPIC_API_KEY=your-api-key-here

기본 체인 구성

LangChain의 핵심은 체인(Chain) 개념입니다. 여러 단계를 파이프라인으로 연결하여 복잡한 작업을 수행합니다.

from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

# 모델 초기화
model = ChatAnthropic(model="claude-sonnet-4-20250514")

# 프롬프트 템플릿 정의
prompt = ChatPromptTemplate.from_messages([
    ("system", "당신은 {domain} 분야의 전문가입니다. 간결하고 정확하게 답변하세요."),
    ("human", "{question}")
])

# 체인 구성 (LCEL - LangChain Expression Language)
chain = prompt | model | StrOutputParser()

# 실행
result = chain.invoke({
    "domain": "웹 개발",
    "question": "React Server Components의 주요 장점은?"
})
print(result)

RAG (Retrieval Augmented Generation) 구현

실제 프로덕션 앱에서 가장 많이 사용되는 패턴은 RAG입니다. 외부 문서를 검색하여 LLM에 컨텍스트로 제공합니다.

문서 로딩 및 벡터 저장소

from langchain_community.document_loaders import DirectoryLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import Chroma
from langchain_anthropic import AnthropicEmbeddings

# 1. 문서 로딩
loader = DirectoryLoader("./docs", glob="**/*.md")
documents = loader.load()

# 2. 텍스트 분할
splitter = RecursiveCharacterTextSplitter(
    chunk_size=1000,
    chunk_overlap=200,
)
chunks = splitter.split_documents(documents)

# 3. 벡터 저장소 생성
vectorstore = Chroma.from_documents(
    documents=chunks,
    embedding=AnthropicEmbeddings(),
    persist_directory="./chroma_db"
)

RAG 체인 구성

from langchain_core.runnables import RunnablePassthrough

# 리트리버 생성
retriever = vectorstore.as_retriever(
    search_type="similarity",
    search_kwargs={"k": 5}
)

# RAG 프롬프트
rag_prompt = ChatPromptTemplate.from_messages([
    ("system", """다음 컨텍스트를 기반으로 질문에 답변하세요.
컨텍스트에 없는 내용은 모른다고 답변하세요.

컨텍스트:
{context}"""),
    ("human", "{question}")
])

# RAG 체인
rag_chain = (
    {"context": retriever, "question": RunnablePassthrough()}
    | rag_prompt
    | model
    | StrOutputParser()
)

# 질문
answer = rag_chain.invoke("프로젝트의 배포 방법은?")

에이전트 구축

LangChain 에이전트는 LLM이 도구(Tool)를 선택적으로 사용하여 작업을 수행합니다.

from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.tools import tool

@tool
def search_documentation(query: str) -> str:
    """프로젝트 문서에서 정보를 검색합니다."""
    docs = retriever.invoke(query)
    return "\n".join(doc.page_content for doc in docs)

@tool
def calculate(expression: str) -> str:
    """수학 계산을 수행합니다."""
    return str(eval(expression))

# 에이전트 생성
agent = create_tool_calling_agent(
    llm=model,
    tools=[search_documentation, calculate],
    prompt=ChatPromptTemplate.from_messages([
        ("system", "도구를 활용하여 사용자의 질문에 답변하세요."),
        ("human", "{input}"),
        ("placeholder", "{agent_scratchpad}"),
    ])
)

executor = AgentExecutor(agent=agent, tools=[search_documentation, calculate])
result = executor.invoke({"input": "배포 비용이 월 50달러일 때 연간 비용은?"})

프로덕션 팁

1. 스트리밍 응답

사용자 경험을 위해 스트리밍은 필수입니다:

async for chunk in rag_chain.astream("질문"):
    print(chunk, end="", flush=True)

2. 에러 핸들링과 재시도

from langchain_core.runnables import RunnableWithFallbacks

# 폴백 모델 설정
primary = ChatAnthropic(model="claude-sonnet-4-20250514")
fallback = ChatAnthropic(model="claude-haiku-4-5-20251001")

robust_model = primary.with_fallbacks([fallback])

3. 비용 최적화

마치며

LangChain은 AI 애플리케이션 개발의 복잡성을 크게 줄여주지만, 기본 원리를 이해하는 것이 중요합니다. 프롬프트 엔지니어링, 벡터 검색, 에이전트 패턴의 기초를 잘 다지면, 어떤 프레임워크를 사용하더라도 효과적인 AI 앱을 만들 수 있습니다.