feat:AI 토큰 사용량 추적 기능 추가

- ai_token_usages 테이블 마이그레이션 생성
- AiTokenUsage 모델 생성
- AiReportService에 usageMetadata 추출 및 저장 로직 추가

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
김보곤
2026-02-07 09:57:12 +09:00
parent 78851ec04a
commit f45f91967f
3 changed files with 122 additions and 0 deletions

View File

@@ -3,6 +3,7 @@
namespace App\Services;
use App\Models\Tenants\AiReport;
use App\Models\Tenants\AiTokenUsage;
use App\Models\Tenants\Card;
use App\Models\Tenants\Deposit;
use App\Models\Tenants\Purchase;
@@ -13,6 +14,7 @@
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class AiReportService extends Service
{
@@ -361,6 +363,9 @@ private function callGeminiApi(array $inputData): array
$result = $response->json();
$text = $result['candidates'][0]['content']['parts'][0]['text'] ?? '';
// 토큰 사용량 저장
$this->saveTokenUsage($result, $model, 'AI리포트');
// JSON 파싱
$parsed = json_decode($text, true);
if (json_last_error() !== JSON_ERROR_NONE) {
@@ -378,6 +383,46 @@ private function callGeminiApi(array $inputData): array
}
}
/**
* 토큰 사용량 저장
*/
private function saveTokenUsage(array $apiResult, string $model, string $menuName): void
{
try {
$usage = $apiResult['usageMetadata'] ?? null;
if (! $usage) {
return;
}
$promptTokens = $usage['promptTokenCount'] ?? 0;
$completionTokens = $usage['candidatesTokenCount'] ?? 0;
$totalTokens = $usage['totalTokenCount'] ?? 0;
// Gemini 2.0 Flash 기준 단가 (USD per token)
$inputPricePerToken = 0.10 / 1_000_000; // $0.10 / 1M tokens
$outputPricePerToken = 0.40 / 1_000_000; // $0.40 / 1M tokens
$costUsd = ($promptTokens * $inputPricePerToken) + ($completionTokens * $outputPricePerToken);
$exchangeRate = (float) config('services.gemini.exchange_rate', 1400);
$costKrw = $costUsd * $exchangeRate;
AiTokenUsage::create([
'tenant_id' => $this->tenantId(),
'model' => $model,
'menu_name' => $menuName,
'prompt_tokens' => $promptTokens,
'completion_tokens' => $completionTokens,
'total_tokens' => $totalTokens,
'cost_usd' => $costUsd,
'cost_krw' => $costKrw,
'request_id' => Str::uuid()->toString(),
'created_by' => $this->apiUserId(),
]);
} catch (\Exception $e) {
Log::warning('AI token usage save failed', ['error' => $e->getMessage()]);
}
}
/**
* AI 프롬프트 생성
*/