메인 콘텐츠로 건너뛰기
이 노트북은 상호작용형입니다. 로컬에서 실행하거나 아래 링크를 통해 이용할 수 있습니다:

커스텀 비용 모델 설정하기

Weave는 사용된 토큰 수와 사용된 모델을 기준으로 비용을 계산합니다. Weave는 이 사용량과 모델 정보를 출력에서 가져와 호출과 연결합니다. 이제 토큰 사용량을 스스로 계산하고 그 값을 Weave에 저장하는 간단한 커스텀 모델을 설정해 보겠습니다.

환경 설정

필요한 모든 패키지를 설치하고 import 합니다. WANDB_API_KEY를 환경 변수에 설정하여 wandb.login()으로 쉽게 로그인할 수 있도록 합니다(이 값은 Colab에 secret으로 제공되어야 합니다). 로그를 남길 W&B 프로젝트를 name_of_wandb_project에 설정합니다. NOTE: name_of_wandb_project는 트레이스를 기록할 팀을 지정하기 위해 {team_name}/{project_name} 형식으로도 사용할 수 있습니다. 그런 다음 weave.init()을 호출해서 Weave 클라이언트를 가져옵니다.
%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)

Weave에서 모델 설정하기

from weave import Model

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

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

    # 이것은 우리가 정의하는 커스텀 op입니다
    # 문자열을 입력받아 사용량 카운트, 모델 이름, 출력이 담긴 사전을 반환합니다
    @weave.op()
    def custom_model_generate(self, input_data: str) -> dict:
        # 모델 로직이 여기에 들어갑니다
        # 여기에 커스텀 generate 함수를 작성하면 됩니다
        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 함수에서 커스텀 generate 함수를 호출하고 출력을 반환합니다.
    @weave.op()
    def predict(self, input_data: str) -> dict:
        # 여기에서 데이터의 후처리를 수행하면 됩니다
        outputs = self.custom_model_generate(input_data)
        return outputs["output"]

사용자 지정 비용 추가

여기서는 사용자 지정 비용을 추가합니다. 이제 사용자 지정 비용이 설정되었고 호출에 usage 정보가 있으므로, include_cost로 호출을 가져올 수 있고, 이때 각 호출의 비용은 summary.weave.costs 아래에 포함됩니다.
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
)

# 그런 다음 호출을 조회할 수 있으며, include_costs=True를 사용하면
# 호출에 비용 정보가 포함되어 반환됩니다
calls = weave_client.get_calls(filter={"trace_roots_only": True}, include_costs=True)

list(calls)