Milvus와 함께 Llama Stack으로 RAG 구축하기

라마 스택은 프로덕션 AI 애플리케이션을 구축하기 위한 서비스 지향의 API 우선 접근 방식입니다. 개발자가 어디서나 개발하고, 어디서나 배포하며, 진정한 공급자 독립성을 갖춘 프로덕션 지원 빌딩 블록을 활용할 수 있는 범용 스택을 제공합니다. 라마 스택은 Meta의 라마 모델, 구성 가능성, 프로덕션 준비성, 파트너 에코시스템에 중점을 두고 있습니다.

이 튜토리얼에서는 개인 데이터를 가져와 지식창고로 사용할 수 있도록 Milvus로 구성된 Llama 스택 서버를 구축하는 방법을 소개합니다. 그런 다음 서버에서 쿼리를 수행하여 완전한 RAG 애플리케이션을 만들어 보겠습니다.

환경 준비하기

라이브러리, 배포 빌드 등 여러 가지 방법으로 Llama Stack 서버를 시작할 수 있습니다. 라마 스택의 각 구성 요소에 대해 다양한 공급자를 선택할 수도 있습니다. 따라서 라마 스택 서버를 시작하는 방법에는 여러 가지가 있습니다.

이 튜토리얼에서는 다음 구성을 예로 들어 서비스를 시작합니다. 다른 방법으로 시작하려면 라마 스택 서버 시작하기를 참조하세요.

  • Conda를 사용하여 Milvus 구성으로 사용자 정의 배포를 구축합니다.
  • LLM 공급자로는 Together AI를 사용합니다.
  • 임베딩 모델로는 기본 all-MiniLM-L6-v2 을 사용합니다.

이 튜토리얼은 주로 라마 스택 문서의 공식 설치 가이드를 참조합니다. 이 튜토리얼에서 오래된 부분을 발견하면 공식 가이드를 우선적으로 따르고 문제를 만들어 주세요.

라마 스택 서버 시작하기

환경 준비하기

LLM 서비스로 Together AI를 사용해야 하므로 먼저 공식 홈페이지에 로그인하여 API 키를 신청하고 환경 변수로 TOGETHER_API_KEY 을 설정해야 합니다.

라마 스택 소스 코드 복제

$ git clone https://github.com/meta-llama/llama-stack.git
$ cd llama-stack

콘다 환경을 생성하고 종속 요소를 설치합니다.

$ conda create -n stack python=3.10
$ conda activate stack

$ pip install -e .

llama_stack/llama_stack/template/together/run.yaml 의 내용을 수정하여 vector_io 섹션을 관련 Milvus 설정으로 변경합니다. 예를 들어 추가합니다:

vector_io:
- provider_id: milvus
  provider_type: inline::milvus
  config:
    db_path: ~/.llama/distributions/together/milvus_store.db

#  - provider_id: milvus
#    provider_type: remote::milvus
#    config:
#      uri: http://localhost:19530
#      token: root:Milvus

Llama Stack에서 Milvus는 로컬 구성( inline::milvus)과 원격 구성( remote::milvus)의 두 가지 방법으로 구성할 수 있습니다.

  • 가장 간단한 방법은 로컬 구성으로, Milvus-Lite 파일을 로컬에 저장할 경로인 db_path 를 설정해야 합니다.

  • 원격 구성은 대용량 데이터 저장에 적합합니다.

    • 대용량의 데이터가 있는 경우 Docker 또는 Kubernetes에 고성능 Milvus 서버를 설정할 수 있습니다. 이 설정에서는 서버 URI(예: http://localhost:19530)를 uri 으로 사용하세요. 기본 tokenroot:Milvus 입니다.
    • Milvus의 완전 관리형 클라우드 서비스인 Zilliz Cloud를 사용하려면 Zilliz Cloud의 공용 엔드포인트와 API 키에 해당하는 uritoken 을 조정하세요.

템플릿에서 배포 빌드하기

다음 명령어를 실행하여 배포를 빌드합니다:

$ llama stack build --template together --image-type conda

~/.llama/distributions/together/together-run.yaml 에 파일이 생성됩니다. 그런 다음 이 명령을 실행하여 서버를 시작합니다:

$ llama stack run --image-type conda ~/.llama/distributions/together/together-run.yaml

모든 것이 순조롭게 진행되면 포트 8321에서 라마 스택 서버가 성공적으로 실행되는 것을 볼 수 있습니다.

클라이언트에서 RAG 수행

서버를 시작했으면 클라이언트 코드를 작성하여 서버에 액세스할 수 있습니다. 다음은 샘플 코드입니다:

import uuid
from llama_stack_client.types import Document
from llama_stack_client.lib.agents.agent import Agent
from llama_stack_client.types.agent_create_params import AgentConfig

# See https://www.together.ai/models for all available models
INFERENCE_MODEL = "meta-llama/Llama-3.3-70B-Instruct-Turbo"
LLAMA_STACK_PORT = 8321


def create_http_client():
    from llama_stack_client import LlamaStackClient

    return LlamaStackClient(
        base_url=f"http://localhost:{LLAMA_STACK_PORT}"  # Your Llama Stack Server URL
    )


client = create_http_client()

# Documents to be used for RAG
urls = ["chat.rst", "llama3.rst", "memory_optimizations.rst", "lora_finetune.rst"]
documents = [
    Document(
        document_id=f"num-{i}",
        content=f"https://raw.githubusercontent.com/pytorch/torchtune/main/docs/source/tutorials/{url}",
        mime_type="text/plain",
        metadata={},
    )
    for i, url in enumerate(urls)
]

# Register a vector database
vector_db_id = f"test-vector-db-{uuid.uuid4().hex}"
client.vector_dbs.register(
    vector_db_id=vector_db_id,
    embedding_model="all-MiniLM-L6-v2",
    embedding_dimension=384,
    provider_id="milvus",
)

print("inserting...")
# Insert the documents into the vector database
client.tool_runtime.rag_tool.insert(
    documents=documents, vector_db_id=vector_db_id, chunk_size_in_tokens=1024,
)

agent_config = AgentConfig(
    model=INFERENCE_MODEL,
    # Define instructions for the agent ( aka system prompt)
    instructions="You are a helpful assistant",
    enable_session_persistence=False,
    # Define tools available to the agent
    toolgroups=[{"name": "builtin::rag", "args": {"vector_db_ids": [vector_db_id]}}],
)

rag_agent = Agent(client, agent_config)
session_id = rag_agent.create_session("test-session")
print("finish init agent...")
user_prompt = (
    "What are the top 5 topics that were explained? Only list succinct bullet points."
)

# Get the final answer from the agent
response = rag_agent.create_turn(
    messages=[{"role": "user", "content": user_prompt}],
    session_id=session_id,
    stream=False,
)
print(f"Response: ")
print(response.output_message.content)

이 코드를 실행하여 RAG 쿼리를 수행합니다. 모든 것이 제대로 작동하면 출력은 다음과 같아야 합니다:

inserting...
finish init agent...
Response: 
* Fine-Tuning Llama3 with Chat Data
* Evaluating fine-tuned Llama3-8B models with EleutherAI's Eval Harness
* Generating text with our fine-tuned Llama3 model
* Faster generation via quantization
* Fine-tuning on a custom chat dataset

Try Managed Milvus for Free

Zilliz Cloud is hassle-free, powered by Milvus and 10x faster.

Get Started
피드백

이 페이지가 도움이 되었나요?