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

カスタムコストの追加

add_cost メソッドを使用して、カスタムコストを追加できます。 必須のフィールドは llm_idprompt_token_cost、および completion_token_cost の3つです。 llm_id は LLM の名前(例:gpt-4o)です。prompt_token_costcompletion_token_cost は、その LLM のトークンあたりのコストです(LLM の価格が100万トークン単位で指定されている場合は、必ず 値 を変換してください)。 また、effective_datedatetime を設定することで、特定の日にコストを有効にすることもできます。デフォルトは現在の日付です。
import weave
from datetime import datetime

client = weave.init("my_custom_cost_model")

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),
)

コストの照会

query_costs メソッドを使用して、コストを照会できます。 コストを照会する方法はいくつかあり、単一のコスト ID を渡すか、LLM モデル名のリストを渡すことができます。
import weave

client = weave.init("my_custom_cost_model")

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

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

カスタムコストの削除

purge_costs メソッドを使用して、カスタムコストを削除できます。コスト ID のリストを渡すと、それらの ID を持つコストが削除されます。
import weave

client = weave.init("my_custom_cost_model")

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

Projects のコスト計算

少しの設定を行い、calls_query を使用して include_costs=True を追加することで、プロジェクトのコストを計算できます。
import weave

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

    client = weave.init(project_name)
    # プロジェクト内のすべての call を取得
    calls = list(
        client.get_calls(filter={"trace_roots_only": True}, include_costs=True)
    )

    for call in calls:
        # call にコストが含まれている場合、合計コストに加算
        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"]

    # 合計コスト、リクエスト数、および call 数を返す
    return {
        "total_cost": total_cost,
        "requests": requests,
        "calls": len(calls),
    }

# 関数を @weave.op() でデコレートしているため、
# 合計値は履歴コストの合計計算用に Weave に保存される
get_costs_for_project("my_custom_cost_model")

カスタムコストを使用したカスタムモデルのセットアップ

カスタムモデルでのコスト設定 のクックブックをお試しください。

Colab で試す