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

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

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

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

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

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

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

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

自動コストトラッキングには、次の 2 つの条件が必要です。

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

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

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

```python lines theme={null}
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}")
```

<div id="add-a-custom-cost">
  ## カスタムコストの追加
</div>

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

[`add_cost`](/ja/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` に日時を設定すると、そのコストを特定の日付から有効にできます。デフォルトでは現在の日付が使用されます。

```python lines theme={null}
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),
)
```

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

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

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

```python lines theme={null}
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)
```

<div id="purge-a-custom-cost">
  ### カスタムコストをパージする
</div>

[`purge_costs`](/ja/weave/reference/python-sdk/trace/weave_client#method-purge-costs) メソッドでカスタムコストをパージします。コスト ID のリストを渡すと、Weave はそれらの ID を持つコストをパージします。

```python lines theme={null}
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])
```

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

project 全体での総支出を把握するには、Weave が返す Call ごとのコストを集計します。`get_calls()` と `include_costs=True` を使用して、project のコストを計算できます。

```python lines theme={null}
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")
```

<div id="set-up-a-custom-model-with-custom-costs">
  ### カスタムコスト付きカスタムモデルの設定
</div>

カスタムモデルとカスタムコストトラッキングを組み合わせたエンドツーエンドの walkthrough については、[カスタムモデルでコストを設定する](/ja/weave/cookbooks/custom_model_cost) の cookbook をお試しください。

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