메인 콘텐츠로 건너뛰기
이 문서는 대화형 노트북입니다. 로컬에서 실행하거나 아래 링크를 사용하세요:

맞춤형 비용 모델 설정

Weave는 사용된 토큰 수와 모델을 기준으로 비용을 계산합니다. Weave는 출력에서 이 사용량과 모델 정보를 가져와 call에 연결합니다. 토큰 사용량을 자체적으로 계산하고 이를 weave에 저장하는 간단한 맞춤형 모델을 설정해 보겠습니다.

환경 설정

필요한 모든 패키지를 설치하고 임포트합니다. wandb.login()으로 쉽게 로그인할 수 있도록 환경 변수에 WANDB_API_KEY를 설정합니다(이는 Colab에 Secret으로 제공해야 합니다). 로그를 기록할 W&B 프로젝트를 name_of_wandb_project에 설정합니다. 참고: name_of_wandb_project는 트레이스를 기록할 Teams를 지정하기 위해 {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입니다
    # 문자열을 입력받아 사용 횟수, 모델 이름, 출력이 포함된 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 Call의 출력과 일치합니다
        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"]

맞춤형 비용 추가

여기서는 맞춤형 비용을 추가합니다. 이제 맞춤형 비용이 있고 call에 사용량도 있으므로, include_cost를 사용해 call을 가져올 수 있으며 call의 비용은 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
)

# 그런 다음 calls를 쿼리할 수 있으며, include_costs=True를 사용하면
# calls에 연결된 비용을 반환받습니다
calls = weave_client.get_calls(filter={"trace_roots_only": True}, include_costs=True)

list(calls)