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

# 맞춤형 모델 비용

> W&B Weave에서 맞춤형 모델 비용을 정의하고 추적하여 여러 LLM 공급자와 모델에 걸친 비용을 모니터링하세요.

<Note>
  이 문서는 대화형 노트북입니다. 로컬에서 실행하거나 아래 링크를 이용하세요.

  * [Google Colab에서 열기](https://colab.research.google.com/github/wandb/docs/blob/main/weave/cookbooks/source/custom_model_cost.ipynb)
  * [GitHub에서 소스 보기](https://github.com/wandb/docs/blob/main/weave/cookbooks/source/custom_model_cost.ipynb)
</Note>

<h2 id="set-up-a-custom-cost-model">
  사용자 정의 비용 모델 설정
</h2>

이 가이드에서는 자체 토큰 사용량을 보고하는 맞춤형 모델을 Weave에서 정의하고, 해당 모델에 토큰당 사용자 정의 비용을 등록한 다음, 비용 정보가 포함된 Call을 조회하는 방법을 설명합니다. Weave의 기본 제공 비용 데이터에 없는 모델을 사용하면서 트레이스와 함께 비용을 추적하려는 경우에 활용하세요.

Weave는 사용된 토큰 수와 모델을 기준으로 비용을 계산합니다.
Weave는 출력에서 사용량과 모델 정보를 가져와 해당 Call에 연결합니다.

자체적으로 토큰 사용량을 계산하고 이를 Weave에 저장하는 단순한 맞춤형 모델을 설정하세요.

<h3 id="set-up-the-environment">
  환경 설정
</h3>

필요한 패키지를 모두 설치하고 임포트하세요.
`wandb.login()`으로 로그인할 수 있도록 환경에 `WANDB_API_KEY`를 설정하세요(이 값은 Colab에 시크릿으로 등록해야 합니다).

데이터를 로깅할 W\&B 프로젝트를 `name_of_wandb_project`에 지정하세요.

<Note>
  트레이스를 로깅할 팀을 지정하려면 `name_of_wandb_project`를 `{team_name}/{project_name}` 형식으로 입력할 수도 있습니다.
</Note>

그런 다음 `weave.init()`을 호출하여 Weave 클라이언트를 가져오세요.

```python lines theme={"system"}
%pip install wandb weave datetime --quiet
python
import os

import wandb
from google.colab import userdata

import weave

os.environ["WANDB_API_KEY"] = userdata.get("WANDB_API_KEY")
name_of_wandb_project = "custom-cost-model"

wandb.login()
python
weave_client = weave.init(name_of_wandb_project)
```

<h3 id="set-up-a-model-with-weave">
  Weave로 모델 설정
</h3>

다음으로, 토큰 사용량을 직접 집계하는 Weave `Model` 서브클래스를 정의합니다. 출력 딕셔너리에 사용량 수치와 모델 이름을 담아 반환해야 Weave가 나중에 이 Call을 다음 섹션에서 정의할 사용자 정의 비용과 연결할 수 있습니다.

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

class YourModel(Model):
    attribute1: str
    attribute2: int

    def simple_token_count(self, text: str) -> int:
        return len(text) // 3

    # 여기서 직접 정의하는 맞춤형 op입니다
    # 문자열을 입력받아 사용량 카운트, 모델 이름, 출력이 담긴 dict를 반환합니다
    @weave.op()
    def custom_model_generate(self, input_data: str) -> dict:
        # 여기에 모델 로직을 작성합니다
        # 맞춤형 생성 함수는 여기에 구현합니다
        prediction = self.attribute1 + " " + input_data

        # 사용량 카운트
        prompt_tokens = self.simple_token_count(input_data)
        completion_tokens = self.simple_token_count(prediction)

        # 사용량 카운트, 모델 이름, 출력이 담긴 딕셔너리를 반환합니다
        # Weave가 이 값을 트레이스와 자동으로 연결합니다
        # 이 객체 {usage, model, output}는 OpenAI 호출의 출력 형식과 같습니다
        return {
            "usage": {
                "input_tokens": prompt_tokens,
                "output_tokens": completion_tokens,
                "total_tokens": prompt_tokens + completion_tokens,
            },
            "model": "your_model_name",
            "output": prediction,
        }

    # predict 함수에서는 맞춤형 생성 함수를 호출한 뒤 출력을 반환합니다.
    @weave.op()
    def predict(self, input_data: str) -> dict:
        # 데이터 후처리가 필요하면 여기에서 수행합니다
        outputs = self.custom_model_generate(input_data)
        return outputs["output"]
```

<h3 id="add-a-custom-cost">
  사용자 정의 비용 추가
</h3>

사용자 정의 비용을 추가하세요. 사용자 정의 비용을 추가한 후 Call에 사용량이 발생하면 `include_cost`로 Call을 가져와 `summary.weave.costs`에서 비용을 확인할 수 있습니다.

```python lines theme={"system"}
model = YourModel(attribute1="Hello", attribute2=1)
model.predict("world")

# 그런 다음 프로젝트에 사용자 정의 비용을 추가합니다
weave_client.add_cost(
    llm_id="your_model_name", prompt_token_cost=0.1, completion_token_cost=0.2
)

# 이제 Call을 쿼리할 수 있으며, include_costs=True를 지정하면
# 각 Call에 연결된 비용 정보도 함께 반환됩니다
calls = weave_client.get_calls(filter={"trace_roots_only": True}, include_costs=True)

list(calls)
```

이제 자체 토큰 사용량을 기록하는 맞춤형 모델, 해당 모델의 `llm_id`에 등록된 사용자 정의 비용, 그리고 Call별 비용 데이터가 `summary.weave.costs` 아래에 첨부된 Call을 조회하는 방법을 모두 갖추었습니다.
