> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sambanova.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Ragas

[Ragas](https://docs.ragas.io/) は、RAG パイプラインを評価するための評価指標ライブラリです。応答のスコアリングの中核はジャッジ (judge) モデルの呼び出しであるため、ジャッジが速ければ、あらゆる評価の実行がそのまま速くなります。

## 前提条件

* [SambaCloud](https://cloud.sambanova.ai/?utm_source=ragas\&utm_medium=external\&utm_campaign=cloud_signup) のアカウントと [API キー](https://cloud.sambanova.ai/apis?utm_source=ragas\&utm_medium=external\&utm_campaign=cloud_signup)
* Python 3.9 以上

## セットアップ

**1. Ragas のインストール**

```bash theme={}
pip install "ragas==0.4.3" openai
pip install "langchain-community==0.3.30" --no-deps
```

> [!NOTE]
>
> Ragas 0.4.3 は、新しいリリースでは削除された `langchain-community` のモジュールをインポートするため、2 つ目のコマンドでこのパッケージのバージョンを固定します。pip が `langchain-core` をダウングレードしないよう、`--no-deps` は外さないでください。この後 `pip check` は、`langchain-community` が `dataclasses-json` を必要としていると報告しますが、Ragas の動作には影響しないため、この警告は無視してかまいません。

**2. SambaCloud API キーのエクスポート**

```bash theme={}
export SAMBANOVA_API_KEY="your-sambanova-api-key"
```

**3. ジャッジモデルの接続先を SambaCloud に設定**

Ragas の `llm_factory` は、カスタムの `base_url` を設定したものを含め、任意の OpenAI クライアントインスタンスを受け付けます。

```python theme={}
import os
from openai import OpenAI
from ragas.llms import llm_factory

client = OpenAI(
    api_key=os.environ["SAMBANOVA_API_KEY"],
    base_url="https://api.sambanova.ai/v1",
)

llm = llm_factory("MiniMax-M3.1-Flash", client=client)
```

## 評価指標

Ragas は、LLM がジャッジする評価指標を、出力の形によって 3 つに分類しています。以下の各例では、セットアップで作成した `llm` を使用します。

### Discrete: correct / incorrect の判定

ジャッジが正答と誤答を見分けられることを確認するため、正しい回答と誤った回答の両方をスコアリングします。

```python theme={}
from ragas.metrics import DiscreteMetric

metric = DiscreteMetric(
    name="correctness",
    prompt="Given the question and response, judge if the response correctly answers the question. Question: {query} Response: {response}. Return 'correct' or 'incorrect'.",
    allowed_values=["correct", "incorrect"],
)

# A correct answer
result = metric.score(
    llm=llm,
    query="What is the capital of France?",
    response="The capital of France is Paris.",
)
print(result.value, "-", result.reason)

# An incorrect answer
bad_result = metric.score(
    llm=llm,
    query="What is the capital of France?",
    response="The capital of France is Berlin.",
)
print(bad_result.value, "-", bad_result.reason)
```

```text Output theme={}
correct - The response correctly identifies Paris as the capital of France.
incorrect - The capital of France is Paris, not Berlin.
```

### Numeric: 連続スケールのスコア

```python theme={}
from ragas.metrics import NumericMetric

relevance = NumericMetric(
    name="relevance",
    allowed_values=(0, 10),
    prompt="Rate how relevant the response is to the query on a scale of 0 to 10. Query: {query} Response: {response}.",
)
result = relevance.score(
    llm=llm,
    query="What is the capital of France?",
    response="The capital of France is Paris, a city known for the Eiffel Tower.",
)
print(result.value, "-", result.reason)
```

```text Output theme={}
10.0 - The response directly and correctly identifies Paris as the capital of France. The additional detail about the Eiffel Tower does not detract from its relevance.
```

### Ranking: 複数の候補応答の順位付け

```python theme={}
from ragas.metrics import RankingMetric

quality_ranking = RankingMetric(
    name="quality_ranking",
    allowed_values=3,
    prompt="Given the query and a list of responses, return the indices of the responses ranked from best to worst. Query: {query} Responses: {responses}.",
)
result = quality_ranking.score(
    llm=llm,
    query="What is the capital of France?",
    responses=[
        "I don't know.",
        "France's capital is a city in Europe.",
        "The capital of France is Paris.",
    ],
)
print(result.value, "-", result.reason)
```

```text Output theme={}
['2', '1', '0'] - Response 2 directly and correctly states that the capital of France is Paris. Response 1 is vague but provides some relevant information, while Response 0 does not answer the question.
```

## データセットと実験

Ragas の `Dataset` と `@experiment` を使うと、評価指標を 1 例ずつ呼び出す代わりに、一連の入力をまとめてシステムに流し、すべての結果をスコアリングする処理を再現可能な形で実行できます。この例では、セットアップの `client` と `llm`、および Discrete の例の `metric` を使用します。

```python theme={}
import asyncio
from ragas import Dataset, experiment

dataset = Dataset(name="capitals", backend="local/csv", root_dir="./ragas_data")
dataset.append({"id": "1", "query": "What is the capital of France?", "expected_answer": "Paris"})
dataset.append({"id": "2", "query": "What is the capital of Japan?", "expected_answer": "Tokyo"})
dataset.save()


@experiment()
async def answer_and_score(row):
    completion = client.chat.completions.create(
        model="MiniMax-M3.1-Flash",
        messages=[{"role": "user", "content": row["query"]}],
    )
    response = completion.choices[0].message.content
    score = metric.score(llm=llm, query=row["query"], response=response)
    return {**row, "response": response, "correctness": score.value, "reason": score.reason}


async def main():
    results = await answer_and_score.arun(dataset)
    for r in sorted(results, key=lambda r: r["id"]):
        print(r["id"], "->", r["correctness"], "-", r["response"][:60])


asyncio.run(main())
```

```text Output theme={}
1 -> correct - The capital of France is **Paris**.
2 -> correct - The capital of Japan is **Tokyo**.
```

各行ごとに、SambaCloud のチャット補完 1 回と `DiscreteMetric` のジャッジ呼び出し 1 回が実行されます。`dataset.save()` は `ragas_data/datasets/capitals.csv` を書き出し、`arun()` はスコア付きの結果を `ragas_data/experiments/` 配下のランダムに生成された名前の CSV に書き出すため、後から実験の実行同士を比較できます。

## 対象外: 合成テストデータの生成

Ragas の RAG テストセット生成 (`TestsetGenerator`) は、ナレッジグラフを介して、手持ちのドキュメントから合成のクエリと参照回答を構築します。上のすべての例と異なり、この機能には LLM と Embedding (埋め込み) モデルの**両方**が必要です。

```python theme={}
from ragas.testset import TestsetGenerator

generator = TestsetGenerator(llm=generator_llm, embedding_model=generator_embeddings)
```

SambaCloud には Embedding モデルがないため、この機能を SambaCloud だけで実行することはできません。`E5-Mistral-7B-Instruct` などの Embedding モデルは SambaStack で利用できます。[Embeddings](https://docs.sambanova.ai/docs/ja/features/embeddings.md) をご参照ください。合成テストデータの生成が必要な場合は、この機能に限り SambaStack インスタンスの Embedding モデルを SambaCloud または SambaStack の LLM と組み合わせ、本ページの他の内容には SambaCloud を使用してください。

## トラブルシューティング

> [accordion] ModuleNotFoundError: No module named 'langchain\_community.chat\_models.vertexai'
>
> [セットアップ](#セットアップ) にあるバージョン固定付きの `langchain-community` のインストールを飛ばしています。`pip install "langchain-community==0.3.30" --no-deps` を実行してください。

> [accordion] KeyError: SAMBANOVA\_API\_KEY
>
> 実行前にキーをエクスポートしてください: `export SAMBANOVA_API_KEY="your-key"`。`echo $SAMBANOVA_API_KEY` で確認できます。

> [accordion] 入力にかかわらずジャッジが常に同じ値を返す
>
> 本番の評価で信頼する前に、上の Discrete の例のように、正しい応答と意図的に誤らせた応答の両方を評価指標に対してテストしてください。両者を区別できないジャッジは、どんなスコアを返していても、有用なシグナルを提供していません。

> [accordion] Embedding モデル未設定のまま TestsetGenerator がエラーになる
>
> これは想定どおりの動作です。合成テストデータの生成には Embedding モデルが必要ですが、SambaCloud では提供されていません。上の [対象外](#対象外-合成テストデータの生成) を参照し、この機能に限り SambaStack インスタンスの Embedding モデルを使用してください。

## 参考情報

* [Ragas ドキュメント](https://docs.ragas.io/)
* [Ragas の評価指標の概要](https://docs.ragas.io/en/stable/concepts/metrics/overview/)
* [Ragas のデータセット](https://docs.ragas.io/en/stable/concepts/datasets/)
* [Ragas の実験機能](https://docs.ragas.io/en/stable/concepts/experimentation/)
* [Ragas でのモデルのカスタマイズ](https://docs.ragas.io/en/stable/howtos/customizations/customize_models/)
* [SambaCloud の対応モデル](https://docs.sambanova.ai/docs/ja/models/sambacloud-models.md)
