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

# 使用例

> 実践的なコード例で Serverless Inference の使い方を学びます


ここでは、Serverless Inference を Weave で使用して、トレース、評価、比較を行う方法をサンプルで紹介します。各サンプルを順に試しながら、モデルの Call をインストルメントしてその動作を観察する方法、データセットを使ってパフォーマンスを測定する方法、複数のモデルを並べて比較する方法を学びましょう。

以下のセクションでは、基本的なトレースのサンプルと、より高度な評価ワークフローについて順を追って説明します。どちらのサンプルを実行する場合も、事前に[前提条件](/ja/products/inference/serverless/prerequisites)を済ませておいてください。

<h2 id="basic-example-trace-llama-31-8b-with-weave">
  基本的な例：Weave で Llama 3.1 8B をトレースする
</h2>

この例では、Llama 3.1 8B モデルにプロンプトを送信し、その Call を Weave でトレースする方法を紹介します。トレースを使用すると、LLM Call の入力と出力をすべて取得し、パフォーマンスを監視して、Weave UI で結果を分析できます。

<Tip>
  詳しくは、[Weave でのトレース](/ja/products/wandb/weave/guides/tracking/tracing) を参照してください。
</Tip>

この例の内容は次のとおりです。

* `@weave.op()` でデコレートした、チャット補完リクエストを送信する関数を定義します。
* Weave がトレースを記録し、W\&B の entity と project に関連付けます。
* Weave が関数を自動的にトレースし、入力、出力、レイテンシー、メタデータをログします。
* 結果がターミナルに出力され、トレースが [Forge](https://forge.coreweave.com/wandb) の **Traces** タブに表示されます。

```python theme={"system"}
import weave
import openai

# トレース先となる Weave のチームと project を設定します
weave.init("[YOUR-TEAM]/[YOUR-PROJECT]")

client = openai.OpenAI(
    base_url='https://api.inference.wandb.ai/v1',

    # APIキーは https://forge.coreweave.com/settings で作成します
    api_key="[YOUR-API-KEY]",

    # オプション: 使用量のトラッキングに使用するチームと project
    project="wandb/inference-demo",
)

# Weave でモデルの Call をトレースします
@weave.op()
def run_chat():
    response = client.chat.completions.create(
        model="meta-llama/Llama-3.1-8B-Instruct",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "Tell me a joke."}
        ],
    )
    return response.choices[0].message.content

# 関数を実行し、トレースした Call をログします
output = run_chat()
print(output)
```

コードを実行したら、次のいずれかの方法で Weave のトレースを確認します。

* ターミナルに出力されたリンクをクリックします。例: `https://wandb.ai/[YOUR-TEAM]/[YOUR-PROJECT]/r/call/01977f8f-839d-7dda-b0c2-27292ef0e04g`
* [Forge](https://forge.coreweave.com/wandb) にアクセスし、**Traces** タブを選択します。

基本的なトレースが動作することを確認できたら、個々の Call を確認するだけにとどまらない、より高度なワークフローに進みましょう。

<h2 id="advanced-example-use-weave-evaluations-and-leaderboards">
  応用例: Weave の評価と Leaderboard を使用する
</h2>

モデルの Call をトレースするだけでなく、パフォーマンスを評価して Leaderboard をパブリッシュすることもできます。この例では、質問応答データセットを使用して 2 つのモデルを比較し、同じプロンプトに対する Llama 3.1 8B と DeepSeek V3.1 のパフォーマンスの違いを示します。

```python theme={"system"}
import os
import asyncio
import openai
import weave
from weave.flow import leaderboard
from weave.trace.ref_util import get_ref

# トレースに使用する Weave のチームと project を設定します
weave.init("[YOUR-TEAM]/[YOUR-PROJECT]")

dataset = [
    {"input": "What is 2 + 2?", "target": "4"},
    {"input": "Name a primary color.", "target": "red"},
]

@weave.op
def exact_match(target: str, output: str) -> float:
    return float(target.strip().lower() == output.strip().lower())

class WBInferenceModel(weave.Model):
    model: str

    @weave.op
    def predict(self, prompt: str) -> str:
        client = openai.OpenAI(
            base_url="https://api.inference.wandb.ai/v1",
            # APIキーは https://forge.coreweave.com/settings で作成します
            api_key="[YOUR-API-KEY]",
            # オプション: 使用量のトラッキングに使用するチームと project
            project="[YOUR-TEAM]/[YOUR-PROJECT]",
        )
        resp = client.chat.completions.create(
            model=self.model,
            messages=[{"role": "user", "content": prompt}],
        )
        return resp.choices[0].message.content

llama = WBInferenceModel(model="meta-llama/Llama-3.1-8B-Instruct")
deepseek = WBInferenceModel(model="deepseek-ai/DeepSeek-V3.1")

def preprocess_model_input(example):
    return {"prompt": example["input"]}

evaluation = weave.Evaluation(
    name="QA",
    dataset=dataset,
    scorers=[exact_match],
    preprocess_model_input=preprocess_model_input,
)

async def run_eval():
    await evaluation.evaluate(llama)
    await evaluation.evaluate(deepseek)

asyncio.run(run_eval())

spec = leaderboard.Leaderboard(
    name="Inference Leaderboard",
    description="Compare models on a QA dataset",
    columns=[
        leaderboard.LeaderboardColumn(
            evaluation_object_ref=get_ref(evaluation).uri(),
            scorer_name="exact_match",
            summary_metric_path="mean",
        )
    ],
)

weave.publish(spec)
```

このコードを実行したら、[Forge](https://forge.coreweave.com/wandb) で W\&B アカウントにアクセスし、次の操作を行います。

* **Traces** タブを選択して、[トレースを表示](/ja/products/wandb/weave/guides/tracking/tracing)します。
* **Evals** タブを選択して、[モデル評価を表示](/ja/products/wandb/weave/guides/core-types/evaluations)します。
* **Leaders** タブを選択して、[生成された Leaderboard を表示](/ja/products/wandb/weave/guides/core-types/leaderboards)します。

<Frame>
  <img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/inference/_media/inference-advanced-evals.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=a86744b0e39f4daaf96ea6e05272c095" alt="モデル評価を表示" width="2912" height="1194" data-path="products/inference/_media/inference-advanced-evals.png" />
</Frame>

<Frame>
  <img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/inference/_media/inference-advanced-leaderboard.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=a0d8acb108352204e2117f682aae936f" alt="Leaderboard を表示" width="2912" height="1194" data-path="products/inference/_media/inference-advanced-leaderboard.png" />
</Frame>

両方のサンプルを完了すると、トレースされた一連のモデルの Call、パブリッシュされた評価、そしてデータセットでモデルを比較する Leaderboard が揃います。

<h2 id="next-steps">
  次のステップ
</h2>

Serverless Inference についてさらに詳しく知るには、次の操作をお試しください。

* 利用可能なすべてのメソッドについては、[API リファレンス](/ja/products/inference/serverless/api-reference)を参照してください。
* [UI](/ja/products/inference/serverless/ui-guide) でモデルを試してみましょう。


## Related topics

- [Serverless Inference](/ja/products/wandb/weave/guides/integrations/inference.md)
