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

# コストをトラッキングする

> Weave における LLM 操作の自動コストトラッキングとカスタムコストトラッキングについて説明します

Weave では、LLM Call のコストを次の 2 つの方法でトラッキングします。

* **自動コストトラッキング**: [サポートされるインテグレーション](/ja/products/wandb/weave/guides/integrations)では、Weave が API の応答からトークン使用量を取得し、モデルの組み込み料金を適用します。追加のコードは必要ありません。
* **カスタムコストトラッキング**: ファインチューニングしたモデル、セルフホストのモデル、または Weave と自動的に統合されないモデルでは、利用可能な API メソッドを使用して、カスタムコストをトラッキングするよう Weave を設定します。

<Note>
  Weave TypeScript はコストトラッキングをサポートしていません。
</Note>

<h2 id="use-automatic-cost-tracking">
  自動コストトラッキングを使用する
</h2>

`weave.init()` を呼び出し、OpenAI、Anthropic、Cohere、Mistral などの[サポートされる LLM インテグレーション](/ja/products/wandb/weave/guides/integrations)を使用すると、Weave は各 Call のトークン使用量を自動的に記録し、コストを計算します。コストは、Weights & Biases UI のトレース ツリーと Call の表に表示されます。また、`include_costs` パラメーターを `true` に設定して Call をクエリすると、`call.summary["weave"]["costs"]` からプログラムでコストを取得することもできます。

自動コストトラッキングを使用するには、次の 2 つの条件を満たす必要があります。

* LLM プロバイダがサポートされるインテグレーションであること。
* API の応答にトークン使用量が含まれていること (ほとんどのプロバイダーはデフォルトでトークン使用量を返します)。

いずれかの条件を満たしていない場合は、代わりにカスタムコストトラッキングを使用してください。

次の例は、自動で記録されたコストデータをプログラムで取得する方法を示しています。

```python lines theme={"system"}
import weave
from openai import OpenAI

weave.init("your-team/project-name")
client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "What is 2 + 2?"}],
)

import time
time.sleep(2)

# 現在の Weave クライアントのインスタンスを取得します
weave_client = weave.get_client()
# インスタンスの Call とそのコストを取得します
calls = list(weave_client.get_calls(include_costs=True, limit=1))
call = calls[0]

# Call のサマリーから、利用可能なコストフィールドを取得します
costs = call.summary.get("weave", {}).get("costs", {})
if not costs:
    print("No costs found in summary.weave.costs")
for model, cost in costs.items():
    print(f"Model: {model}")
    print(f"  Input cost:  ${cost['prompt_tokens_total_cost']:.6f}")
    print(f"  Output cost: ${cost['completion_tokens_total_cost']:.6f}")
```

<h2 id="add-a-custom-cost">
  カスタムコストを追加する
</h2>

ファインチューニングしたモデル、セルフホストのモデル、Weave が統合していないプロバイダーなど、自動コストトラッキングを使用できない場合は、カスタムコストトラッキングを使用します。以下のセクションでは、カスタムコストの追加、クエリ、削除、集計の方法について説明します。

カスタムコストを追加するには、[`add_cost`](/ja/products/wandb/weave/reference/python-sdk/trace/weave_client#method-add-cost) メソッドを使用します。
必須フィールドは `llm_id`、`prompt_token_cost`、`completion_token_cost` の 3 つです。
`llm_id` は LLM 名です (例: `gpt-4o`) 。`prompt_token_cost` と `completion_token_cost` は、その LLM のトークンあたりのコストです。LLM の料金が 100 万トークンあたりで設定されている場合は、トークンあたりの値に換算してください。
`effective_date` に datetime を設定すると、特定の日付からコストを適用できます。デフォルトは現在の日付です。

```python lines theme={"system"}
import weave
from datetime import datetime

client = weave.init("your-team/project-name")

client.add_cost(
    llm_id="your_model_name",
    prompt_token_cost=0.01,
    completion_token_cost=0.02
)

client.add_cost(
    llm_id="your_model_name",
    prompt_token_cost=10,
    completion_token_cost=20,
    effective_date=datetime(2025, 4, 22),
)
```

<h3 id="query-custom-costs">
  カスタムコストをクエリする
</h3>

カスタムコストを追加した後は、コストを取得して値を確認したり、削除などの他の操作に必要なコスト ID を調べたりできます。

[`query_costs`](/ja/products/wandb/weave/reference/python-sdk/trace/weave_client#method-query-costs) メソッドを使用してコストをクエリします。
コストのクエリ方法はいくつかあり、単一のコスト ID を渡すことも、LLM モデル名のリストを渡すこともできます。

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

client = weave.init("your-team/project-name")

costs = client.query_costs(llm_ids=["your_model_name"])

cost = client.query_costs(costs[0].id)
```

<h3 id="purge-a-custom-cost">
  カスタムコストを削除する
</h3>

カスタムコストを削除するには、[`purge_costs`](/ja/products/wandb/weave/reference/python-sdk/trace/weave_client#method-purge-costs) メソッドを使用します。コスト ID のリストを渡すと、該当する ID のコストが Weave によって削除されます。

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

client = weave.init("your-team/project-name")

costs = client.query_costs(llm_ids=["your_model_name"])
client.purge_costs([cost.id for cost in costs])
```

<h3 id="calculate-custom-costs-for-a-project">
  project のカスタムコストを計算する
</h3>

project 全体の総支出を把握するには、Weave から返される Call ごとのコストを集計します。project のコストは、`get_calls()` に `include_costs=True` を指定して計算します。

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

weave.init("your-team/project-name")

@weave.op()
def get_costs_for_project(project_name: str):
    total_cost = 0
    requests = 0

    client = weave.init(project_name)
    calls = list(
        client.get_calls(filter={"trace_roots_only": True}, include_costs=True)
    )

    for call in calls:
        if call.summary["weave"] is not None and call.summary["weave"].get("costs", None) is not None:
            for k, cost in call.summary["weave"]["costs"].items():
                requests += cost["requests"]
                total_cost += cost["prompt_tokens_total_cost"]
                total_cost += cost["completion_tokens_total_cost"]

    return {
        "total_cost": total_cost,
        "requests": requests,
        "calls": len(calls),
    }

get_costs_for_project("my_custom_cost_model")
```

<h3 id="set-up-a-custom-model-with-custom-costs">
  カスタムコストを使用してカスタムモデルを設定する
</h3>

カスタムモデルとカスタムコストトラッキングを組み合わせたエンドツーエンドの手順については、クックブック「[カスタムモデルでコストを設定する](/ja/products/wandb/weave/cookbooks/custom_model_cost)」をご覧ください。

<Card title="Colab で試す" href="https://colab.research.google.com/github/wandb/weave/blob/master/docs/./notebooks/custom_model_cost.ipynb" icon="code" />
