Skip to content

Commit

Permalink
feat(model): add usage log
Browse files Browse the repository at this point in the history
  • Loading branch information
OrenZhang committed Mar 3, 2025
1 parent bdbc15f commit a82bf87
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
12 changes: 8 additions & 4 deletions backend/apps/usage/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from django.db.models import F
from django.utils.translation import gettext_lazy
from ovinc_client.core.constants import MAX_CHAR_LENGTH
from ovinc_client.core.logger import logger
from ovinc_client.core.models import BaseModel, ForeignKey, UniqIDField


Expand Down Expand Up @@ -89,6 +90,7 @@ def record(
prompt_tokens: int,
completion_tokens: int,
usage: dict,
user_info: dict,
) -> "UsageLog":
log = cls.objects.create(
user_id=user_id,
Expand All @@ -101,10 +103,12 @@ def record(
usage=usage,
)
# pylint: disable=E1101
UserBalance.objects.filter(user_id=user_id).update(
balance=F("balance")
- (prompt_tokens * model.prompt_price / 1000 / 1000)
- (completion_tokens * model.completion_price / 1000 / 1000)
prompt_price = prompt_tokens * model.prompt_price / 1000 / 1000
completion_price = completion_tokens * model.completion_price / 1000 / 1000
total_price = prompt_price + completion_price
UserBalance.objects.filter(user_id=user_id).update(balance=F("balance") - total_price)
logger.info(
"[usage log] user: %s, tokens: %d/%s, cost: %.4f", user_info, prompt_tokens, completion_tokens, total_price
)
return log

Expand Down
1 change: 1 addition & 0 deletions backend/apps/usage/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def outlet(self, request: Request, *args, **kwargs) -> Response:
prompt_tokens=usage.get("prompt_tokens", 0),
completion_tokens=usage.get("completion_tokens", 0),
usage=usage,
user_info=req_data["user"],
)
balance = UserBalance.get_balance(
user_id=req_data["user"]["id"], user_name=req_data["user"]["name"], email=req_data["user"]["email"]
Expand Down

0 comments on commit a82bf87

Please sign in to comment.