メインコンテンツへスキップ

Documentation Index

Fetch the complete documentation index at: https://docs.wandb.ai/llms.txt

Use this file to discover all available pages before exploring further.

このガイドでは、Serverless Inference で W&B Weave を使う方法を紹介します。Serverless Inference を使うと、自前のインフラストラクチャーを用意したり、複数のプロバイダーの APIキー を管理したりすることなく、すぐに使えるオープンソースモデルで LLM アプリケーションを構築し、トレースできます。W&B APIキー があれば、Serverless Inference でホストされているすべてのモデル を利用できます。

このガイドで学べること

このガイドでは、次のことを学びます。
  • Weave と Serverless Inference を設定する
  • 自動トレースを備えた基本的な LLM アプリケーションを構築する
  • 複数のモデルを比較する
  • データセットに対するモデル性能を評価する
  • Weave UI で結果を確認する

前提条件

  • W&Bアカウント
  • Python 3.8+ または Node.js 18+
  • 必要なパッケージがインストールされていること:
    • Python: pip install weave openai
    • TypeScript: npm install weave openai
  • OpenAI APIキー が環境変数として設定されていること

最初の LLM 呼び出しをトレースする

まず、次のコード例をコピー&ペーストしてください。このコード例では、Serverless Inference の Llama 3.1-8B を使用します。 このコードを実行すると、Weave は次のことを行います。
  • LLM 呼び出しを自動的にトレースします
  • 入力、出力、レイテンシ、トークン使用量をログします
  • Weave UI でトレースを表示するためのリンクを提供します
import weave
import openai

# Weave を初期化します - your-team/your-project に置き換えてください
weave.init("<team-name>/inference-quickstart")

# Serverless Inference を指す OpenAI 互換クライアントを作成します
client = openai.OpenAI(
    base_url='https://api.inference.wandb.ai/v1',
    api_key="YOUR_WANDB_API_KEY",  # 実際の APIキー に置き換えてください
    project="<team-name>/my-first-weave-project",  # 使用状況のトラッキングに必須です
)

# トレースを有効にするために関数をデコレートします。標準の OpenAI クライアントを使用します
@weave.op()
def ask_llama(question: str) -> str:
    response = client.chat.completions.create(
        model="meta-llama/Llama-3.1-8B-Instruct",
        messages=[
            {"role": "system", "content": "あなたは役に立つアシスタントです。"},
            {"role": "user", "content": question}
        ],
    )
    return response.choices[0].message.content

# 関数を呼び出します - Weave が自動的にすべてをトレースします
result = ask_llama("LLM 開発で W&B Weave を使用する利点は何ですか?")
print(result)

テキスト要約アプリケーションを構築する

次に、このコードを実行してみてください。これは、Weave がネストした処理をどのようにトレースするかを示すシンプルな要約アプリです。
import weave
import openai

# Weave を初期化します - "<>" で囲まれた値を実際の値に置き換えてください。
weave.init("<team-name>/inference-quickstart")

client = openai.OpenAI(
    base_url='https://api.inference.wandb.ai/v1',
    api_key="YOUR_WANDB_API_KEY",  # 実際の API キーに置き換えてください
    project="<team-name>/my-first-weave-project",  # 使用状況のトラッキングに必須
)

@weave.op()
def extract_key_points(text: str) -> list[str]:
    """Extract key points from a text."""
    response = client.chat.completions.create(
        model="meta-llama/Llama-3.1-8B-Instruct",
        messages=[
            {"role": "system", "content": "Extract 3-5 key points from the text. Return each point on a new line."},
            {"role": "user", "content": text}
        ],
    )
    # 空白行を除いてレスポンスを返します
    return [line for line in response.choices[0].message.content.strip().splitlines() if line.strip()]

@weave.op()
def create_summary(key_points: list[str]) -> str:
    """Create a concise summary based on key points."""
    points_text = "\n".join(f"- {point}" for point in key_points)
    response = client.chat.completions.create(
        model="meta-llama/Llama-3.1-8B-Instruct",
        messages=[
            {"role": "system", "content": "Create a one-sentence summary based on these key points."},
            {"role": "user", "content": f"Key points:\n{points_text}"}
        ],
    )
    return response.choices[0].message.content

@weave.op()
def summarize_text(text: str) -> dict:
    """Main summarization pipeline."""
    key_points = extract_key_points(text)
    summary = create_summary(key_points)
    return {
        "key_points": key_points,
        "summary": summary
    }

# サンプルテキストで試してみましょう
sample_text = """
The Apollo 11 mission was a historic spaceflight that landed the first humans on the Moon 
on July 20, 1969. Commander Neil Armstrong and lunar module pilot Buzz Aldrin descended 
to the lunar surface while Michael Collins remained in orbit. Armstrong became the first 
person to step onto the Moon, followed by Aldrin 19 minutes later. They spent about 
two and a quarter hours together outside the spacecraft, collecting samples and taking photographs.
"""

result = summarize_text(sample_text)
print("Key Points:", result["key_points"])
print("\nSummary:", result["summary"])

複数のモデルを比較する

Serverless Inference では、複数のモデルを利用できます。次のコードを使用して、Llama と DeepSeek の応答のパフォーマンスを比較します。
import weave
import openai

# Weave を初期化します - your-team/your-project に置き換えてください
weave.init("<team-name>/inference-quickstart")

client = openai.OpenAI(
    base_url='https://api.inference.wandb.ai/v1',
    api_key="YOUR_WANDB_API_KEY",  # 実際のAPIキーに置き換えてください
    project="<team-name>/my-first-weave-project",  # 使用状況のトラッキングに必須
)

# 異なる LLM を比較するための Model クラスを定義します
class InferenceModel(weave.Model):
    model_name: str
    
    @weave.op()
    def predict(self, question: str) -> str:
        response = client.chat.completions.create(
            model=self.model_name,
            messages=[
                {"role": "user", "content": question}
            ],
        )
        return response.choices[0].message.content

# 異なるモデルのインスタンスを作成します
llama_model = InferenceModel(model_name="meta-llama/Llama-3.1-8B-Instruct")
deepseek_model = InferenceModel(model_name="deepseek-ai/DeepSeek-V3.1")

# 応答を比較します
test_question = "Explain quantum computing in one paragraph for a high school student."

print("Llama 3.1 8B response:")
print(llama_model.predict(test_question))
print("\n" + "="*50 + "\n")
print("DeepSeek V3 response:")
print(deepseek_model.predict(test_question))

モデル性能を評価する

Weave に組み込まれている EvaluationLogger を使用して、Q&A タスクにおけるモデルの性能を評価します。これにより、自動集約、トークン使用量の取得、UI での高度な比較機能を備えた、構造化された評価のトラッキングが可能になります。 前のセクションで使用したスクリプトに、次のコードを追記します:
from typing import Optional
from weave import EvaluationLogger

# シンプルなデータセットを作成する
dataset = [
    {"question": "What is 2 + 2?", "expected": "4"},
    {"question": "What is the capital of France?", "expected": "Paris"},
    {"question": "Name a primary color", "expected_one_of": ["red", "blue", "yellow"]},
]

# Scorer を定義する
@weave.op()
def accuracy_scorer(expected: str, output: str, expected_one_of: Optional[list[str]] = None) -> dict:
    """Score the accuracy of the model output."""
    output_clean = output.strip().lower()
    
    if expected_one_of:
        is_correct = any(option.lower() in output_clean for option in expected_one_of)
    else:
        is_correct = expected.lower() in output_clean
    
    return {"correct": is_correct, "score": 1.0 if is_correct else 0.0}

# Weave の EvaluationLogger を使用してモデルを評価する
def evaluate_model(model: InferenceModel, dataset: list[dict]):
    """Run evaluation on a dataset using Weave's built-in evaluation framework."""
    # モデルを呼び出す前に EvaluationLogger を初期化してトークン使用量を取得する
    # これはサーバーレス Inference のコストをトラッキングする際に特に重要です
    # モデル名を有効な形式に変換する(英数字以外の文字をアンダースコアに置換)
    safe_model_name = model.model_name.replace("/", "_").replace("-", "_").replace(".", "_")
    eval_logger = EvaluationLogger(
        model=safe_model_name,
        dataset="qa_dataset"
    )
    
    for example in dataset:
        # モデルの予測を取得する
        output = model.predict(example["question"])
        
        # 予測をログする
        pred_logger = eval_logger.log_prediction(
            inputs={"question": example["question"]},
            output=output
        )
        
        # output をスコアリングする
        score = accuracy_scorer(
            expected=example.get("expected", ""),
            output=output,
            expected_one_of=example.get("expected_one_of")
        )
        
        # スコアをログする
        pred_logger.log_score(
            scorer="accuracy",
            score=score["score"]
        )
        
        # この予測のログを完了する
        pred_logger.finish()
    
    # サマリーをログする - Weave が精度スコアを自動的に集計します
    eval_logger.log_summary()
    print(f"Evaluation complete for {model.model_name} (logged as: {safe_model_name}). View results in the Weave UI.")

# 複数のモデルを比較する - Weave の評価フレームワークの主要機能
models_to_compare = [
    llama_model,
    deepseek_model,
]

for model in models_to_compare:
    evaluate_model(model, dataset)

# Weave UI で Evals タブにアクセスし、モデル間の結果を比較する
これらの例を実行すると、ターミナルにトレースへのリンクが表示されます。いずれかのリンクをクリックすると、Weave UIでトレースを確認できます。 Weave UIでは、次のことができます。
  • すべてのLLM Callのタイムラインを確認する
  • 各operationの入力と出力を調べる
  • トークン使用量と推定コストを表示する (EvaluationLoggerが自動的に取得)
  • レイテンシとパフォーマンスのメトリクスを分析する
  • Evals タブにアクセスして、集計された評価結果を確認する
  • Compare 機能を使用して、異なるモデル間のパフォーマンスを分析する
  • 個々の例を順に見ながら、同じ入力に対して異なるモデルがどのようなパフォーマンスを示したかを確認する

利用可能なモデル

利用可能なモデルの一覧については、Serverless Inference ドキュメントの利用可能なモデル セクションを参照してください。

次のステップ

トラブルシューティング