> ## 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.

# Intro to Weave Hello Eval

<Note>
  これはインタラクティブなノートブックです。ローカルで実行するか、以下のリンクを使用できます：

  * [Open in Google Colab](https://colab.research.google.com/github/wandb/weave/blob/master/docs/notebooks/Intro_to_Weave_Hello_Eval.ipynb)
  * [View source on GitHub](https://github.com/wandb/weave/blob/master/docs/notebooks/Intro_to_Weave_Hello_Eval.ipynb)
</Note>

## 🔑 前提条件

Weave評価を実行する前に、以下の前提条件を完了してください。

1. W\&B Weave SDKをインストールし、[API key](https://wandb.ai/settings#api)でログインします。
2. OpenAI SDKをインストールし、[API key](https://platform.openai.com/api-keys)でログインします。
3. W\&Bプロジェクトを初期化します。

```python
# Install dependancies and imports
!pip install wandb weave openai -q

import os
from getpass import getpass

from openai import OpenAI
from pydantic import BaseModel

import weave

# 🔑 Setup your API keys
# Running this cell will prompt you for your API key with `getpass` and will not echo to the terminal.
#####
print("---")
print(
    "You can find your Weights and Biases API key here: https://wandb.ai/settings#api"
)
os.environ["WANDB_API_KEY"] = getpass("Enter your Weights and Biases API key: ")
print("---")
print("You can generate your OpenAI API key here: https://platform.openai.com/api-keys")
os.environ["OPENAI_API_KEY"] = getpass("Enter your OpenAI API key: ")
print("---")
#####

# 🏠 Enter your W&B project name
weave_client = weave.init("MY_PROJECT_NAME")  # 🐝 Your W&B project name
```

## 🐝 最初の評価を実行する

以下のコードサンプルは、Weaveの`Model`と`Evaluation`APIを使用してLLMを評価する方法を示しています。まず、`weave.Model`をサブクラス化してWeaveモデルを定義し、モデル名とプロンプト形式を指定し、`predict`メソッドを`@weave.op`で追跡します。`predict`メソッドはOpenAIにプロンプトを送信し、Pydanticスキーマ（`FruitExtract`）を使用して応答を構造化された出力に解析します。次に、入力文と期待されるターゲットで構成される小さな評価データセットを作成します。次に、カスタムスコアリング関数（`@weave.op`を使用して追跡）を定義し、モデルの出力をターゲットラベルと比較します。最後に、すべてを`weave.Evaluation`でラップし、データセットとスコアラーを指定して、`evaluate()`を呼び出して評価パイプラインを非同期で実行します。

```python
# 1. Construct a Weave model
class FruitExtract(BaseModel):
    fruit: str
    color: str
    flavor: str

class ExtractFruitsModel(weave.Model):
    model_name: str
    prompt_template: str

    @weave.op()
    def predict(self, sentence: str) -> dict:
        client = OpenAI()

        response = client.beta.chat.completions.parse(
            model=self.model_name,
            messages=[
                {
                    "role": "user",
                    "content": self.prompt_template.format(sentence=sentence),
                }
            ],
            response_format=FruitExtract,
        )
        result = response.choices[0].message.parsed
        return result

model = ExtractFruitsModel(
    name="gpt4o",
    model_name="gpt-4o",
    prompt_template='Extract fields ("fruit": <str>, "color": <str>, "flavor": <str>) as json, from the following text : {sentence}',
)

# 2. Collect some samples
sentences = [
    "There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy.",
    "Pounits are a bright green color and are more savory than sweet.",
    "Finally, there are fruits called glowls, which have a very sour and bitter taste which is acidic and caustic, and a pale orange tinge to them.",
]
labels = [
    {"fruit": "neoskizzles", "color": "purple", "flavor": "candy"},
    {"fruit": "pounits", "color": "green", "flavor": "savory"},
    {"fruit": "glowls", "color": "orange", "flavor": "sour, bitter"},
]
examples = [
    {"id": "0", "sentence": sentences[0], "target": labels[0]},
    {"id": "1", "sentence": sentences[1], "target": labels[1]},
    {"id": "2", "sentence": sentences[2], "target": labels[2]},
]

# 3. Define a scoring function for your evaluation
@weave.op()
def fruit_name_score(target: dict, output: FruitExtract) -> dict:
    target_flavors = [f.strip().lower() for f in target["flavor"].split(",")]
    output_flavors = [f.strip().lower() for f in output.flavor.split(",")]
    # Check if any target flavor is present in the output flavors
    matches = any(tf in of for tf in target_flavors for of in output_flavors)
    return {"correct": matches}

# 4. Run your evaluation
evaluation = weave.Evaluation(
    name="fruit_eval",
    dataset=examples,
    scorers=[fruit_name_score],
)
await evaluation.evaluate(model)
```

## 🚀 さらに例を探していますか？

* [evlauation pipeline end-to-end](https://weave-docs.wandb.ai/tutorial-eval)の構築方法を学びましょう。
* [RAG application by building](https://weave-docs.wandb.ai/tutorial-rag)を評価する方法を学びましょう。
