LlamaIndex로 Qwen RAG 구현하기

LlamaIndex로 Qwen RAG 구현하기

Qwen2.5를 문서나 웹 페이지 같은 외부 데이터와 연결하기 위해 LlamaIndex 튜토리얼을 제공해요. 이 가이드는 Qwen2.5와 함께 LlamaIndex를 사용해 검색 증강 생성(RAG, Retrieval-Augmented Generation)을 빠르게 구현하는 방법을 알려드려요.

출처: 문서

본문

⚠️ 주의: 이 페이지는 Qwen3 기준으로 업데이트 예정이에요.

준비

RAG를 구현하려면 먼저 LlamaIndex 관련 패키지를 설치하는 것을 권장해요. 간단한 코드는 다음과 같아요:

pip install llama-index
pip install llama-index-llms-huggingface
pip install llama-index-readers-web

파라미터 설정

이제 LLM, 임베딩 모델, 관련 설정을 구성할 수 있어요. Qwen2.5-Instruct는 영어와 중국어를 포함한 여러 언어의 대화를 지원해요. 영어 문서에서 검색하려면 bge-base-en-v1.5 모델을 사용하고, 중국어 문서에서 검색하려면 bge-base-zh-v1.5 모델을 다운로드해 사용할 수 있어요. 컴퓨팅 리소스에 따라 bge-large나 bge-small을 임베딩 모델로 고르거나, 컨텍스트 윈도우 크기나 텍스트 청크 크기를 수정할 수도 있어요.

Qwen2.5 모델 제품군은 최대 32K 컨텍스트 윈도우 크기를 지원해요 (7B, 14B, 32B, 72B는 최대 128K까지 지원하며 추가 설정이 필요해요).

import torch
from llama_index.core import Settings
from llama_index.core.node_parser import SentenceSplitter
from llama_index.llms.huggingface import HuggingFaceLLM
from llama_index.embeddings.huggingface import HuggingFaceEmbedding

# Set prompt template for generation (optional)
from llama_index.core import PromptTemplate

def completion_to_prompt(completion):
   return f"<|im_start|>system\n<|im_end|>\n<|im_start|>user\n{completion}<|im_end|>\n<|im_start|>assistant\n"

def messages_to_prompt(messages):
    prompt = ""
    for message in messages:
        if message.role == "system":
            prompt += f"<|im_start|>system\n{message.content}<|im_end|>\n"
        elif message.role == "user":
            prompt += f"<|im_start|>user\n{message.content}<|im_end|>\n"
        elif message.role == "assistant":
            prompt += f"<|im_start|>assistant\n{message.content}<|im_end|>\n"

    if not prompt.startswith("<|im_start|>system"):
        prompt = "<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n" + prompt

    prompt = prompt + "<|im_start|>assistant\n"

    return prompt

# Set Qwen2.5 as the language model and set generation config
Settings.llm = HuggingFaceLLM(
    model_name="Qwen/Qwen2.5-7B-Instruct",
    tokenizer_name="Qwen/Qwen2.5-7B-Instruct",
    context_window=30000,
    max_new_tokens=2000,
    generate_kwargs={"temperature": 0.7, "top_k": 50, "top_p": 0.95},
    messages_to_prompt=messages_to_prompt,
    completion_to_prompt=completion_to_prompt,
    device_map="auto",
)

# Set embedding model
Settings.embed_model = HuggingFaceEmbedding(
    model_name = "BAAI/bge-base-en-v1.5"
)

# Set the size of the text chunk for retrieval
Settings.transformations = [SentenceSplitter(chunk_size=1024)]

인덱스 구축

이제 문서나 웹사이트에서 인덱스를 구축할 수 있어요.

다음 코드는 document라는 로컬 폴더에 있는 파일(PDF 또는 TXT 형식)들에 대한 인덱스를 만드는 방법을 보여줘요.

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

documents = SimpleDirectoryReader("./document").load_data()
index = VectorStoreIndex.from_documents(
    documents,
    embed_model=Settings.embed_model,
    transformations=Settings.transformations
)

다음 코드는 웹사이트 목록의 콘텐츠에 대한 인덱스를 만드는 방법을 보여줘요.

from llama_index.readers.web import SimpleWebPageReader
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

documents = SimpleWebPageReader(html_to_text=True).load_data(
    ["web_address_1","web_address_2",...]
)
index = VectorStoreIndex.from_documents(
    documents,
    embed_model=Settings.embed_model,
    transformations=Settings.transformations
)

인덱스를 저장하고 불러오려면 다음 코드를 사용할 수 있어요.

from llama_index.core import StorageContext, load_index_from_storage

# save index
storage_context = StorageContext.from_defaults(persist_dir="save")

# load index
index = load_index_from_storage(storage_context)

RAG

이제 쿼리를 수행할 수 있고, Qwen2.5가 인덱싱된 문서의 내용을 바탕으로 답변할 거예요.

query_engine = index.as_query_engine()
your_query = "<your query here>"
print(query_engine.query(your_query).response)

더 알아보기 (Learn more)