credits adn tokens final correct setup

This commit is contained in:
IGNY8 VPS (Salman)
2025-12-20 00:36:23 +00:00
parent e041cb8e65
commit c17b22e927
13 changed files with 1170 additions and 233 deletions

View File

@@ -376,18 +376,18 @@ class AIEngine:
# Map function name to operation type
operation_type = self._get_operation_type(function_name)
# Calculate actual amount based on results
actual_amount = self._get_actual_amount(function_name, save_result, parsed, data)
# Get actual token usage from response (AI returns 'input_tokens' and 'output_tokens')
tokens_input = raw_response.get('input_tokens', 0)
tokens_output = raw_response.get('output_tokens', 0)
# Deduct credits using the new convenience method
# Deduct credits based on actual token usage
CreditService.deduct_credits_for_operation(
account=self.account,
operation_type=operation_type,
amount=actual_amount,
tokens_input=tokens_input,
tokens_output=tokens_output,
cost_usd=raw_response.get('cost'),
model_used=raw_response.get('model', ''),
tokens_input=raw_response.get('tokens_input', 0),
tokens_output=raw_response.get('tokens_output', 0),
related_object_type=self._get_related_object_type(function_name),
related_object_id=save_result.get('id') or save_result.get('cluster_id') or save_result.get('task_id'),
metadata={
@@ -399,7 +399,10 @@ class AIEngine:
}
)
logger.info(f"[AIEngine] Credits deducted: {operation_type}, amount: {actual_amount}")
logger.info(
f"[AIEngine] Credits deducted: {operation_type}, "
f"tokens: {tokens_input + tokens_output} ({tokens_input} in, {tokens_output} out)"
)
except InsufficientCreditsError as e:
# This shouldn't happen since we checked before, but log it
logger.error(f"[AIEngine] Insufficient credits during deduction: {e}")