Documentation Index
Fetch the complete documentation index at: https://wb-21fd5541-john-wbdocs-2044-rename-serverless-products.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
これはインタラクティブなノートブックです。ローカルで実行することも、以下のリンクを使用することもできます。
Weave の評価を実行する前に、次の準備を済ませてください。
- W&B Weave SDK をインストールし、APIキーを使用してログインします。
- OpenAI SDK をインストールし、APIキーを使用してログインします。
- W&B のプロジェクトを初期化します。
# 依存関係のインストールとインポート
!pip install wandb weave openai -q
import os
from getpass import getpass
from openai import OpenAI
from pydantic import BaseModel
import weave
# 🔑 APIキーの設定
# このセルを実行すると、`getpass` でAPIキーの入力を求められます。入力内容はターミナルに表示されません。
#####
print("---")
print(
"W&B APIキーの作成はこちら: https://wandb.ai/settings#apikeys"
)
os.environ["WANDB_API_KEY"] = getpass("W&B APIキーを入力してください: ")
print("---")
print("OpenAI APIキーはこちらで生成できます: https://platform.openai.com/api-keys")
os.environ["OPENAI_API_KEY"] = getpass("OpenAI APIキーを入力してください: ")
print("---")
#####
# 🏠 W&Bのプロジェクト名を入力してください
weave_client = weave.init("MY_PROJECT_NAME") # 🐝 W&Bのプロジェクト名
次のコードサンプルでは、Weave の Model API と Evaluation API を使って LLM を評価する方法を示します。まず、weave.Model を継承して Weave モデルを定義し、モデル名とプロンプト形式を指定したうえで、@weave.op を使って predict メソッドをトラッキングします。predict メソッドは OpenAI にプロンプトを送信し、Pydantic スキーマ (FruitExtract) を使ってレスポンスを構造化された出力として解析します。次に、入力文と期待されるターゲットからなる小規模な評価用データセットを作成します。続いて、モデルの出力とターゲットラベルを比較するカスタムのスコアリング関数 (これも @weave.op でトラッキング) を定義します。最後に、データセットと scorers を指定して、これらをまとめて weave.Evaluation に渡し、evaluate() を呼び出して評価パイプラインを非同期に実行します。
# 1. Weave モデルを構築する
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. サンプルを収集する
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. 評価用のスコアリング関数を定義する
@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(",")]
# 出力フレーバーにターゲットフレーバーが含まれているかチェックする
matches = any(tf in of for tf in target_flavors for of in output_flavors)
return {"correct": matches}
# 4. 評価を実行する
evaluation = weave.Evaluation(
name="fruit_eval",
dataset=examples,
scorers=[fruit_name_score],
)
await evaluation.evaluate(model)