メインコンテンツへスキップ
Weave は、LlamaIndex の Python ライブラリ を介して行われるすべての呼び出しのトラッキングとログ取得を簡単にするよう設計されています。 LLM を扱う際、デバッグは避けられません。モデル呼び出しが失敗したり、出力の形式が崩れたり、ネストしたモデル呼び出しが混乱を招いたりすると、問題の特定は困難になりがちです。LlamaIndex アプリケーションは、複数のステップや LLM 呼び出しから構成されることが多く、チェーンやエージェントの内部動作を把握することが重要です。 Weave は、LlamaIndex アプリケーションのトレースを自動的に取得することで、このプロセスを簡素化します。これにより、アプリケーションのパフォーマンスを監視・分析しやすくなり、LLM ワークフローのデバッグや最適化が容易になります。さらに、評価ワークフローの実行にも役立ちます。

はじめに

まずは、スクリプトの冒頭で weave.init() を呼び出します。weave.init() の引数には、トレースを整理するためのプロジェクト名を指定します。
import weave
from llama_index.core.chat_engine import SimpleChatEngine

# プロジェクト名でWeaveを初期化する
weave.init("llamaindex_demo")

chat_engine = SimpleChatEngine.from_defaults()
response = chat_engine.chat(
    "Say something profound and romantic about fourth of July"
)
print(response)
上の例では、内部で OpenAI への呼び出しを行うシンプルな LlamaIndex チャットエンジンを作成しています。以下のトレースを確認してください: simple_llamaindex.png

トレーシング

LlamaIndex は、データと LLM を簡単に接続できることで知られています。シンプルな RAG アプリケーションには、埋め込みステップ、検索ステップ、応答合成ステップが必要です。アプリケーションが複雑になるにつれて、開発と本番の両方において、各ステップのトレースを集中管理されたデータベースに保存することが重要になります。 これらのトレースは、アプリケーションのデバッグや改善に不可欠です。Weave は、LlamaIndex ライブラリ経由で実行されるすべての呼び出しを自動的に追跡します。これには、プロンプトテンプレート、LLM 呼び出し、ツール、エージェントステップが含まれます。トレースは Weave の Web インターフェースで確認できます。 以下は、LlamaIndex の Starter Tutorial (OpenAI) にあるシンプルな RAG パイプラインの例です。
import weave
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

# プロジェクト名でWeaveを初期化する
weave.init("llamaindex_demo")

# `data` ディレクトリに `.txt` ファイルが存在することを前提とする
documents = SimpleDirectoryReader("data").load_data()
index = VectorStoreIndex.from_documents(documents)

query_engine = index.as_query_engine()
response = query_engine.query("What did the author do growing up?")
print(response)
Trace timeline では、単に「events」を記録するだけでなく、該当する場合には実行時間、コスト、トークン数も記録します。トレースを掘り下げていくことで、各ステップの入力と出力を確認できます。 llamaindex_rag.png

ワンクリックでのオブザーバビリティ 🔭

LlamaIndex は、本番環境で原則に基づいた LLM アプリケーションを構築できるようにするために、ワンクリックでのオブザーバビリティ 🔭 を提供します。 本インテグレーションでは LlamaIndex のこの機能を活用し、自動的に WeaveCallbackHandler()llama_index.core.global_handler に設定します。そのため、LlamaIndex と Weave を利用するユーザーは Weave の run を初期化するだけで済みます。具体的には weave.init(<name-of-project>) を実行してください。

実験を容易にするために Model を作成する

さまざまなユースケース向けのアプリケーション内で LLM を整理して評価することは、プロンプト、モデルの設定、推論パラメータなど複数のコンポーネントが関わるため困難です。weave.Model を使用すると、システムプロンプトや使用するモデルなどの実験に関する詳細を記録・整理できるため、異なるイテレーションの比較が容易になります。 次の例では、weave/data フォルダ内のデータを使用して、WeaveModel 内に LlamaIndex のクエリエンジンを構築する方法を示します。
import weave

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.core.node_parser import SentenceSplitter
from llama_index.llms.openai import OpenAI
from llama_index.core import PromptTemplate


PROMPT_TEMPLATE = """
You are given with relevant information about Paul Graham. Answer the user query only based on the information provided. Don't make up stuff.

User Query: {query_str}
Context: {context_str}
Answer:
"""

class SimpleRAGPipeline(weave.Model):
    chat_llm: str = "gpt-4"
    temperature: float = 0.1
    similarity_top_k: int = 2
    chunk_size: int = 256
    chunk_overlap: int = 20
    prompt_template: str = PROMPT_TEMPLATE

    def get_llm(self):
        return OpenAI(temperature=self.temperature, model=self.chat_llm)

    def get_template(self):
        return PromptTemplate(self.prompt_template)

    def load_documents_and_chunk(self, data):
        documents = SimpleDirectoryReader(data).load_data()
        splitter = SentenceSplitter(
            chunk_size=self.chunk_size,
            chunk_overlap=self.chunk_overlap,
        )
        nodes = splitter.get_nodes_from_documents(documents)
        return nodes

    def get_query_engine(self, data):
        nodes = self.load_documents_and_chunk(data)
        index = VectorStoreIndex(nodes)

        llm = self.get_llm()
        prompt_template = self.get_template()

        return index.as_query_engine(
            similarity_top_k=self.similarity_top_k,
            llm=llm,
            text_qa_template=prompt_template,
        )

    @weave.op()
    def predict(self, query: str):
        query_engine = self.get_query_engine(
            # このデータはweaveリポジトリのdata/paul_grahamフォルダにあります
            "data/paul_graham",
        )
        response = query_engine.query(query)
        return {"response": response.response}

weave.init("test-llamaindex-weave")

rag_pipeline = SimpleRAGPipeline()
response = rag_pipeline.predict("What did the author do growing up?")
print(response)
この SimpleRAGPipeline クラスは weave.Model のサブクラスとして定義されており、この RAG パイプラインの重要なパラメータを整理しています。query メソッドに weave.op() をデコレートすることで、トレースできるようになります。 llamaindex_model.png

weave.Evaluation で評価を行う

評価は、アプリケーションのパフォーマンスを測定するのに役立ちます。weave.Evaluation クラスを使用すると、特定のタスクやデータセットに対してモデルがどの程度良く機能しているかを記録できるため、異なるモデルやアプリケーションの反復バージョンを比較しやすくなります。次の例では、作成したモデルをどのように評価するかを示します。
import asyncio
from llama_index.core.evaluation import CorrectnessEvaluator

eval_examples = [
    {
        "id": "0",
        "query": "What programming language did Paul Graham learn to teach himself AI when he was in college?",
        "ground_truth": "Paul Graham learned Lisp to teach himself AI when he was in college.",
    },
    {
        "id": "1",
        "query": "What was the name of the startup Paul Graham co-founded that was eventually acquired by Yahoo?",
        "ground_truth": "The startup Paul Graham co-founded that was eventually acquired by Yahoo was called Viaweb.",
    },
    {
        "id": "2",
        "query": "What is the capital city of France?",
        "ground_truth": "I cannot answer this question because no information was provided in the text.",
    },
]

llm_judge = OpenAI(model="gpt-4", temperature=0.0)
evaluator = CorrectnessEvaluator(llm=llm_judge)

@weave.op()
def correctness_evaluator(query: str, ground_truth: str, output: dict):
    result = evaluator.evaluate(
        query=query, reference=ground_truth, response=output["response"]
    )
    return {"correctness": float(result.score)}

evaluation = weave.Evaluation(dataset=eval_examples, scorers=[correctness_evaluator])

rag_pipeline = SimpleRAGPipeline()

asyncio.run(evaluation.evaluate(rag_pipeline))
この評価は前のセクションの例に基づいています。weave.Evaluation を使って評価するには、評価用データセット、scorer 関数、および weave.Model が必要です。これら 3 つの主要コンポーネントについて、次のようないくつかの注意点があります。
  • 評価サンプルの dict のキーが、scorer 関数および weave.Modelpredict メソッドの引数と一致していることを確認してください。
  • weave.Model には、predictinfer、または forward という名前のメソッドが必要です。このメソッドをトレースするために、weave.op() でデコレートしてください。
  • scorer 関数は weave.op() でデコレートし、名前付き引数として output を受け取る必要があります。
llamaindex_evaluation.png Weave を LlamaIndex と統合することで、LLM アプリケーションの包括的なロギングとモニタリングを行うことができ、評価を用いたデバッグやパフォーマンス最適化を容易に行えます。