> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-feature-automate-reference-docs-generation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Llamaindex

# LlamaIndex

Weaveは[LlamaIndex Pythonライブラリ](https://github.com/run-llama/llama_index)を通じて行われるすべての呼び出しの追跡とログ記録を簡素化するように設計されています。

LLMを扱う際、デバッグは避けられません。モデル呼び出しが失敗したり、出力の形式が間違っていたり、ネストされたモデル呼び出しが混乱を招いたりする場合、問題を特定することは難しい場合があります。[LlamaIndex](https://docs.llamaindex.ai/en/stable/)アプリケーションは多くの場合、複数のステップとLLM呼び出しで構成されており、チェーンやエージェントの内部動作を理解することが重要です。

Weaveは、LlamaIndexアプリケーションのトレースを自動的にキャプチャすることでこのプロセスを簡素化します。これにより、アプリケーションのパフォーマンスを監視および分析し、LLMワークフローのデバッグと最適化が容易になります。Weaveは評価ワークフローにも役立ちます。

## はじめに

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

```python
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](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/integrations/imgs/simple_llamaindex.png)](https://wandb.ai/wandbot/test-llamaindex-weave/weave/calls/b6b5d898-2df8-4e14-b553-66ce84661e74)

## トレーシング

LlamaIndexは、データとLLMを簡単に接続できることで知られています。単純なRAGアプリケーションには、埋め込みステップ、検索ステップ、応答合成ステップが必要です。複雑さが増すにつれて、開発中も本番環境でも個々のステップのトレースを中央データベースに保存することが重要になります。

これらのトレースは、アプリケーションのデバッグと改善に不可欠です。Weaveは、プロンプトテンプレート、LLM呼び出し、ツール、エージェントステップなど、LlamaIndexライブラリを通じて行われるすべての呼び出しを自動的に追跡します。Weaveウェブインターフェイスでトレースを表示できます。

以下はLlamaIndexの[Starter Tutorial (OpenAI)](https://docs.llamaindex.ai/en/stable/getting_started/starter_example/)からの単純なRAGパイプラインの例です：

```python
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](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/integrations/imgs/llamaindex_rag.png)](https://wandb.ai/wandbot/test-llamaindex-weave/weave/calls?filter=%7B%22traceRootsOnly%22%3Atrue%7D\&peekPath=%2Fwandbot%2Ftest-llamaindex-weave%2Fcalls%2F6ac53407-1bb7-4c38-b5a3-c302bd877a11%3Ftracetree%3D1)

## ワンクリック観測性 🔭

LlamaIndexは[one-click observability 🔭](https://docs.llamaindex.ai/en/stable/module_guides/observability/)を提供し、本番環境で原則に基づいたLLMアプリケーションを構築できるようにします。

私たちの統合はLlamaIndexのこの機能を活用し、自動的に[`WeaveCallbackHandler()`](https://github.com/wandb/weave/blob/master/weave/integrations/llamaindex/llamaindex.py)を`llama_index.core.global_handler`に設定します。したがって、LlamaIndexとWeaveのユーザーとして、あなたがする必要があるのはWeaveランを初期化することだけです - `weave.init(<name-of-project>)`

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

プロンプト、モデル構成、推論パラメータなど、複数のコンポーネントを持つさまざまなユースケースのアプリケーションでLLMを整理および評価することは難しいです。[`weave.Model`](/ja/guides/core-types/models)を使用すると、システムプロンプトや使用するモデルなどの実験の詳細をキャプチャして整理し、異なるイテレーションを比較しやすくなります。

次の例は、`WeaveModel`でLlamaIndexクエリエンジンを構築する方法を示しています。[weave/data](https://github.com/wandb/weave/tree/master/data) folder:

```python
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](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/integrations/imgs/llamaindex_model.png)](https://wandb.ai/wandbot/test-llamaindex-weave/weave/calls?filter=%7B%22traceRootsOnly%22%3Atrue%7D\&peekPath=%2Fwandbot%2Ftest-llamaindex-weave%2Fcalls%2Fa82afbf4-29a5-43cd-8c51-603350abeafd%3Ftracetree%3D1)

## 評価の実施 `weave.Evaluation`

評価はアプリケーションのパフォーマンスを測定するのに役立ちます。[`weave.Evaluation`](/ja/guides/core-types/evaluations) クラスを使用することで、モデルが特定のタスクやデータセットでどれだけうまく機能するかを把握でき、異なるモデルやアプリケーションの反復を比較しやすくなります。以下の例では、作成したモデルを評価する方法を示しています：

```python
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.Model` の `predict` メソッドの引数と一致することを確認してください。
* `weave.Model` には `predict` または `infer` または `forward` という名前のメソッドが必要です。このメソッドには `weave.op()` でトレースのための装飾をしてください。
* スコアラー関数は `weave.op()` で装飾され、`output` を名前付き引数として持つ必要があります。

[![llamaindex\_evaluation.png](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/integrations/imgs/llamaindex_evaluation.png)](https://wandb.ai/wandbot/llamaindex-weave/weave/calls?filter=%7B%22opVersionRefs%22%3A%5B%22weave%3A%2F%2F%2Fwandbot%2Fllamaindex-weave%2Fop%2FEvaluation.predict_and_score%3ANmwfShfFmgAhDGLXrF6Xn02T9MIAsCXBUcifCjyKpOM%22%5D%2C%22parentId%22%3A%2233491e66-b580-47fa-9d43-0cd6f1dc572a%22%7D\&peekPath=%2Fwandbot%2Fllamaindex-weave%2Fcalls%2F33491e66-b580-47fa-9d43-0cd6f1dc572a%3Ftracetree%3D1)

WeaveとLlamaIndexを統合することで、LLMアプリケーションの包括的なロギングとモニタリングを確保し、評価を使用したデバッグとパフォーマンス最適化を容易にすることができます。
