Phidata 지식 베이스(Knowledge)와 RAG
Phidata 지식 베이스(Knowledge)와 RAG
모델을 아무리 잘 훈련해도 우리 회사 내부 문서나 최신 데이터는 모를 수밖에 없어요. Phidata에서 에이전트는 지식(Knowledge)을 이용해 훈련 데이터를 도메인 전문 지식으로 보완해요. 지식은 벡터 데이터베이스에 저장되어, 질의 시점에 에이전트에게 비즈니스 컨텍스트를 제공하고 맥락을 아는 응답을 하게 도와줘요.
기본 문법
에이전트에 지식 베이스를 붙이는 기본 형태는 이래요.
from phi.agent import Agent, AgentKnowledge
# Create a knowledge base for the Agent
knowledge_base = AgentKnowledge(vector_db=...)
# Add information to the knowledge base
knowledge_base.load_text("The sky is blue")
# Add the knowledge base to the Agent and
# give it a tool to search the knowledge base as needed
agent = Agent(knowledge=knowledge_base, search_knowledge=True)
AgentKnowledge에 벡터 DB를 연결하고 내용을 넣은 뒤, 에이전트의 knowledge에 넘겨요. search_knowledge=True를 주면 에이전트가 필요할 때 지식 베이스를 검색하는 도구를 갖게 돼요.
벡터 데이터베이스와 에이전트
지식 베이스로는 모든 저장소를 쓸 수 있지만, 벡터 데이터베이스가 밀집 정보에서 관련 결과를 빠르게 찾는 데 가장 좋아요. 흐름은 세 단계예요.
- 정보를 청크(chunk)로 분해 — 검색 질의가 관련 결과만 반환하도록 지식을 작은 조각으로 나눠요.
- 지식 베이스를 로드 — 청크를 임베딩 벡터로 변환해 벡터 DB에 저장해요.
- 지식 베이스를 검색 — 사용자가 메시지를 보내면 입력을 임베딩으로 바꾸고 벡터 DB에서 최근접 이웃을 "검색"해요.
예시: PDF 지식 베이스를 가진 RAG 에이전트
요리 레시피 PDF에서 질문에 답하는 RAG 에이전트를 만들어 볼게요.
1단계: PgVector 실행
벡터 DB로 PgVector를 쓰면 에이전트의 저장소(storage)도 겸할 수 있어요. Docker Desktop이 설치되어 있다면 아래 명령으로 PgVector를 5532 포트에 띄워요.
docker run -d \
-e POSTGRES_DB=ai \
-e POSTGRES_USER=ai \
-e POSTGRES_PASSWORD=ai \
-e PGDATA=/var/lib/postgresql/data/pgdata \
-v pgvolume:/var/lib/postgresql/data \
-p 5532:5432 \
--name pgvector \
phidata/pgvector:16
2단계: 전통적 RAG
RAG(Retrieval Augmented Generation)는 **"관련 정보로 프롬프트를 채우는 것"**을 뜻해요. 과정은 두 단계예요: ① 지식 베이스에서 관련 정보를 검색하고, ② 모델에게 컨텍스트를 주도록 프롬프트를 증강해요. 레시피 PDF에 답하는 전통적 RAG 에이전트는 이렇게 생겼어요.
from phi.agent import Agent
from phi.model.openai import OpenAIChat
from phi.knowledge.pdf import PDFUrlKnowledgeBase
from phi.vectordb.pgvector import PgVector, SearchType
db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
knowledge_base = PDFUrlKnowledgeBase(
# Read PDF from this URL
urls=["https://phi-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"],
# Store embeddings in the `ai.recipes` table
vector_db=PgVector(table_name="recipes", db_url=db_url, search_type=SearchType.hybrid),
)
# Load the knowledge base: Comment after first run
knowledge_base.load(upsert=True)
agent = Agent(
model=OpenAIChat(id="gpt-4o"),
knowledge=knowledge_base,
# Enable RAG by adding references from AgentKnowledge to the user prompt.
add_context=True,
# Set as False because Agents default to `search_knowledge=True`
search_knowledge=False,
markdown=True,
# debug_mode=True,
)
agent.print_response("How do I make chicken and galangal in coconut milk soup")
add_context=True가 지식 베이스의 참조를 유저 프롬프트에 넣어 RAG를 켜는 역할을 해요.
3단계: 에이전틱 RAG
위 전통적 RAG의 add_context=True는 질문과 관련 있든 없든 항상 지식 베이스 정보를 프롬프트에 넣어요. 반면 에이전틱 RAG는 에이전트가 "지식 베이스에 접근할지, 그리고 어떤 검색 파라미터로 질의할지"를 스스로 결정해요.
from phi.agent import Agent
from phi.model.openai import OpenAIChat
from phi.knowledge.pdf import PDFUrlKnowledgeBase
from phi.vectordb.pgvector import PgVector, SearchType
db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
knowledge_base = PDFUrlKnowledgeBase(
urls=["https://phi-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"],
vector_db=PgVector(table_name="recipes", db_url=db_url, search_type=SearchType.hybrid),
)
# Load the knowledge base: Comment out after first run
knowledge_base.load(upsert=True)
agent = Agent(
model=OpenAIChat(id="gpt-4o"),
knowledge=knowledge_base,
# Add a tool to search the knowledge base which enables agentic RAG.
search_knowledge=True,
# Add a tool to read chat history.
read_chat_history=True,
show_tool_calls=True,
markdown=True,
# debug_mode=True,
)
agent.print_response("How do I make chicken and galangal in coconut milk soup", stream=True)
agent.print_response("What was my last question?", markdown=True)
search_knowledge=True와 read_chat_history=True를 켜면 에이전트가 필요할 때 지식 베이스와 대화 기록을 검색하는 도구를 갖게 돼요. 실행해 보면 "질문을 받았을 때 지식 베이스를, 대화 맥락이 필요할 때 기록을" 검색하는 걸 눈으로 확인할 수 있어요.
지식 관련 속성
| Parameter | Type | Default | Description |
|---|---|---|---|
knowledge |
AgentKnowledge |
None |
Provides the knowledge base used by the agent. |
search_knowledge |
bool |
True |
Adds a tool that allows the Model to search the knowledge base (aka Agentic RAG). Enabled by default when knowledge is provided. |
add_context |
bool |
False |
Enable RAG by adding references from AgentKnowledge to the user prompt. |
retriever |
Callable[..., Optional[list[dict]]] |
None |
Function to get context to add to the user message. This function is called when add_context is True. |
context_format |
Literal['json', 'yaml'] |
json |
Specifies the format for RAG, either "json" or "yaml". |
add_context_instructions |
bool |
False |
If True, add instructions for using the context to the system prompt (if knowledge is also provided). For example: add an instruction to prefer information from the knowledge base over its training data. |
knowledge를 제공하면 search_knowledge가 기본적으로 True가 돼요. 그래서 전통적 RAG를 쓰려면 명시적으로 search_knowledge=False로 꺼야 해요. 헷갈리기 쉬운 부분이라 짚어 드릴게요.
더 알아보기
- 지식 베이스 종류: Knowledge Bases
- 벡터 DB 연결: Vectordb
- 청크 방식: Chunking