> ## 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의 비용을 두 가지 방식으로 추적합니다.

* **자동 비용 추적**: [지원되는 인테그레이션](/ko/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 인테그레이션](/ko/products/wandb/weave/guides/integrations)을 사용하면 Weave가 각 Call의 토큰 사용량을 자동으로 기록하고 비용을 계산합니다. 비용은 Weights & Biases UI의 트레이스 트리와 Call table에 표시됩니다. `include_costs` 매개변수를 `true`로 설정하고 Call을 쿼리하면 `call.summary["weave"]["costs"]`에서 프로그래밍 방식으로도 비용을 확인할 수 있습니다.

자동 비용 추적을 사용하려면 다음 두 가지 조건을 모두 충족해야 합니다.

* 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과 각 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`](/ko/products/wandb/weave/reference/python-sdk/trace/weave_client#method-add-cost) 메서드로 사용자 정의 비용을 추가하세요.
필수 필드는 `llm_id`, `prompt_token_cost`, `completion_token_cost` 세 가지입니다.
`llm_id`는 LLM의 이름입니다(예: `gpt-4o`). `prompt_token_cost`와 `completion_token_cost`는 해당 LLM의 토큰당 비용입니다. LLM 가격이 백만 토큰 단위로 책정되어 있다면 토큰당 가격으로 환산하세요.
`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>

사용자 정의 비용을 추가한 후에는 비용을 조회하여 값을 확인하거나, 삭제(purge)와 같은 다른 오퍼레이션에 필요한 비용 ID를 찾을 수 있습니다.

[`query_costs`](/ko/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`](/ko/products/wandb/weave/reference/python-sdk/trace/weave_client#method-purge-costs) 메서드를 사용해 사용자 정의 비용을 삭제하세요. 비용 ID 목록을 전달하면 Weave가 해당 ID의 비용을 삭제합니다.

```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">
  프로젝트의 사용자 정의 비용 계산하기
</h3>

프로젝트 전체의 총 비용을 파악하려면 Weave가 반환하는 Call별 비용을 합산하세요. `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>

맞춤형 모델과 맞춤형 비용 추적을 함께 다루는 엔드투엔드 워크스루는 [맞춤형 모델로 비용 설정하기](/ko/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" />
