LlamaIndex

WeaveはLlamaIndex Pythonライブラリを通じて行われるすべての呼び出しの追跡とログ記録を簡素化するように設計されています。 LLMを扱う際、デバッグは避けられません。モデル呼び出しが失敗したり、出力の形式が間違っていたり、ネストされたモデル呼び出しが混乱を招いたりする場合、問題を特定することは難しい場合があります。LlamaIndexアプリケーションは多くの場合、複数のステップとLLM呼び出しで構成されており、チェーンやエージェントの内部動作を理解することが重要です。 Weaveは、LlamaIndexアプリケーションのトレースを自動的にキャプチャすることでこのプロセスを簡素化します。これにより、アプリケーションのパフォーマンスを監視および分析し、LLMワークフローのデバッグと最適化が容易になります。Weaveは評価ワークフローにも役立ちます。

はじめに

開始するには、スクリプトの先頭で単にweave.init()を呼び出すだけです。weave.init()の引数は、トレースを整理するのに役立つプロジェクト名です。
import weave
from llama_index.core.chat_engine import SimpleChatEngine

# Initialize Weave with your project name
# highlight-next-line
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は、プロンプトテンプレート、LLM呼び出し、ツール、エージェントステップなど、LlamaIndexライブラリを通じて行われるすべての呼び出しを自動的に追跡します。Weaveウェブインターフェイスでトレースを表示できます。 以下はLlamaIndexのStarter Tutorial (OpenAI)からの単純なRAGパイプラインの例です:
import weave
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

# Initialize Weave with your project name
# highlight-next-line
weave.init("llamaindex_demo")

# Assuming you have a `.txt` file in the `data` directory
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)
トレースタイムラインは「イベント」だけでなく、実行時間、コスト、該当する場合はトークン数も記録します。各ステップの入力と出力を確認するには、トレースを掘り下げてください。 llamaindex_rag.png

ワンクリック観測性 🔭

LlamaIndexはone-click observability 🔭を提供し、本番環境で原則に基づいたLLMアプリケーションを構築できるようにします。 私たちの統合はLlamaIndexのこの機能を活用し、自動的にWeaveCallbackHandler()llama_index.core.global_handlerに設定します。したがって、LlamaIndexとWeaveのユーザーとして、あなたがする必要があるのはWeaveランを初期化することだけです - weave.init(<name-of-project>)

作成するModelより簡単な実験のために

プロンプト、モデル構成、推論パラメータなど、複数のコンポーネントを持つさまざまなユースケースのアプリケーションでLLMを整理および評価することは難しいです。weave.Modelを使用すると、システムプロンプトや使用するモデルなどの実験の詳細をキャプチャして整理し、異なるイテレーションを比較しやすくなります。 次の例は、WeaveModelでLlamaIndexクエリエンジンを構築する方法を示しています。weave/data folder:
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:
"""

# highlight-next-line
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,
        )

# highlight-next-line
    @weave.op()
    def predict(self, query: str):
        query_engine = self.get_query_engine(
            # This data can be found in the weave repo under data/paul_graham
            "data/paul_graham",
        )
        response = query_engine.query(query)
        return {"response": response.response}

# highlight-next-line
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)

# highlight-next-line
@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)}

# highlight-next-line
evaluation = weave.Evaluation(dataset=eval_examples, scorers=[correctness_evaluator])

rag_pipeline = SimpleRAGPipeline()

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