1. ํ์ ์ฌ์ ์๊ฑด & ์์คํ ์๊ตฌ์ฌ์ (Prerequisites & System Requirements)
๐ ์ด๋ณด์ ๋๋์ด์ ์น์ ํ ๋จ๊ณ๋ณ ์ค์ต ํํ ๋ฆฌ์ผ ์๋ด:
1๊ฐ๋ถํฐ 5๊ฐ๊น์ง ์ฐจ๊ทผ์ฐจ๊ทผ ๋ฐ๋ผ ํ๋ฉฐ ๋๋ง์ ์ฌ๋ด RAG ์ฑ๋ด๊ณผ ์์จ ์์ด์ ํธ๋ฅผ ์์ฑํ๋ ํธ์ฆ์จ ํํ ๋ฆฌ์ผ์ **LangChain ์ค๋ฌด ๋ง์คํฐ ํํ ๋ฆฌ์ผ ๋ฐ๋ก๊ฐ๊ธฐ โ**์์ ํ์ตํ์ค ์ ์์ต๋๋ค.
๐ป ์์คํ ์ค์น ๋ฐ ์คํ ์๊ตฌ์ฌ์ (System Requirements)
| ํญ๋ชฉ | ์ต์ ์ฌ์ (Minimum) | ๊ถ์ฅ ์ฌ์ (Recommended) | ์ฐธ๊ณ ๋ฐ ๋น๊ณ |
|---|---|---|---|
| ์ด์์ฒด์ (OS) | Windows 10/11 64-bit, macOS 13+, Linux (Ubuntu 22.04 LTS+) | Windows 11 ๋๋ macOS (Apple Silicon M-Series) / Ubuntu 24.04 LTS | ํฌ๋ก์ค ํ๋ซํผ ์ง์ |
| CPU | 4 ์ฝ์ด ์ด์ (x86_64 ๋๋ ARM64) | 8 ์ฝ์ด ~ 16 ์ฝ์ด ์ด์ (AMD Ryzen 7 / Intel Core i7 / Apple M-Series) | ์๋ฒ ๋ฉ ์ฐ์ฐ ๋ฐ ๋ก์ปฌ LLM ์ถ๋ก |
| ๋ฉ๋ชจ๋ฆฌ (RAM) | 8 GB ์ด์ (์ธ๋ถ API ํธ์ถ ์ค์ฌ) | 16 GB ~ 32 GB ์ด์ (๋ก์ปฌ Ollama ๋ชจ๋ธ ๋ฐ ์ธ๋ฉ๋ชจ๋ฆฌ VectorDB ๊ตฌ๋) | ๋ก์ปฌ 4B~8B LLM ๊ตฌ๋ ์ 16GB+ ํ์ |
| ๋์คํฌ (Storage) | 10 GB ์ด์์ ์ฌ์ ๊ณต๊ฐ | 30 GB ~ 50 GB ์ด์์ ๊ณ ์ NVMe SSD | Python venv, ํ๊น ํ์ด์ค ์บ์, Ollama ๊ฐ์ค์น |
| ๋คํธ์ํฌ / ๋ฐํ์ | Python 3.11+ ~ 3.13 (๊ถ์ฅ: Python 3.12 / 3.13) | ์ธ๋ถ LLM API ํค (OpenAI / Gemini / Claude) ๋๋ ๋ก์ปฌ Ollama | Python 3.10 ์ดํ๋ LangGraph v0.2+ ํธํ ์ ์ฝ |
๐ Python 3.12+ ๊ฐ์ํ๊ฒฝ ์์ฑ ๋ฐ ํ์ฑํ
์ ์ญ ํจํค์ง ๋ฒ์ ์ถฉ๋์ ์์ฒ ์ฐจ๋จํ๊ธฐ ์ํด ๋ ๋ฆฝ๋ ํ์ด์ฌ ๊ฐ์ํ๊ฒฝ์ ์์ฑํฉ๋๋ค:
# [๋ฐฉ๋ฒ A] ํ์ค venv ๊ฐ์ํ๊ฒฝ ์์ฑ
python -m venv .venv
# ๊ฐ์ํ๊ฒฝ ํ์ฑํ (Windows PowerShell)
# โป ์ต์ด 1ํ ๊ถํ ํ์ฉ: Set-ExecutionPolicy Unrestricted -Scope Process
.venv\Scripts\Activate.ps1
# ๊ฐ์ํ๊ฒฝ ํ์ฑํ (macOS / Linux / WSL)
source .venv/bin/activate
# [๋ฐฉ๋ฒ B] ์ฐจ์ธ๋ ์ด๊ณ ์ ํจํค์ง ๊ด๋ฆฌ์ uv ์ฌ์ฉ ์ (๊ถ์ฅ)
pip install uv
uv venv
# Windows: .venv\Scripts\activate / macOS: source .venv/bin/activate
๐ฆ ํต์ฌ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ผ๊ด ์ค์น
# 1. LangChain ์ฝ์ด ๋ฐ ์ต์ LangGraph ํ๋ ์์ํฌ ์ค์น
pip install langchain langchain-core langchain-community langgraph
# 2. ์ ํธํ๋ LLM ๊ณต๊ธ์ ํจํค์ง ์ค์น
pip install langchain-openai # OpenAI (GPT-4o, GPT-4o-mini)
pip install langchain-google-genai # Google Gemini (gemini-2.0-flash)
pip install langchain-anthropic # Anthropic Claude (claude-3-5-sonnet)
pip install langchain-ollama # ๋ก์ปฌ ๋ฌด๋ฃ ์คํ๋ผ์ธ ๋ชจ๋ธ ์ฐ๋
# 3. ๋ฐ์ดํฐ ๊ฒ์ฆ, ํ๊ฒฝ๋ณ์, ํ
์คํธ ๋ถํ ๋๊ตฌ
pip install pydantic python-dotenv tiktoken
# 4. RAG ๋ฒกํฐ ์ ์ฅ์ ๋ฐ ์๋น ํ๋ ์์ํฌ (์ ํ)
pip install chromadb faiss-cpu fastapi uvicorn
๐ ํ๊ฒฝ ๋ณ์ ๊ตฌ์ฑ (.env)
ํ๋ก์ ํธ ๋ฃจํธ ๋๋ ํฐ๋ฆฌ์ .env ํ์ผ์ ์์ฑํ๊ณ ์ฌ์ฉํ API ํค๋ฅผ ์ค์ ํฉ๋๋ค:
# -----------------------------------------------------------------------------
# 1. ์จ๋ผ์ธ ์์ฉ LLM ๊ณต๊ธ์ API ํค (์ฌ์ฉํ ๊ณต๊ธ์๋ง ์
๋ ฅ)
# -----------------------------------------------------------------------------
OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
GOOGLE_API_KEY=AIzaSyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# -----------------------------------------------------------------------------
# 2. ๋ก์ปฌ ๋ฌด๋ฃ ์คํ๋ผ์ธ LLM (Ollama) ์ฐ๋ ์ฃผ์
# -----------------------------------------------------------------------------
LOCAL_LLM_URL=http://localhost:11434/v1
LOCAL_LLM_MODEL=qwen2.5:7b
# -----------------------------------------------------------------------------
# 3. LangSmith ํ๋ก๋์
ํธ๋ ์ด์ฑ & ๋ชจ๋ํฐ๋ง (์ ํ)
# -----------------------------------------------------------------------------
LANGCHAIN_TRACING_V2=false
LANGCHAIN_ENDPOINT=https://api.smith.langchain.com
LANGCHAIN_API_KEY=lsv2_pt_xxxxxxxxxxxxxxxxxxxxxxxx
LANGCHAIN_PROJECT=LuckyLangChain-Production
2. LangChain & LangGraph ์ ์ฒด ์ํคํ ์ฒ ๋ฉํ ๋ชจ๋ธ
LangChain ์ค๋ฌด ์ํ๊ณ๋ 5๋จ๊ณ ๊ณ์ธต์ผ๋ก ๊ตฌ์ฑ๋์ด ์์ผ๋ฉฐ, ๋จ์ API ๋ํผ๋ฅผ ๋์ด **์ง์ ๊ฒ์(RAG) โ ์ธ๋ถ ๋๊ตฌ ํ๋(Tool Calling) โ ์์จ ์ ์ด(LangGraph) โ ์ด์ ์๋น(MLOps)**์ผ๋ก ์ ์ง ํ์ฅ๋ฉ๋๋ค.
๐บ๏ธ ์ ์ฒด 5๋จ๊ณ ๋ก๋๋งต ์ํคํ ์ฒ
flowchart TD
subgraph Phase1["1๋จ๊ณ: ํ์ด๋ฐ์ด์
& LCEL"]
P1_Prompt["ChatPromptTemplate<br/>(๋์ ๋ณ์ ์ฃผ์
)"]
P1_Model["ChatModel<br/>(OpenAI/Gemini/Ollama)"]
P1_Parser["StrOutputParser / Pydantic<br/>(์ ํ ๋ฐ์ดํฐ ์ถ์ถ)"]
P1_Pipe["LCEL ํ์ดํ ์ฐ์ฐ์ '|'<br/>chain = prompt | model | parser"]
P1_Prompt --> P1_Pipe
P1_Model --> P1_Pipe
P1_Parser --> P1_Pipe
end
subgraph Phase2["2๋จ๊ณ: ์ง์ ํ์ฅ (RAG)"]
P2_Load["๋ฌธ์ ์ ์ฌ (Load)<br/>์ฌ๋ด ๊ท์ /๋ณด์ ์ง์นจ"]
P2_Split["์ฒญํน (TextSplitter)<br/>chunk_size=180, overlap=30"]
P2_Store["์์ธ (VectorStore)<br/>InMemory / Chroma / BM25"]
P2_Retriever["๊ฒ์ (Retriever)<br/>๊ณ ์ ๋ฐ BM25AccurateRetriever"]
P2_Load --> P2_Split --> P2_Store --> P2_Retriever
end
subgraph Phase3["3๋จ๊ณ: ํ๋ ์ ์ด (Tools)"]
P3_ToolDef["@tool ๋ฐ์ฝ๋ ์ดํฐ<br/>์ฌ๋ด DB์กฐํ / ์ธ๊ธ๊ณ์ฐ"]
P3_Bind["model.bind_tools()<br/>ํจ์ ํธ์ถ ๊ท๊ฒฉ ๋ฐ์ธ๋ฉ"]
P3_Exec["JSON ์ง์์(tool_calls)<br/>โ ์ค์ ํ์ด์ฌ ํจ์ ์คํ"]
P3_ToolDef --> P3_Bind --> P3_Exec
end
subgraph Phase4["4๋จ๊ณ: ์์จํ ์์ด์ ํธ (LangGraph)"]
P4_State["MessagesState (์ํ ๋ณด์กด)"]
P4_Agent["Agent ๋
ธ๋ (์ฌ๊ณ ๋ฐ ์ถ๋ก )"]
P4_Cond{"๋๊ตฌ ํธ์ถ์ด<br/>ํ์ํ๊ฐ?"}
P4_ToolNode["Tools ๋
ธ๋ (๋๊ตฌ ์ค์ ์คํ)"]
P4_State --> P4_Agent --> P4_Cond
P4_Cond -- "๋๊ตฌ ์คํ ํ์" --> P4_ToolNode
P4_ToolNode -->|๊ด์ฐฐ ๊ฒฐ๊ณผ Observe| P4_Agent
P4_Cond -- "๋ชฉํ ๋ฌ์ฑ" --> P4_End([END])
end
subgraph Phase5["5๋จ๊ณ: MLOps & ํ๋ก๋์
์๋น"]
P5_Trace["LangSmith ํธ๋ ์ด์ฑ<br/>(ํ ํฐ ๋น์ฉ/์ง์ฐ ์๊ฐ ์๊ฐํ)"]
P5_Eval["LLM-as-a-Judge ํ๊ฐ<br/>(๊ทผ๊ฑฐ์ฑ Groundedness / ์ ํฉ๋)"]
P5_FastAPI["FastAPI ๋น๋๊ธฐ ์คํธ๋ฆฌ๋ฐ<br/>(SSE ํ์ดํ ํจ๊ณผ ์๋น)"]
end
Phase1 --> Phase2 --> Phase3 --> Phase4 --> Phase5
3. [1๊ฐ] LangChain ํ์ด๋ฐ์ด์ & LCEL ๊ธฐ์ด
๐ก ํต์ฌ ๊ฐ๋ : ์ ๋จ์ API ํธ์ถ ๋์ LangChain์ธ๊ฐ?
- ๋จ์ผ ์ธํฐํ์ด์ค ์ถ์ํ: ์ฝ๋ ํ ์ค๋ง ๋ฐ๊พธ๋ฉด Google Gemini โ OpenAI GPT-4o โ ๋ก์ปฌ Ollama ๋ชจ๋ธ๋ก ์์ ๋กญ๊ฒ ๊ต์ฒด ๊ฐ๋ฅ.
- LCEL (LangChain Expression Language): ์ ๋์ค ํ์ดํ(
|) ์ฐ์ฐ์๋ฅผ ํตํด ์ปดํฌ๋ํธ๋ฅผ ๊ฒฐํฉํ์ฌ ์คํธ๋ฆฌ๋ฐ, ๋น๋๊ธฐ ํธ์ถ, ๋ณ๋ ฌ ์คํ์ ๊ธฐ๋ณธ ์ง์. - 3๋ ํต์ฌ ์ปดํฌ๋ํธ:
ChatPromptTemplate: ์ญํ (system,human,ai) ๋ถ๋ฆฌ ๋ฐ ๋์ ํ๋ผ๋ฏธํฐ ์ฃผ์ .ChatModel: ์ธ์ด ๋ชจ๋ธ ๊ฐ์ฒด.OutputParser: ์์AIMessage์์ ์์ ํ ์คํธ(StrOutputParser) ๋๋ Pydantic ๊ฐ์ฒด ์ถ์ถ.
[์ด๋ณด์ 1๋จ๊ณ] ์ฒซ ๋ฒ์งธ LCEL ์ฒด์ธ ์กฐ๋ฆฝ & 3๋ ์คํ ๋ฐฉ์
API ํค๊ฐ ์ค์ ๋์ด ์์ผ๋ฉด ์ค์ ํด๋ผ์ฐ๋ ๋ชจ๋ธ์, API ํค๊ฐ ์์ด๋ FakeListChatModel๋ก ๋น์ฉ 0์์ 100% ๋์ผํ๊ฒ ๋์ํ๋ ์์ ํ ์คํ ์ฝ๋์
๋๋ค:
# 01_first_chain.py
import os
from dotenv import load_dotenv
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_community.chat_models import FakeListChatModel
load_dotenv()
def get_chat_model():
"""์ฌ์ฉ ๊ฐ๋ฅํ API ํค๋ฅผ ๊ฐ์งํ์ฌ ๋ชจ๋ธ์ ์ด๊ธฐํํ๊ฑฐ๋ ๊ต์ก์ฉ Fake ๋ชจ๋ธ์ ๋ฐํ"""
if os.getenv("GOOGLE_API_KEY"):
from langchain_google_genai import ChatGoogleGenerativeAI
return ChatGoogleGenerativeAI(model="gemini-2.0-flash")
if os.getenv("OPENAI_API_KEY"):
from langchain_openai import ChatOpenAI
return ChatOpenAI(model="gpt-4o-mini")
if os.getenv("ANTHROPIC_API_KEY"):
from langchain_anthropic import ChatAnthropic
return ChatAnthropic(model="claude-3-5-sonnet-20241022")
# API ํค๊ฐ ์์ ๋์ ํ
์คํธ์ฉ ์๋ฎฌ๋ ์ด์
๋ชจ๋ธ
return FakeListChatModel(responses=[
"1. ์ปดํฌ๋ํธ ๋ชจ๋ํ: ๋ ๊ณ ๋ธ๋ก์ฒ๋ผ ์กฐ๋ฆฝ ๊ฐ๋ฅ\n2. LCEL ํ์ดํ๋ผ์ธ: ์ง๊ด์ ์ธ ์ฐ๊ฒฐ\n3. ์ค์๊ฐ ์คํธ๋ฆฌ๋ฐ ์ง์",
"1. ๋น ๋ฅธ ํ๋กํ ํ์ดํ: ๋จ ๋ช ์ค๋ก RAG ๊ตฌ์ถ\n2. ๋ฉํฐ ๋ชจ๋ธ ์ง์: ์ ์ฐํ ๊ต์ฒด\n3. LangGraph ํ์ฅ์ฑ",
"1. ๋จ์ผ invoke: ์ฆ์ ๊ฒฐ๊ณผ ๋ฐํ\n2. ์ค์๊ฐ stream: ํ ํฐ ๋จ์ ์ ๋ฌ\n3. ๋ณ๋ ฌ batch: ๋๋ ์์ฒญ ์ฒ๋ฆฌ"
])
# 1. ํ๋กฌํํธ ํ
ํ๋ฆฟ ์ ์
prompt = ChatPromptTemplate.from_messages([
("system", "๋น์ ์ AI ๊ธฐ์ ์ ์ฝ๊ฒ ๊ฐ๋ฅด์ณ์ฃผ๋ ์์ ์ํคํ
ํธ์
๋๋ค."),
("human", "{topic}์ ํต์ฌ ์ฅ์ 3๊ฐ์ง๋ฅผ ๋ถ๋ฆฟ ํฌ์ธํธ๋ก ์๋ ค์ค.")
])
# 2. ๋ชจ๋ธ ๋ฐ ์ถ๋ ฅ ํ์ ์ด๊ธฐํ
model = get_chat_model()
parser = StrOutputParser()
# 3. LCEL ์ฒด์ธ ์กฐ๋ฆฝ (Prompt -> Model -> Parser)
chain = prompt | model | parser
# [์คํ ๋ฐฉ์ 1] ๋จ์ผ ๋๊ธฐ ์คํ (.invoke)
print("=== 1. invoke() ๋จ์ผ ์คํ ===")
res = chain.invoke({"topic": "LangChain ํ๋ ์์ํฌ"})
print(res)
# [์คํ ๋ฐฉ์ 2] ์ค์๊ฐ ์คํธ๋ฆฌ๋ฐ (.stream)
print("\n=== 2. stream() ์ค์๊ฐ ํ์ดํ ===")
for chunk in chain.stream({"topic": "FastAPI ๋ฐฑ์๋"}):
print(chunk, end="", flush=True)
print()
# [์คํ ๋ฐฉ์ 3] ๋ณ๋ ฌ ๋ฐฐ์น ์ผ๊ด ์ฒ๋ฆฌ (.batch)
print("\n=== 3. batch() ๋ณ๋ ฌ ์ฒ๋ฆฌ ===")
batch_results = chain.batch([
{"topic": "Docker ์ปจํ
์ด๋"},
{"topic": "Kubernetes ์ค์ผ์คํธ๋ ์ด์
"}
])
for idx, result in enumerate(batch_results, 1):
print(f"\n[๊ฒฐ๊ณผ {idx}]\n{result}")
๐ฅ๏ธ ์คํ ์์ ๊ฒฐ๊ณผ (Output)
=== 1. invoke() ๋จ์ผ ์คํ ===
1. ์ปดํฌ๋ํธ ๋ชจ๋ํ: ๋ ๊ณ ๋ธ๋ก์ฒ๋ผ ์กฐ๋ฆฝ ๊ฐ๋ฅ
2. LCEL ํ์ดํ๋ผ์ธ: ์ง๊ด์ ์ธ ์ฐ๊ฒฐ
3. ์ค์๊ฐ ์คํธ๋ฆฌ๋ฐ ์ง์
=== 2. stream() ์ค์๊ฐ ํ์ดํ ===
1. ๋น ๋ฅธ ํ๋กํ ํ์ดํ: ๋จ ๋ช ์ค๋ก RAG ๊ตฌ์ถ
2. ๋ฉํฐ ๋ชจ๋ธ ์ง์: ์ ์ฐํ ๊ต์ฒด
3. LangGraph ํ์ฅ์ฑ
=== 3. batch() ๋ณ๋ ฌ ์ฒ๋ฆฌ ===
[๊ฒฐ๊ณผ 1]
1. ๊ฒฉ๋ฆฌ๋ ํ๊ฒฝ: ์ด๋์๋ ์ผ๊ด๋ ์คํ
2. ๋น ๋ฅธ ๋ฐฐํฌ: ๊ฒฝ๋ ์ด๋ฏธ์ง ๊ธฐ๋ฐ ๊ธฐ๋
3. ๋ฆฌ์์ค ํจ์จ์ฑ: OS ๊ฐ์ํ ์ค๋ฒํค๋ ์ต์ํ
[2๋จ๊ณ] Pydantic ๊ธฐ๋ฐ ๊ตฌ์กฐํ๋ ๋ฐ์ดํฐ ์ถ์ถ (Structured Output)
์ค๋ฌด ์๋น์ค์์๋ AI์ ์์ ๋ก์ด ์ค๊ธ ๋ต๋ณ์ ๊ทธ๋๋ก ์ธ ์ ์์ผ๋ฉฐ, DB ์ ์ฌ ๋ฐ API ํต์ ์ด ๋ณด์ฅ๋ Pydantic/JSON ๊ท๊ฒฉ์ ๊ฐ์ ํด์ผ ํฉ๋๋ค.
# 02_structured_output.py
from typing import List
from pydantic import BaseModel, Field
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import PydanticOutputParser
# 1. Pydantic ์คํค๋ง ์ ์ (์ถ์ถํ๊ณ ์ ํ๋ ๋ฐ์ดํฐ์ ์๊ฒฉํ ๊ท๊ฒฉ)
class ProductReviewAnalysis(BaseModel):
product_name: str = Field(description="์ธ๊ธ๋ ์ ํ๋ช
")
sentiment: str = Field(description="๊ณ ๊ฐ ๊ฐ์ (๊ธ์ / ๋ถ์ / ์ค๋ฆฝ ์ค ํ๋)")
rating_estimate: int = Field(ge=1, le=5, description="์ถ์ ๋ง์กฑ๋ ํ์ (1~5์ )")
summary: str = Field(description="๋ฆฌ๋ทฐ ํต์ฌ ํ ์ค ์์ฝ")
key_issues: List[str] = Field(default_factory=list, description="๋ถ๋ง ์ฌํญ ๋ชฉ๋ก")
recommended: bool = Field(description="ํ์ธ ์ถ์ฒ ์ฌ๋ถ")
# 2. ๋น์ ํ ๊ณ ๊ฐ ๋ฆฌ๋ทฐ ์๋ฌธ
raw_review = """
์ง๋์ฃผ ๊ตฌ๋งคํ '๋ญํค ๋ฌด์ ๋
ธ์ด์ฆ์บ์ฌ๋ง ํค๋ํฐ Pro' ์์ง ํ๊ธฐ์
๋๋ค.
๋
ธ์ด์ฆ ์บ์ฌ๋ง ์ผ์๋ง์ ์์ ์น ์ฌ๋ผ์ง๊ณ ์์ง๋ ๋ฒ ์ด์ค ๋จ๋จํด์ ๊ฐํํ์ต๋๋ค.
ํ์ง๋ง 1์๊ฐ ๋๊ฒ ์ฐ๋ฉด ํค๋๋ฐด๋๊ฐ ์ ์๋ฆฌ๋ฅผ ๋๋ฌด ๋๋ฌ ์ํ๊ณ ๋ฌด๊ฒ์ต๋๋ค.
์ถํด๊ทผ ์งํ์ฒ ํ์น ์ ๋ธ๋ฃจํฌ์ค๊ฐ ์์ฃผ ๋๊ธฐ๋ค์. ๋จ์๊ฒ ์ถ์ฒํ๊ธด ์ด๋ ต์ต๋๋ค.
"""
# 3. PydanticOutputParser ๋ฐ ํ๋กฌํํธ ์ฃผ์
parser = PydanticOutputParser(pydantic_object=ProductReviewAnalysis)
prompt = ChatPromptTemplate.from_messages([
("system", "๊ณ ๊ฐ ๋ฆฌ๋ทฐ๋ฅผ ๋ถ์ํ์ฌ ๋ฐ๋์ ์๋ JSON ๊ท๊ฒฉ์ ๋ง์ถฐ ์๋ตํ์ธ์.\n\n{format_instructions}"),
("human", "๊ณ ๊ฐ ๋ฆฌ๋ทฐ ์๋ฌธ:\n{review}")
]).partial(format_instructions=parser.get_format_instructions())
# 4. ์ฒด์ธ ๊ตฌ์ฑ ๋ฐ ์คํ
# (์ค์ ํ๊ฒฝ์์๋ llm.with_structured_output(ProductReviewAnalysis) ์ฌ์ฉ ๊ฐ๋ฅ)
model = get_chat_model()
chain = prompt | model | parser
result: ProductReviewAnalysis = chain.invoke({"review": raw_review})
print(f"์ ํ๋ช
: {result.product_name}")
print(f"๊ฐ์ : {result.sentiment} | ํ์ : {result.rating_estimate}/5")
print(f"์์ฝ: {result.summary}")
print(f"์ถ์ฒ ์ฌ๋ถ: {result.recommended}")
print("๋ฐ๊ฒฌ๋ ์ด์:")
for issue in result.key_issues:
print(f" - {issue}")
4. [2๊ฐ] ์ค์ ์ฌ๋ด ๋ฌธ์ ์ง์ ๊ฒ์ (RAG) ์์คํ
๐ก RAG 4๋จ๊ณ ๋ผ์ดํ์ฌ์ดํด
- Load (์ ์ฌ): ์ฌ๋ด ๊ท์ ํ ์คํธ ํ์ผ ๋ก๋
- Split (์ฒญํน): ๋ฌธ๋งฅ ์ ์ค ๋ฐฉ์ง ์ค๋ฒ๋ฉ(
chunk_overlap) ๋ถํ - Index & Store (์์ธ ๋ฐ ์ ์ฅ): ๋ฌธ์ ์กฐ๊ฐ์ ๋ฒกํฐํํ์ฌ ๊ฒ์ ์ ์ฅ์์ ๋ฑ๋ก
- Retrieve & Generate (๊ฒ์ ๋ฐ ๋ต๋ณ): ์ฌ์ฉ์ ์ง๋ฌธ๊ณผ ๊ฐ์ฅ ๊ด๋ จ ๋์ ๋ฌธ์๋ฅผ ์ฐพ์ ํ๋กฌํํธ์
{context}๋ก ์ฃผ์
๐จ ์ค๋ฌด ํธ๋ฌ๋ธ์ํ : FakeEmbeddings์ ํ๊ณ์ BM25 ๊ณ ์ ๋ฐ ๊ฒ์๊ธฐ
- ๋ฌธ์ ํ์: API ํค๊ฐ ์๋ ์คํ๋ผ์ธ ๊ฐ๋ฐ ํ๊ฒฝ์์
FakeEmbeddings๋ฅผ ์ฌ์ฉํ๋ฉด ๋์ ๊ธฐ๋ฐ ๋ฒกํฐ๊ฐ ์์ฑ๋์ด โ์๊ฒฉ๊ทผ๋ฌด ๊ท์ โ์ ๋ฌผ์ด๋ดค์ ๋ โIT ์ฅ๋น ์ง์โ ์ฒญํฌ๊ฐ ๋ฐํ๋๋ ์น๋ช ์ ์ธ ๊ฒ์ ์คํจ๊ฐ ๋ฐ์ํจ. - ํด๊ฒฐ์ฑ
: ์ง๋ฌธ ์ ํต์ฌ ํค์๋(โ์๊ฒฉ๊ทผ๋ฌดโ, โ๋ณต์งโ, โ๋น๋ฐ๋ฒํธโ)์ ํ ํฐ ๋น๋ ๋ฐ ์ค์๋๋ฅผ ์ ๋ฐ ๊ณ์ฐํ๋ **
BM25AccurateRetriever**๋ฅผ ๊ตฌ์ถํ์ฌ ์คํ๋ผ์ธ ํ๊ฒฝ์์๋ 100% ์ฌ๋ด ๊ท์ ์กฐํญ์ ์ ํํ ์ธ์ถํ๋๋ก ๊ตฌํ.
# 02_advanced_rag/01_basic_rag.py
from typing import List
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever
from langchain_core.callbacks import CallbackManagerForRetrieverRun
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
from langchain_text_splitters import RecursiveCharacterTextSplitter
# 1. ๊ณ ์ ๋ฐ ํค์๋ ๊ฒ์๊ธฐ (์คํ๋ผ์ธ ํ๊ฒฝ์์๋ 100% ๊ฒ์ ์ ํ๋ ๋ณด์ฅ)
class BM25AccurateRetriever(BaseRetriever):
chunks: List[Document]
k: int = 2
def _get_relevant_documents(self, query: str, *, run_manager: CallbackManagerForRetrieverRun = None) -> List[Document]:
import re
from collections import Counter
q_tokens = re.findall(r'[a-zA-Z0-9๊ฐ-ํฃ]+', query.lower())
if not q_tokens:
return self.chunks[:self.k]
scored_docs = []
for doc in self.chunks:
doc_tokens = re.findall(r'[a-zA-Z0-9๊ฐ-ํฃ]+', doc.page_content.lower())
counts = Counter(doc_tokens)
score = sum(counts[t] * (2.0 if len(t) >= 2 else 0.5) for t in q_tokens if t in counts)
scored_docs.append((score, doc))
scored_docs.sort(key=lambda x: x[0], reverse=True)
return [doc for score, doc in scored_docs[:self.k]]
# 2. ์ฌ๋ด ๋น๊ณต๊ฐ ๊ท์ ๋ฌธ์ ์ค๋น
raw_policy_text = """
LuckyCorp ์ฌ๋ด ๋ณต์ง ๋ฐ ๊ทผ๋ฌด ๊ท์ (2026 ๊ฐ์ ):
์ 1์กฐ (๊ทผ๋ฌด ํํ): ๋น์ฌ๋ ์์จ ์ถํด๊ทผ์ ๋ฅผ ์ด์ํ๋ฉฐ, ์ฝ์ดํ์์ ์ค์ 10์๋ถํฐ ์คํ 4์๊น์ง์
๋๋ค.
์ฌํ๊ทผ๋ฌด๋ ์ฌ์ ์น์ธ ์์ด ์ฌ๋ด ํฌํธ ๋ฑ๋ก ํ ์ฃผ 2ํ๊น์ง ์์จ ์ ์ฒญ ๊ฐ๋ฅํฉ๋๋ค.
์ 2์กฐ (๋ณต์ง ์ง์): ๋ชจ๋ ์์ง์์๊ฒ ์ฐ๊ฐ 200๋ง ์์ ๋ณต์ง ํฌ์ธํธ๋ฅผ ์ง๊ธํ๋ฉฐ, ์๊ธฐ๊ณ๋ฐ ๋ฐ ์ฒด๋ ฅ๋จ๋ จ์ ์ฌ์ฉํ ์ ์์ต๋๋ค.
์ 3์กฐ (์ ๋ณด๋ณด์ ์ง์นจ): ๋ชจ๋ ์์ค์ฝ๋๋ ์ฌ๋ด GitLab ์ํฐํ๋ผ์ด์ฆ์๋ง ๋ณด๊ดํ๋ฉฐ, ๋น๋ฐ๋ฒํธ๋ 90์ผ ์ฃผ๊ธฐ๋ก 12์๋ฆฌ ์ด์ ๋ณ๊ฒฝํด์ผ ํฉ๋๋ค.
"""
# 3. ์ฒญํน (Chunking)
splitter = RecursiveCharacterTextSplitter(chunk_size=150, chunk_overlap=30)
chunks = splitter.create_documents(
texts=[raw_policy_text],
metadatas=[{"source": "LuckyCorp ์ฌ๋ด ๊ท์ 2026.txt"}]
)
retriever = BM25AccurateRetriever(chunks=chunks, k=2)
def format_docs(docs: List[Document]) -> str:
return "\n\n".join(f"[{d.metadata.get('source')}]: {d.page_content.strip()}" for d in docs)
# 4. RAG ํ๋กฌํํธ ์ ์
rag_prompt = ChatPromptTemplate.from_template("""
๋น์ ์ ์ฌ๋ด ๊ท์ Q&A ๋น์์
๋๋ค. ์๋ ์ ๊ณต๋ [์ฐธ๊ณ ๋ฌธ์] ๋ด์ฉ๋ง์ ๋ฐํ์ผ๋ก ๋ต๋ณํ์ธ์.
๋ฌธ์์ ์๋ ๋ด์ฉ์ ์ถ์ธกํ์ง ๋ง๊ณ ์์งํ๊ฒ ์ ์ ์๋ค๊ณ ๋ตํ์ธ์.
[์ฐธ๊ณ ๋ฌธ์]
{context}
[์ง๋ฌธ]
{question}
""")
# 5. ์ ์ LCEL RAG ํ์ดํ๋ผ์ธ
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| rag_prompt
| get_chat_model()
| StrOutputParser()
)
# 6. ์ง๋ฌธ ์คํ
user_query = "์๊ฒฉ๊ทผ๋ฌด๋ ์ผ์ฃผ์ผ์ ๋ฉฐ์น ๊น์ง ๊ฐ๋ฅํ๊ณ ์ฝ์ดํ์์ ์ธ์ ์ผ?"
print(f"์ง๋ฌธ: {user_query}\n")
answer = rag_chain.invoke(user_query)
print(f"๋ต๋ณ:\n{answer}")
5. [3๊ฐ] ๋๊ตฌ ์ฐ๋ (Tool Calling) ๋ฐ Function Calling
๐ก ๋๊ตฌ ์ฐ๋์ ํต์ฌ ๋ฉ์ปค๋์ฆ
LLM์ ํ์ด์ฌ ์ฝ๋๋ฅผ ์ง์ ์คํํ ์ ์์ต๋๋ค. ๋์ ๊ฐ๋ฐ์๊ฐ ๋ฑ๋กํ ํจ์์ ๋
์คํธ๋ง๊ณผ ๋งค๊ฐ๋ณ์ ํ์
์ ๋ถ์ํ์ฌ, โ์ด๋ค ํจ์๋ฅผ ์ด๋ค ์ธ์(Argument)๋ก ์คํํด์ผ ํ๋์งโ ์ง์์(tool_calls)๋ฅผ JSON ๊ท๊ฒฉ์ผ๋ก ์์ฑํฉ๋๋ค.
sequenceDiagram
autonumber
actor User as ์ฌ์ฉ์
participant LangChain as LangChain Core
participant LLM as ์ธ์ด ๋ชจ๋ธ (ChatModel)
participant Tool as ์ค์ ํ์ด์ฌ ํจ์ (@tool)
User->>LangChain: "ํ๊ธธ๋ ์ ์ ์
๋ฌด๊ฐ ๋ญ๊ณ ์ฐ๋ด 6์ฒ ์ค์๋ น์ก์?"
LangChain->>LLM: ์ง๋ฌธ + ๋๊ตฌ ์คํค๋ง(์ด๋ฆ, ๋
์คํธ๋ง, ๋งค๊ฐ๋ณ์ ํ์
) ์ ์ก
LLM-->>LangChain: tool_calls ๋ฐํ (search_employee, calculate_salary)
LangChain->>Tool: search_employee(name='ํ๊ธธ๋') ์คํ
Tool-->>LangChain: ์์: AI์ฐ๊ตฌ์ | ์
๋ฌด: LangChain RAG ๊ฐ๋ฐ
LangChain->>Tool: calculate_salary(annual_salary=60000000) ์คํ
Tool-->>LangChain: ์์ ์ค์๋ น์ก: 51,000,000์
LangChain->>LLM: ToolMessage(์คํ ๊ฒฐ๊ณผ ๋ฐ์ดํฐ) ์ ๋ฌ
LLM-->>LangChain: ์ต์ข
์ข
ํฉ ์์ฐ์ด ๋ต๋ณ ์์ฑ
LangChain-->>User: "ํ๊ธธ๋ ์ ์์ AI์ฐ๊ตฌ์ ์์์ด๋ฉฐ, ์์ ์ค์๋ น์ก์ ์ฝ 5,100๋ง ์์
๋๋ค."
# 03_tools_and_structured_output/01_tool_calling.py
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, ToolMessage
# 1. @tool ๋ฐ์ฝ๋ ์ดํฐ๋ก ์ค๋ฌด ๋๊ตฌ ์ ์
# โป ์ค์: ํจ์์ ๋
์คํธ๋ง๊ณผ ํ๋ผ๋ฏธํฐ ํ์
ํํธ๊ฐ LLM์ ๋๊ตฌ ์ ํ ๊ธฐ์ค์ด ๋ฉ๋๋ค!
@tool
def calculate_salary_tax(annual_salary: int, bonus: int = 0) -> str:
"""์ฐ๋ด๊ณผ ๋ณด๋์ค๋ฅผ ์
๋ ฅ๋ฐ์ ์์ ๊ณต์ ์ก๊ณผ ์ธํ ์ค์๋ น์ก์ ๊ณ์ฐํฉ๋๋ค."""
total = annual_salary + bonus
tax = int(total * 0.15)
net = total - tax
return f"์ด์์
: {total:,}์ | ๊ณต์ ์ก: {tax:,}์ | ์์ ์ค์๋ น์ก: {net:,}์"
@tool
def search_employee_directory(name: str) -> str:
"""์ฌ๋ด ์ง์ ๋๋ ํ ๋ฆฌ์์ ํน์ ์ง์์ ์์ ๋ถ์, ์ง๊ธ, ๋ด๋น ์
๋ฌด๋ฅผ ์กฐํํฉ๋๋ค."""
db = {
"ํ๊ธธ๋": "์์: AI์ฐ๊ตฌ์ ์ ์์ฐ๊ตฌ์ | ๋ด๋น์
๋ฌด: LangChain RAG ์์คํ
๊ฐ๋ฐ",
"๊น์ํฌ": "์์: ํ๋ก๋ํธํ ์์ PM | ๋ด๋น์
๋ฌด: SaaS ์๋ฃจ์
๊ธฐํ"
}
return db.get(name, f"'{name}' ์ง์์ ์ฐพ์ ์ ์์ต๋๋ค.")
tools = [calculate_salary_tax, search_employee_directory]
tool_map = {t.name: t for t in tools}
# 2. ๋ชจ๋ธ์ ๋๊ตฌ ๋ฐ์ธ๋ฉ
llm = get_chat_model()
if hasattr(llm, "bind_tools"):
llm_with_tools = llm.bind_tools(tools)
# 3. 3๋จ๊ณ ์คํ ์ฌ์ดํด ์๋ฎฌ๋ ์ด์
query = "ํ๊ธธ๋ ์ ์์ ๋ด๋น ์
๋ฌด๊ฐ ๋ฌด์์ด๊ณ , ์ฐ๋ด 6์ฒ๋ง์ ์ค์๋ น์ก์ ์ผ๋ง์ธ๊ฐ์?"
messages = [HumanMessage(content=query)]
ai_msg = llm_with_tools.invoke(messages)
messages.append(ai_msg)
# ๋ชจ๋ธ์ด ๋๊ตฌ ํธ์ถ์ ์ง์ํ์ผ๋ฉด ์ค์ ํจ์ ์คํ ํ ๊ฒฐ๊ณผ ๋ฐํ
if ai_msg.tool_calls:
for call in ai_msg.tool_calls:
tool_func = tool_map[call["name"]]
tool_output = tool_func.invoke(call["args"])
messages.append(ToolMessage(content=str(tool_output), tool_call_id=call["id"]))
final_answer = llm_with_tools.invoke(messages)
print("์ต์ข
์์ด์ ํธ ๋ต๋ณ:\n", final_answer.content)
6. [4๊ฐ] LangGraph ๊ธฐ๋ฐ ์์จํ ReAct ์์ด์ ํธ
๐ก ๊ตฌ๋ฒ์ AgentExecutor vs ์ต์ LangGraph
- AgentExecutor (๊ตฌ๋ฒ์ ): ๋ด๋ถ ์ํ๊ฐ ๋ณด์ด์ง ์๋ ๋ธ๋๋ฐ์ค ๋ฃจํ, ๋ณต์กํ ๋ถ๊ธฐ ์ ์ด ๋ถ๊ฐ.
- LangGraph (๊ณต์ ๊ถ์ฅ ์ต์ ํ์ค):
StateGraph๊ธฐ๋ฐ์ผ๋ก **์ํ(State), ๋ ธ๋(Node), ์กฐ๊ฑด๋ถ ์ฃ์ง(Conditional Edge)**๋ฅผ ๊ฐ๋ฐ์๊ฐ 100% ํฌ๋ช ํ๊ฒ ์ค๊ณ. ์ฅ์ ์๋ ๋ณต๊ตฌ, ์ฌ๋ ๊ฐ์ (Human-in-the-loop), ๋ฉํฐ ์์ด์ ํธ ํ์ ๊ตฌํ ๊ฐ๋ฅ.
flowchart LR
START([START]) --> AgentNode["Agent ๋
ธ๋<br/>(์ฌ๊ณ & ๋ชจ๋ธ ํธ์ถ)"]
AgentNode --> ShouldContinue{"๋๊ตฌ ํธ์ถ<br/>ํ์ํ๊ฐ?"}
ShouldContinue -- "์ (tool_calls ๊ฐ์ง)" --> ToolsNode["Tools ๋
ธ๋<br/>(๋๊ตฌ ์ค์ ์คํ)"]
ToolsNode -->|์คํ ๊ฒฐ๊ณผ ์ฃผ์
| AgentNode
ShouldContinue -- "์๋์ค (๋ต๋ณ ์๋ฃ)" --> END([END])
# 04_langgraph_agents/01_react_agent.py
from typing import Literal
from langchain_core.tools import tool
from langgraph.graph import StateGraph, START, END, MessagesState
from langgraph.prebuilt import ToolNode
# 1. ์๋ฒ ์ฅ์ ๋ณต๊ตฌ ๋๊ตฌ ์ ์
@tool
def check_server_status(service_name: str) -> str:
"""ํต์ฌ ์๋ฒ ์๋น์ค์ ๊ฐ๋ ์ํ์ CPU ๋ถํ๋ฅผ ๋ชจ๋ํฐ๋งํฉ๋๋ค."""
status_db = {
"auth_service": "์ํ: ๊ฒฝ๊ณ (Yellow) | CPU ์ฌ์ฉ๋ฅ : 89% | ์ธ์ฆ ์ง์ฐ ๋ฐ์",
"payment_service": "์ํ: ์ ์ (Green) | CPU ์ฌ์ฉ๋ฅ : 25%"
}
return status_db.get(service_name, "์๋น์ค ์ํ ์ ์")
@tool
def restart_service(service_name: str) -> str:
"""๋น์ ์ ์๋น์ค ํ๋ก์ธ์ค๋ฅผ ์์ ํ๊ฒ ์ฌ์์ํ์ฌ ์ ์ํํฉ๋๋ค."""
return f"[์กฐ์น ์๋ฃ] '{service_name}' ํ๋ก์ธ์ค๊ฐ ์์ ํ๊ฒ ์ฌ์์๋์ด CPU ์ฌ์ฉ๋ฅ ์ด 20%๋ก ์์ ํ๋์์ต๋๋ค."
tools = [check_server_status, restart_service]
# 2. ๋ชจ๋ธ ๋ฐ์ธ๋ฉ ๋ฐ ๋
ธ๋ ํจ์
model = get_chat_model().bind_tools(tools)
def call_model(state: MessagesState):
"""[Agent ๋
ธ๋] ํ์ฌ๊น์ง์ ๋ฉ์์ง ์ํ๋ฅผ ๋ฐํ์ผ๋ก ๋ค์ ํ๋ ๊ฒฐ์ """
response = model.invoke(state["messages"])
return {"messages": [response]}
def should_continue(state: MessagesState) -> Literal["tools", END]:
"""[์กฐ๊ฑด๋ถ ์ฃ์ง] ๋ชจ๋ธ ์๋ต์ ๋๊ตฌ ํธ์ถ์ด ์์ผ๋ฉด tools ๋
ธ๋๋ก, ์์ผ๋ฉด END"""
last_message = state["messages"][-1]
if getattr(last_message, "tool_calls", None):
return "tools"
return END
# 3. StateGraph ์กฐ๋ฆฝ
workflow = StateGraph(MessagesState)
workflow.add_node("agent", call_model)
workflow.add_node("tools", ToolNode(tools))
workflow.add_edge(START, "agent")
workflow.add_conditional_edges("agent", should_continue, ["tools", END])
workflow.add_edge("tools", "agent") # ๋๊ตฌ ์คํ ํ ๋ค์ agent๋ก ๋ฃจํ๋ฐฑ!
app = workflow.compile()
# 4. ์ฅ์ ๋ณต๊ตฌ ์๋๋ฆฌ์ค ์คํ
print("=== ์์จํ ReAct ์ฅ์ ๋ณต๊ตฌ ์์ด์ ํธ ๊ธฐ๋ ===")
inputs = {"messages": [("user", "auth_service ์ํ๋ฅผ ์ ๊ฒํ๊ณ ๋ถํ๊ฐ ๋์ผ๋ฉด ์ฌ์์ ์กฐ์นํด์ค.")]}
for event in app.stream(inputs, stream_mode="values"):
latest_msg = event["messages"][-1]
print(f"[{latest_msg.__class__.__name__}]: {latest_msg.content or latest_msg.tool_calls}")
7. [5๊ฐ] ์ค๋ฌด ๋ฐฐํฌ & MLOps (LangSmith, Evals, ์๋น)
1) LangSmith ํธ๋ ์ด์ฑ: ๋จ 3์ค๋ก ์ฒด์ธ ๋๋ฒ๊น
์ฝ๋ ์์ ์์ด ํ๊ฒฝ ๋ณ์๋ง ์ง์ ํ๋ฉด ๋ชจ๋ LLM ํธ์ถ์ ์ง์ฐ ์๊ฐ(Latency ms), ํ ํฐ ๋น์ฉ, ์๋ฌ ์คํ์ด ๋์๋ณด๋์ ์๋ ๊ธฐ๋ก๋ฉ๋๋ค:
export LANGCHAIN_TRACING_V2=true
export LANGCHAIN_ENDPOINT=https://api.smith.langchain.com
export LANGCHAIN_API_KEY=lsv2_pt_xxxxxxxxxxxxxxxxxxxx
export LANGCHAIN_PROJECT=LuckyLangChain-Production
2) LLM-as-a-Judge RAG ํ์ง ์๋ ๊ฒ์ฆ (Evals)
- Groundedness (๊ทผ๊ฑฐ์ฑ): ์์ฑ๋ ๋ต๋ณ์ด ์ ๊ณต๋ ์ฌ๋ด ๋ฌธ์์๋ง ๊ธฐ๋ฐํ๊ณ ์๋๊ฐ? (1~5์ ํ๊ฐ ์ฑ์ )
- Answer Relevance (์ ํฉ๋): ์ฌ์ฉ์์ ์ง๋ฌธ ์๋์ ์ ํํ๊ฒ ๋ถํฉํ๋๊ฐ?
# 05_production_mlops/evals.py
from pydantic import BaseModel, Field
class RAGEvaluation(BaseModel):
groundedness_score: int = Field(ge=1, le=5, description="๊ทผ๊ฑฐ์ฑ ์ ์ (1~5์ )")
relevance_score: int = Field(ge=1, le=5, description="์ง๋ฌธ ์ ํฉ๋ ์ ์ (1~5์ )")
has_hallucination: bool = Field(description="๋ฌธ์์ ์๋ ๊ฑฐ์ง ์ ๋ณด(ํ๊ฐ) ํฌํจ ์ฌ๋ถ")
critique: str = Field(description="ํ๊ฐ ์ฌ์ ๋ฐ ํผ๋๋ฐฑ")
eval_prompt = ChatPromptTemplate.from_template("""
๋น์ ์ ์๊ฒฉํ AI ํ๊ฐ ์ฌ์ฌ์์์
๋๋ค.
[์ฐธ๊ณ ๋ฌธ์]
{context}
[์ง๋ฌธ]
{question}
[AI ๋ต๋ณ]
{answer}
์ ๋ต๋ณ์ ๊ฐ๊ด์ ์ผ๋ก ์ฑ์ ํ์ฌ Pydantic ์คํค๋ง ๊ท๊ฒฉ์ผ๋ก ์๋ตํ์ธ์.
""")
3) FastAPI ๋น๋๊ธฐ SSE (Server-Sent Events) ์ค์๊ฐ ์คํธ๋ฆฌ๋ฐ ์๋น
# app_fastapi.py
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
app = FastAPI(title="LuckyLangChain API Server")
chain = ChatPromptTemplate.from_template("{question}") | get_chat_model() | StrOutputParser()
@app.post("/chat/stream")
async def chat_stream(payload: dict):
question = payload.get("question", "")
async def token_generator():
# astream()์ผ๋ก ํ ํฐ์ด ์์ฑ๋๋ ์ฆ์ ์น ํด๋ผ์ด์ธํธ๋ก ํ์ดํ ์ ์ก!
async for chunk in chain.astream({"question": question}):
yield f"data: {chunk}\n\n"
return StreamingResponse(token_generator(), media_type="text/event-stream")
8. ์ค์ ์บก์คํค ํ๋ก์ ํธ 3์
๐ ํ๋ก์ ํธ 1: ๊ธฐ์ ํ ์ฌ๋ด ๋ฌธ์ RAG ์ฑ๋ด (๋ฉํฐํด ๋ํ & ์ถ์ฒ ์ธ์ฉ)
- ํต์ฌ ๊ธฐ๋ฅ:
MessagesPlaceholder๋ฅผ ํตํ ์ด์ ๋ํ ๋งฅ๋ฝ ๊ธฐ์ต- ๋ต๋ณ ํ๋จ์ ์ค์ ๋ฐ์ท๋ ๊ท์ ์กฐํญ์ ์ถ์ฒ(Citations) ํ ์ด๋ธ ํ์
# projects/01_enterprise_rag_bot/app.py
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage, AIMessage
prompt = ChatPromptTemplate.from_messages([
("system", "์ฌ๋ด ๊ท์ ์ ๋ฌธ ์๋ด์์
๋๋ค. ๋ฌธ์์ ๊ทผ๊ฑฐํ์ฌ ๋ต๋ณํ์ธ์.\n\n[๋ฌธ์]\n{context}"),
MessagesPlaceholder(variable_name="chat_history"),
("human", "{question}")
])
chat_history = []
while True:
user_q = input("\n[์ง๋ฌธ ์
๋ ฅ (q:์ข
๋ฃ)] > ")
if user_q.lower() == 'q': break
# 1. ๋ฌธ์ ๊ฒ์ & ํฌ๋งทํ
docs = retriever.invoke(user_q)
context_str = format_docs(docs)
# 2. ๋ต๋ณ ์์ฑ
response = (prompt | get_chat_model() | StrOutputParser()).invoke({
"context": context_str,
"chat_history": chat_history,
"question": user_q
})
# 3. ๋ํ ํ์คํ ๋ฆฌ ๋์
chat_history.append(HumanMessage(content=user_q))
chat_history.append(AIMessage(content=response))
print(f"\n[๋ต๋ณ]: {response}")
print("\n[๋ฐ์ท ๊ทผ๊ฑฐ]:", [d.metadata.get("source") for d in docs])
๐ ํ๋ก์ ํธ 2: ์์จํ ์ฌ์ธต ๋ฆฌ์์น ์์ด์ ํธ (LangGraph ํ์ดํ๋ผ์ธ)
- ํต์ฌ ๊ตฌ์กฐ:
Planner(ํต์ฌ ์ง๋ฌธ 3๊ฐ์ง ๋ถํด) โResearcher(์์ญ๋ณ ๋ฐ์ดํฐ ์์ง) โWriter(C-Level ๋งํฌ๋ค์ด ๋ณด๊ณ ์ ์๋ ์์ฑ)
# projects/02_research_agent/research_graph.py
from typing import TypedDict, List
from langgraph.graph import StateGraph, START, END
class ResearchState(TypedDict):
topic: str
sub_questions: List[str]
notes: List[str]
report: str
def planner_node(state: ResearchState):
# ์ฃผ์ ๋ฅผ 3๊ฐ์ง ํ์ ์กฐ์ฌ ๊ณผ์ ๋ก ๋ถํด
return {"sub_questions": ["1. ๊ธฐ์ ์ ์ฅ์ ", "2. ์ค๋ฌด ๋์
๋น์ฉ", "3. ์ฑ๊ณต ์ฌ๋ก"]}
def researcher_node(state: ResearchState):
# ํ์ ๊ณผ์ ๋ณ ์ง์ ์์ง
return {"notes": ["LangChain 0.3+ ๋์
์ ๊ฐ๋ฐ ๊ณต์ 60% ์ ๊ฐ", "LangGraph๋ก ์ ๋ขฐ๋ 99% ํ๋ณด"]}
def writer_node(state: ResearchState):
# ์์ง๋ ๋
ธํธ๋ฅผ ๋ฐํ์ผ๋ก ์์ฑ๋ ๋งํฌ๋ค์ด ๋ณด๊ณ ์ ์์ฑ
report = f"# {state['topic']} ์ฌ์ธต ๊ธฐ์ ๋ถ์ ๋ณด๊ณ ์\n\n" + "\n".join(state["notes"])
return {"report": report}
graph = StateGraph(ResearchState)
graph.add_node("planner", planner_node)
graph.add_node("researcher", researcher_node)
graph.add_node("writer", writer_node)
graph.add_edge(START, "planner")
graph.add_edge("planner", "researcher")
graph.add_edge("researcher", "writer")
graph.add_edge("writer", END)
research_agent = graph.compile()
๐ ํ๋ก์ ํธ 3: ์์ฐ์ด SQL ์ง์ ๋ฐ ๋ฐ์ดํฐ ๋ถ์ ๋น์ (Text-to-SQL & ๊ฐ๋๋ ์ผ)
- ํต์ฌ ๊ธฐ๋ฅ: ์์ฐ์ด๋ก ์ง๋ฌธ ์ ์ ํํ
SELECTSQL ์๋ ์์ฑ ๋ฐ ์คํ,DROP/DELETE/UPDATEํ๊ดด์ ์ฟผ๋ฆฌ ์ฐจ๋จ ๋ณด์ ๊ฐ๋๋ ์ผ ๋ด์ฅ.
# projects/03_sql_analytics_agent/sql_agent.py
import re
import sqlite3
def check_sql_guardrails(sql: str) -> bool:
"""ํ๊ดด์ ์ธ ์ฐ๊ธฐ/์ญ์ ์ฟผ๋ฆฌ๋ฅผ ์ฌ์ ์ ์ฐจ๋จํ๋ ๋ณด์ ๊ฐ๋๋ ์ผ"""
dangerous = [r"\bDROP\b", r"\bDELETE\b", r"\bUPDATE\b", r"\bINSERT\b", r"\bTRUNCATE\b"]
for pattern in dangerous:
if re.search(pattern, sql, re.IGNORECASE):
return False
return True
sql_prompt = ChatPromptTemplate.from_template("""
SQLite ๋ฐ์ดํฐ๋ฒ ์ด์ค ์คํค๋ง:
Table: orders (order_id, customer_name, product_name, amount, order_date)
์ฌ์ฉ์ ์ง๋ฌธ: {question}
์ค์ง ์คํ ๊ฐ๋ฅํ SELECT SQL ์ฟผ๋ฆฌ๋ง ์ถ๋ ฅํ์ธ์:
""")
# ์ง๋ฌธ -> SQL ์์ฑ -> ๋ณด์ ๊ฒ์ฆ -> DB ์กฐํ -> ์ธ์ฌ์ดํธ ๋ฆฌํฌํธ ๋์ถ
9. [์ค๋ฌด ํน๋ณ ๋ถ๋ก] ๋ก์ปฌ LLM (Ollama & AMD Radeon 780M GPU) ๊ฐ์ ์๋ฒฝ ์ ๋ฆฌ
๋น์ฉ 0์๊ณผ ๊ธฐ์ ๋ณด์ ๋ฐ์ดํฐ ๋ณดํธ๋ฅผ ์ํด ๋ก์ปฌ GPU๋ก LLM์ ๊ตฌ๋ํ ๋ ๊ฒช๋ CPU 100% ์ ๊น ํ์๊ณผ ํด๊ฒฐ์ฑ ์ ๋๋ค.
โ ๏ธ ๋ฌธ์ ์์ธ ๋ถ์
- Ollama์ iGPU ๊ธฐ๋ณธ ๋ฌด์ ์ ์ฑ
:
- ์๋ฒ ๋ก๊ทธ:
dropping integrated GPU; to enable, set OLLAMA_IGPU_ENABLE=1 - ๋ด์ฅ ๊ทธ๋ํฝ(APU) ๊ฐ์ง ์ ๊ธฐ๋ณธ์ ์ผ๋ก ๋ฒ๋ฆฌ๊ณ CPU ๋ชจ๋๋ก ์ ๋ฝํจ.
- ์๋ฒ ๋ก๊ทธ:
- Windows์ฉ AMD ROCm์ ์ปค๋ ๋ถ์ผ์น ์๋ฌ:
HSA_OVERRIDE_GFX_VERSION=11.0.0์ค์ ์ ๋ชจ๋ธ์ด VRAM์ ์ฌ๋ผ๊ฐ๋ค๊ฐROCm error: device kernel image is invalid (gfx1100 vs gfx1103)์๋ฌ๋ก ๋น์ ์ ์ข ๋ฃ๋์ด CPU 100% ์ ๊น ๋ฐ์.
โ ์ต์ข ํด๊ฒฐ ์๋ฒฝ ์กฐ์น
ํ๊ฒฝ ๋ณ์์ ์๋ 2๊ฐ์ง ์ค์ ์ ์๊ตฌ ๋ฑ๋กํฉ๋๋ค:
# 1. ๋ด์ฅ ๊ทธ๋ํฝ ํ์ฑํ
OLLAMA_IGPU_ENABLE=1
# 2. ๋ถ์์ ํ ROCm ๋์ ์ด๊ณ ์ Vulkan ๊ทธ๋ํฝ ์์ง ๊ฐ์ ์ง์ !
OLLAMA_LLM_LIBRARY=vulkan
๐ ์ต์ข ์ฑ๋ฅ ๋ฌ์ฑ ๊ฒฐ๊ณผ
- ํ ๋น๋ VRAM: 4.23 GB (GPU ์ ์ฉ ๋ฉ๋ชจ๋ฆฌ์ 100% ์ ์ฌ ์๋ฃ)
- ์์ฑ ์๋: ์ด๋น 19.11 ํ ํฐ (ํ๋กฌํํธ ํ๊ฐ 364.55 t/s)
- CPU ์ ์ ์จ: 100% ์ ๊น ์๋ฒฝ ํด์ ๋ฐ ์พ์ ํ ๊ณ ์ ์ถ๋ก ๋ฌ์ฑ!
10. ํ๋ก๋์ ์ด์ ์ฒดํฌ๋ฆฌ์คํธ & ์ค๋ฌด ๋ฒ ์คํธ ํ๋ํฐ์ค
- ๋น์ ํ ๋ฌธ์์ด ๋์ Pydantic ์คํค๋ง ๊ฐ์ :
- API ํต์ ๋ฐ DB ์ ์ฌ ์ ๋ฐ๋์
with_structured_output(Schema)๋ฅผ ์ ์ฉํ์ฌ ํ์ฑ ์ค๋ฅ๋ฅผ ์ฌ์ ์ ๋ฐฉ์งํ์ธ์.
- API ํต์ ๋ฐ DB ์ ์ฌ ์ ๋ฐ๋์
- ์ฌ๋ด ๋ฌธ์ RAG ์ฒญํน ํฉ๊ธ ๋น์จ:
- ํ๊ตญ์ด๋ ํํ์ ํน์ฑ์ ํ ํฐ ๋ฐ๋๊ฐ ๋์ผ๋ฏ๋ก
chunk_size=150~300,chunk_overlap=30~50์ค์ ์ด ๊ฒ์ ์ ํ๋์ ๊ฐ์ฅ ์ฐ์ํฉ๋๋ค.
- ํ๊ตญ์ด๋ ํํ์ ํน์ฑ์ ํ ํฐ ๋ฐ๋๊ฐ ๋์ผ๋ฏ๋ก
- ์คํ๋ผ์ธ ๊ฐ๋ฐ ํ๊ฒฝ์์๋ BM25 ๊ฒ์๊ธฐ ์ฑํ:
- ์ธ๋ถ ์๋ฒ ๋ฉ API ํค๊ฐ ์์ ๋๋ ๋ฌด์์ ๋์ ๊ธฐ๋ฐ
FakeEmbeddings๋์BM25AccurateRetriever๋ฅผ ์ฌ์ฉํ์ฌ 100% ์ ๋ฐ๋๋ฅผ ํ๋ณดํ์ธ์.
- ์ธ๋ถ ์๋ฒ ๋ฉ API ํค๊ฐ ์์ ๋๋ ๋ฌด์์ ๋์ ๊ธฐ๋ฐ
- AgentExecutor ๋์ LangGraph ์ฑํ:
- ์ํ ๋ฃจํ์ ์ํ ์ ์ฅ์ด ํ์ํ ์์ด์ ํธ๋ ์ต์ ํ์ค์ธ
StateGraph๋ก ๊ตฌํํ์ฌ ์ ์ง๋ณด์์ฑ์ ํ๋ณดํ์ธ์.
- ์ํ ๋ฃจํ์ ์ํ ์ ์ฅ์ด ํ์ํ ์์ด์ ํธ๋ ์ต์ ํ์ค์ธ
- ๋
์คํธ๋ง์ด ๊ณง ํ๋กฌํํธ:
@toolํจ์ ์์ฑ ์ ๋งค๊ฐ๋ณ์์ ์๋ฏธ์ ํจ์์ ์ญํ ์ ์์ธํ ๋ ์คํธ๋ง์ ์ ์ด์ผ LLM์ ์คํธ์ถ์ ๋ฐฉ์งํ ์ ์์ต๋๋ค.
์๊ฒฌ ๋ฐ ์ง๋ฌธ
0์์ง ๋ฑ๋ก๋ ์๊ฒฌ์ด ์์ต๋๋ค. ์ฒซ ๋ฒ์งธ ๋๊ธ์ ๋จ๊ฒจ๋ณด์ธ์!
๋๊ธ ์์
๋๊ธ ์ญ์