[MS] GraphRAG 사용하기📊 w. Ollama (2)

이전 포스팅에서 혼자 Microsoft의 공식 문서를 읽고 시도해보려고 했으나, OpenAI를 연결하는 부분에서 에러가 나 해결하지 못했다. 그래서 이 포스팅을 읽고 이 분의 방법을 따라해보고자 한다.
결론: 실패했다.
1. Ollama 설치 및 모델 다운로드
GraphRAG를 시작하기에 앞서, Ollama를 설치해야 하고, Ollama에 대해서 간단하게 알고 넘어가자.
Ollama(올라마)란?
Ollama는 Llama 3와 같은 오픈 소스 대규모 언어 모델을 로컬에서 실행할 수 있도록 설계된 도구다. Ollama는 사용자의 요구에 맞게 모델을 커스터마이징할 수 있고, 인터넷 연결 없이도 모델을 사용할 수 있다.
다음 링크에서 운영체제에 맞는 Ollama를 설치한다. (Windows 쓰는 분들은 다운받지 말고 잠시 대기!)

Ollama를 설치하고 냅다 터미널에 Gemma 2 모델을 다운받는 코드를 치니 다음과 같이 에러가 나왔다.

알고보니 Ollama는 현재 macOS와 Linux만 지원하고 아직 Windows는 지원하고 있지 않기 때문에 Windows에서 Linux를 실행할 수 있는 WSL(Windows Subsystem for Linux)를 먼저 설치해야 한다. 그래서 Ollama를 설치하자마자 VSCode에서 다음과 같은 알림을 받을 수 있었다.

Install 버튼을 누르니 다음과 같이 설치가 된 것을 볼 수 있다.

WSL의 설명을 읽다보니 해야 할 부분들이 있다.
- VSCode와 WSL 연동시키기
- Ubuntu 설치하기
나는 이미 2번째가 되어있기 때문에 필요한 사람들은 위의 링크에서 제공하는 설명을 읽어보고 설치하길 바란다.
1.1 VSCode와 WSL 연동시키기
VSCode에서 `Ctrl + Shift + P`를 누르고 `Connect to WSL`을 검색하여 실행한다.


Terminal을 열면 바로 Linux Terminal이 나오는 것을 볼 수 있다!

그러면 Ollama도 Linux 운영체제에 맞게 설치해야되기 때문에 다운로드 하는 링크로 가서 명령어를 가져와서 터미널에 넣어준다.
curl -fsSL https://ollama.com/install.sh | sh

Ollama를 실행시키기 위해서는 꼭 이 명령어를 실행해야 한다.
ollama serve

그리고 Terminal을 새로 만들어서 다음 명령어를 실행하여 Gemma2 모델과 nomic-embed-text 모델을 다운로드한다.
ollama pull gemma2
ollama pull nomic-embed-text


2. GraphRAG 설치
GraphRAG를 설치하려고 `pip install graphrag`를 쳤지만, `pip`를 설치하라고 `sudo apt install python3-pip`를 하라고 추천하지만 에러가 뜬다. 따라서 다음 순서대로 설치하길 바란다.
sudo apt-get update
sudo apt-get install samba
sudo apt-get install python3-pip
pip를 설치하고 graphrag를 설치해보자.
pip install graphrag

3. 데이터 프로젝트 설정
다음과 같이 `graphragtest/input` 디렉토리를 만들어준다.

`book.txt` 파일을 만들어서 GraphRAG 논문의 일부 샘플데이터로 저장한다.

The use of retrieval-augmented generation (RAG) to retrieve relevant information from an external knowledge source enables large language models (LLMs) to answer questions over private and/or previously unseen document collections. However, RAG fails on global questions directed at an entire text corpus, such as “What are the main themes in the dataset?”, since this is inherently a queryfocused summarization (QFS) task, rather than an explicit retrieval task. Prior QFS methods, meanwhile, fail to scale to the quantities of text indexed by typical RAG systems. To combine the strengths of these contrasting methods, we propose a Graph RAG approach to question answering over private text corpora that scales with both the generality of user questions and the quantity of source text to be indexed. Our approach uses an LLM to build a graph-based text index in two stages: first to derive an entity knowledge graph from the source documents, then to pregenerate community summaries for all groups of closely-related entities. Given a question, each community summary is used to generate a partial response, before all partial responses are again summarized in a final response to the user. For a class of global sensemaking questions over datasets in the 1 million token range, we show that Graph RAG leads to substantial improvements over a na¨ıve RAG baseline for both the comprehensiveness and diversity of generated answers. An open-source, Python-based implementation of both global and local Graph RAG approaches is forthcoming at https://aka.ms/graphrag.
4. 초기화
GraphRAG를 초기화 하기 위해 다음 명령을 실행한다.
python3 -m graphrag.index --init --root ./graphragtest
그러면 다음 그림 15와 같이 GraphRAG 실행에 필요한 `.env` 파일과 `settings.yaml` 파일이 생성된다.

.env 파일 수정
`.env` 파일에서 다음과 같이 `GRAPHRAG_API_KEY`를 ollama 라고 써준다. 사실 openAI를 사용하게 된다면 key를 발급받아야 하지만 ollama는 로컬에서 돌아갈 수 있는 LLM이기 때문에 아무렇게나 작성해주면 된다.
GRAPHRAG_API_KEY=ollama
settings.yaml 파일 수정
`settings.yaml` 파일을 다음 그림을 참고하여 수정하면 된다.


5. openai_embeddings_llm.py 수정
\\wsl.localhost\Ubuntu\home\chaewon\.local\lib\python3.10\site-packages\graphrag\llm\openai
위의 경로에 있는 `openai_embeddings_llm.py` 다음과 같이 수정한다.
from typing_extensions import Unpack
from graphrag.llm.base import BaseLLM
from graphrag.llm.types import (
EmbeddingInput,
EmbeddingOutput,
LLMInput,
)
from .openai_configuration import OpenAIConfiguration
from .types import OpenAIClientTypes
import ollama
class OpenAIEmbeddingsLLM(BaseLLM[EmbeddingInput, EmbeddingOutput]):
_client: OpenAIClientTypes
_configuration: OpenAIConfiguration
def __init__(self, client: OpenAIClientTypes, configuration: OpenAIConfiguration):
self._client = client
self._configuration = configuration
async def _execute_llm(
self, input: EmbeddingInput, **kwargs: Unpack[LLMInput]
) -> EmbeddingOutput | None:
args = {
"model": self._configuration.model,
**(kwargs.get("model_parameters") or {}),
}
embedding_list = []
for inp in input:
embedding = ollama.embeddings(model="nomic-embed-text", prompt=inp)
embedding_list.append(embedding["embedding"])
return embedding_list
6. 인덱싱 파이프라인
꼭 `./graphragtest`내에서 명령어를 치지 말고 `cd ..` 치고 명령어를 치세요..^^
python3 -m graphrag.index --root ./graphragtest

7. 질의 엔진 사용
전역 검색을 수행하는 명령을 실행한다.
python3 -m graphrag.query --root ./graphragtest --method global "What's the point of this story?"

실패했다. 죽일까?