Neo4j와 Milvus로 GraphRAG 에이전트 구축하기
이 블로그는 원래 Neo4j에 게시되었으며 허가를 받아 여기에 재게시되었습니다
개요
이 블로그 게시물에서는 Neo4j 그래프 데이터베이스와 Milvus 벡터 데이터베이스를 사용하여 GraphRAG 에이전트를 구축하는 방법을 자세히 설명합니다. 이 에이전트는 그래프 데이터베이스와 벡터 검색의 강점을 결합하여 사용자 쿼리에 정확하고 관련성 높은 답변을 제공합니다. 이 예제에서는 LangGraph, Ollama와 함께 Llama 3.1 8B 및 GPT-4o를 사용합니다.
전통적인 Retrieval Augmented Generation(RAG) 시스템은 관련 문서를 검색하기 위해 오직 벡터 데이터베이스에만 의존합니다. 우리의 접근 방식은 한 걸음 더 나아가 Neo4j 를 통합하여 엔티티와 개념 간의 관계를 포착함으로써 정보에 대한 더 미묘한 이해를 제공합니다. 우리는 이 두 가지 기법을 결합하여 더 견고하고 유익한 RAG 시스템을 만들고자 합니다.
RAG 에이전트 구축
우리 에이전트는 라우팅, 폴백 메커니즘, 자기 수정이라는 세 가지 핵심 개념을 따릅니다. 이러한 원칙은 일련의 LangGraph 컴포넌트를 통해 구현됩니다:
라우팅 – 전용 라우팅 메커니즘이 쿼리를 기반으로 벡터 데이터베이스, 지식 그래프 또는 둘의 조합 중 무엇을 사용할지 결정합니다.
폴백 – 초기 검색이 충분하지 않은 상황에서는 에이전트가 Tavily를 사용한 웹 검색으로 폴백합니다.
자기 수정 – 에이전트는 자신의 답변을 평가하고 환각이나 부정확성을 수정하려고 시도합니다.
그런 다음 다음과 같은 다른 컴포넌트가 있습니다:
검색 – 우리는 오픈 소스 고성능 벡터 데이터베이스인 Milvus를 사용하여 사용자의 쿼리에 대한 의미적 유사성을 기반으로 문서 청크를 저장하고 검색합니다.
그래프 향상 – Neo4j는 검색된 문서에서 지식 그래프를 구성하는 데 사용되어 관계와 엔티티로 컨텍스트를 풍부하게 합니다.
LLM 통합 – 로컬 LLM인 Llama 3.1 8B는 답변 생성과 검색된 정보의 관련성 및 정확성 평가에 사용되며, GPT-4o는 Neo4j에서 사용하는 쿼리 언어인 Cypher를 생성하는 데 사용됩니다.
GraphRAG 아키텍처
우리 GraphRAG 에이전트의 아키텍처는 여러 상호 연결된 노드가 있는 워크플로로 시각화할 수 있습니다:
질문 라우팅 – 에이전트는 먼저 질문을 분석하여 최적의 검색 전략(벡터 검색, 그래프 검색 또는 둘 다)을 결정합니다.
검색 – 라우팅 결정에 따라 Milvus에서 관련 문서를 검색하거나 Neo4j 그래프에서 정보를 추출합니다.
생성 – LLM은 검색된 컨텍스트를 사용하여 답변을 생성합니다.
평가 – 에이전트는 생성된 답변의 관련성, 정확성, 잠재적 환각을 평가합니다.
개선 (필요한 경우) – 답변이 만족스럽지 않다고 판단되면 에이전트는 검색을 개선하거나 오류 수정을 시도할 수 있습니다.
에이전트 예시
우리 LLM 에이전트의 기능을 보여주기 위해 두 가지 다른 컴포넌트인 Graph Generation과 Composite Agent를 살펴보겠습니다.
전체 코드는 이 게시물의 하단에서 확인할 수 있지만, 이 스니펫들은 이러한 에이전트가 LangChain 프레임워크 내에서 어떻게 작동하는지 더 잘 이해하는 데 도움이 될 것입니다.
그래프 생성
이 컴포넌트는 Neo4j의 기능을 사용하여 질의응답 프로세스를 개선하도록 설계되었습니다. Neo4j 그래프 데이터베이스 내에 포함된 지식을 활용하여 질문에 답합니다. 작동 방식은 다음과 같습니다:
1. GraphCypherQAChain – LLM이 Neo4j 그래프 데이터베이스와 상호작용할 수 있게 합니다. LLM을 두 가지 방식으로 사용합니다:
cypher_llm– 이 LLM 인스턴스는 사용자의 질문을 기반으로 그래프에서 관련 정보를 추출하기 위한 Cypher 쿼리를 생성하는 역할을 합니다.검증 – Cypher 쿼리가 구문적으로 올바른지 확인하기 위해 검증합니다.
2. 컨텍스트 검색 – 검증된 쿼리는 필요한 컨텍스트를 검색하기 위해 Neo4j 그래프에서 실행됩니다.
3. 답변 생성 – 언어 모델은 검색된 컨텍스트를 사용하여 사용자의 질문에 대한 답변을 생성합니다.
### Generate Cypher Query
llm = ChatOllama(model=local_llm, temperature=0)
# Chain
graph_rag_chain = GraphCypherQAChain.from_llm(
cypher_llm=llm,
qa_llm=llm,
validate_cypher=True,
graph=graph,
verbose=True,
return_intermediate_steps=True,
return_direct=True,
)
# Run
question = "agent memory"
generation = graph_rag_chain.invoke({"query": question})
이 컴포넌트는 RAG 시스템이 Neo4j를 활용할 수 있게 해주며, 이를 통해 더 포괄적이고 정확한 답변을 제공하는 데 도움이 될 수 있습니다.
복합 에이전트, 그래프 및 벡터 🪄
여기서 마법이 일어납니다: 우리의 에이전트는 Milvus와 Neo4j의 결과를 결합할 수 있어 정보를 더 잘 이해하고 더 정확하며 미묘한 차이를 반영한 답변을 이끌어낼 수 있습니다. 작동 방식은 다음과 같습니다:
프롬프트 – LLM이 Milvus와 Neo4j의 컨텍스트를 모두 사용하여 질문에 답하도록 지시하는 프롬프트를 정의합니다.
검색 – 에이전트는 Milvus(벡터 검색 사용)와 Neo4j(그래프 생성 사용)에서 관련 정보를 검색합니다.
답변 생성 – Llama 3.1 8B는 프롬프트를 처리하고 복합 체인을 통해 벡터 및 그래프 데이터베이스의 결합된 지식을 활용하여 간결한 답변을 생성합니다.
### Composite Vector + Graph Generations
cypher_prompt = PromptTemplate(
template="""You are an expert at generating Cypher queries for Neo4j.
Use the following schema to generate a Cypher query that answers the given question.
Make the query flexible by using case-insensitive matching and partial string matching where appropriate.
Focus on searching paper titles as they contain the most relevant information.
Schema:
{schema}
Question: {question}
Cypher Query:""",
input_variables=["schema", "question"],
)
# QA prompt
qa_prompt = PromptTemplate(
template="""You are an assistant for question-answering tasks.
Use the following Cypher query results to answer the question. If you don't know the answer, just say that you don't know.
Use three sentences maximum and keep the answer concise. If topic information is not available, focus on the paper titles.
Question: {question}
Cypher Query: {query}
Query Results: {context}
Answer:""",
input_variables=["question", "query", "context"],
)
llm = ChatOpenAI(model="gpt-4o", temperature=0)
# Chain
graph_rag_chain = GraphCypherQAChain.from_llm(
cypher_llm=llm,
qa_llm=llm,
validate_cypher=True,
graph=graph,
verbose=True,
return_intermediate_steps=True,
return_direct=True,
cypher_prompt=cypher_prompt,
qa_prompt=qa_prompt,
)
연구 논문 탐색을 향상시키기 위해 그래프 및 벡터 데이터베이스의 강점을 결합한 검색 결과를 살펴보겠습니다.
Neo4j를 사용한 그래프 검색부터 시작합니다:
# Example input data
question = "What paper talks about Multi-Agent?"
generation = graph_rag_chain.invoke({"query": question})
print(generation)
> Entering new GraphCypherQAChain chain...
Generated Cypher:
cypher
MATCH (p:Paper)
WHERE toLower(p.title) CONTAINS toLower("Multi-Agent")
RETURN p.title AS PaperTitle, p.summary AS Summary, p.url AS URL
> Finished chain.
{'query': 'What paper talks about Multi-Agent?', 'result': [{'PaperTitle': 'Collaborative Multi-Agent, Multi-Reasoning-Path (CoMM) Prompting Framework', 'Summary': 'In this work, we aim to push the upper bound of the reasoning capability of LLMs by proposing a collaborative multi-agent, multi-reasoning-path (CoMM) prompting framework. Specifically, we prompt LLMs to play different roles in a problem-solving team, and encourage different role-play agents to collaboratively solve the target task. In particular, we discover that applying different reasoning paths for different roles is an effective strategy to implement few-shot prompting approaches in the multi-agent scenarios. Empirical results demonstrate the effectiveness of the proposed methods on two college-level science problems over competitive baselines. Our further analysis shows the necessity of prompting LLMs to play different roles or experts independently.', 'URL': 'https://github.com/amazon-science/comm-prompt'}]
그래프 검색은 관계와 메타데이터를 찾는 데 탁월합니다. 제목, 저자 또는 사전 정의된 카테고리를 기반으로 논문을 빠르게 식별하여 데이터에 대한 구조화된 관점을 제공합니다.
다음으로, 다른 관점을 위해 벡터 검색으로 전환합니다:
# Example input data
question = "What paper talks about Multi-Agent?"
# Get vector + graph answers
docs = retriever.invoke(question)
vector_context = rag_chain.invoke({"context": docs, "question": question})
> The paper discusses "Adaptive In-conversation Team Building for Language Model Agents" and talks about Multi-Agent. It presents a new adaptive team-building paradigm that offers a flexible solution for building teams of LLM agents to solve complex tasks effectively. The approach, called Captain Agent, dynamically forms and manages teams for each step of the task-solving process, utilizing nested group conversations and reflection to ensure diverse expertise and prevent stereotypical outputs.
벡터 검색은 맥락과 의미적 유사성을 이해하는 데 매우 뛰어납니다. 검색어를 명시적으로 포함하지 않더라도, 쿼리와 개념적으로 관련된 논문을 찾아낼 수 있습니다.
마지막으로, 두 검색 방법을 결합합니다:
이는 벡터 데이터베이스와 그래프 데이터베이스를 모두 사용할 수 있게 해주는, 우리 RAG 에이전트의 핵심적인 부분입니다.
composite_chain = prompt | llm | StrOutputParser()
answer = composite_chain.invoke({"question": question, "context": vector_context, "graph_context": graph_context})
print(answer)
> The paper "Collaborative Multi-Agent, Multi-Reasoning-Path (CoMM) Prompting Framework" talks about Multi-Agent. It proposes a framework that prompts LLMs to play different roles in a problem-solving team and encourages different role-play agents to collaboratively solve the target task. The paper presents empirical results demonstrating the effectiveness of the proposed methods on two college-level science problems.
그래프 검색과 벡터 검색을 통합함으로써, 우리는 두 접근 방식의 강점을 모두 활용합니다. 그래프 검색은 정밀성을 제공하고 구조화된 관계를 탐색하는 반면, 벡터 검색은 의미적 이해를 통해 깊이를 더합니다.
이 결합된 방법은 여러 가지 장점을 제공합니다:
향상된 재현율: 어느 한 방법만으로는 놓칠 수 있는 관련 논문을 찾아냅니다.
강화된 맥락: 논문들이 서로 어떻게 관련되는지에 대해 더 미묘한 이해를 제공합니다.
유연성: 특정 키워드 검색부터 더 넓은 개념적 탐색까지, 다양한 유형의 쿼리에 적응할 수 있습니다.
정리
이 블로그 게시물에서는 Neo4j와 Milvus를 사용하여 GraphRAG Agent를 구축하는 방법을 보여주었습니다. 그래프 데이터베이스와 벡터 검색의 강점을 결합함으로써, 이 에이전트는 사용자 쿼리에 정확하고 관련성 높은 답변을 제공합니다.
전용 라우팅, 폴백 메커니즘, 자체 수정 기능을 갖춘 RAG 에이전트의 아키텍처는 견고하고 신뢰할 수 있게 만들어 줍니다. Graph Generation 및 Composite Agent 컴포넌트의 예시는 이 에이전트가 벡터 데이터베이스와 그래프 데이터베이스를 모두 활용하여 포괄적이고 미묘한 차이를 반영한 답변을 제공할 수 있음을 보여줍니다.
이 가이드가 도움이 되었기를 바라며, 여러분의 프로젝트에서 그래프 데이터베이스와 벡터 검색을 결합할 수 있는 가능성을 살펴보는 데 영감을 주기를 바랍니다.
현재 코드는 GitHub에서 확인할 수 있습니다.
따라 하기
계속 읽기

Zilliz Cloud Now Available in AWS Asia Pacific (Seoul)
Zilliz Cloud is now available in AWS Seoul — low-latency vector search, in-country data residency, and one-step migration for Korean AI teams. 31 regions across 5 clouds.

AI Agents Are Quietly Transforming E-Commerce — Here’s How
Discover how AI agents transform e-commerce with autonomous decision-making, enhanced product discovery, and vector search capabilities for today's retailers.

AI Integration in Video Surveillance Tools: Transforming the Industry with Vector Databases
Discover how AI and vector databases are revolutionizing video surveillance with real-time analysis, faster threat detection, and intelligent search capabilities for enhanced security.




