LlamaスタックとMilvusでRAGを構築する

Llama Stackは、プロダクションAIアプリケーションを構築するためのサービス指向、APIファーストのアプローチです。Llama Stackは、開発者があらゆる場所で開発し、あらゆる場所にデプロイし、真のプロバイダー非依存でプロダクション対応のビルディングブロックを活用できるユニバーサルなスタックを提供します。Llamaスタックは、MetaのLlamaモデル、コンポーザビリティ、プロダクション対応、提携エコシステムに焦点を当てている。

このチュートリアルでは、Milvusで構成されたLlama Stackサーバーの構築方法を紹介し、ナレッジベースとして使用するプライベートデータのインポートを可能にします。その後、サーバー上でクエリを実行し、完全なRAGアプリケーションを作成します。

環境の準備

Llama Stackサーバを起動するには、ライブラリとして起動したり、ディストリビューションをビルドしたりなど、様々な方法があります。Llama Stackの各コンポーネントに対して、様々なプロバイダを選択することもできます。したがって、Llama Stackサーバーを起動する方法は数多くあります。

このチュートリアルでは、サービスを起動する例として以下の設定を使用します。他の方法で起動したい場合は、Llama Stackサーバーの起動を参照してください。

  • Milvus構成でカスタムディストリビューションを構築するためにCondaを使用します。
  • LLMプロバイダーとしてTogether AIを使用しています。
  • 埋め込みモデルとして、デフォルトのall-MiniLM-L6-v2 を使用します。

このチュートリアルでは、主にLlama Stackドキュメントの公式インストールガイドを参照しています。このチュートリアルで古い部分を見つけた場合は、公式ガイドに従うことを優先し、私たちにissueを作成してください。

Llama Stackサーバーの起動

環境の準備

LLM サービスとして Together AI を使用する必要があるため、まず公式サイトにログインしてAPI キーを申請し、API キーTOGETHER_API_KEY を環境変数として設定する必要があります。

Llama Stack のソースコードをクローンする

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

conda環境を作成し、依存関係をインストールする。

$ 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 のリモート設定の2つの方法があります。

  • 最も簡単な方法はローカル設定で、db_pathMilvus-Liteファイルをローカルに保存するパスを設定する必要があります。

  • リモート設定は大容量データの保存に適しています。

    • 大量のデータがある場合、DockerやKubernetes上にパフォーマンスの高いMilvusサーバを構築することができます。このセットアップでは、サーバURI、例えばhttp://localhost:19530uri として使用してください。デフォルトのtokenroot:Milvus です。
    • MilvusのフルマネージドクラウドサービスであるZilliz Cloudを利用する場合は、Zilliz CloudのPublic EndpointとAPI keyに対応する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

すべてがスムーズにいけば、Llama Stackサーバーがポート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
フィードバック

このページは役に立ちましたか ?