$e->getMessage()]); } } /** * Claude API 응답에서 토큰 사용량 저장 */ public static function saveClaudeUsage(array $apiResult, string $model, string $menuName): void { try { $usage = $apiResult['usage'] ?? null; if (! $usage) { return; } $promptTokens = $usage['input_tokens'] ?? 0; $completionTokens = $usage['output_tokens'] ?? 0; $totalTokens = $promptTokens + $completionTokens; // Claude 3 Haiku 기준 단가 $inputPrice = 0.25 / 1_000_000; $outputPrice = 1.25 / 1_000_000; self::save($model, $menuName, $promptTokens, $completionTokens, $totalTokens, $inputPrice, $outputPrice); } catch (\Exception $e) { Log::warning('AI token usage save failed (Claude)', ['error' => $e->getMessage()]); } } /** * Google Cloud Storage 업로드 사용량 저장 * GCS Class A 오퍼레이션: $0.005 / 1,000건, Storage: $0.02 / GB / month */ public static function saveGcsStorageUsage(string $menuName, int $fileSizeBytes): void { try { $fileSizeMB = $fileSizeBytes / (1024 * 1024); // 업로드 API 호출 비용 ($0.005/1000 operations) + 월 스토리지 비용 ($0.02/GB, 7일 기준) $operationCost = 0.005 / 1000; $storageCost = ($fileSizeMB / 1024) * 0.02 * (7 / 30); // 7일 보관 기준 $costUsd = $operationCost + $storageCost; self::save('google-cloud-storage', $menuName, $fileSizeBytes, 0, $fileSizeBytes, $costUsd / max($fileSizeBytes, 1), 0); } catch (\Exception $e) { Log::warning('AI token usage save failed (GCS)', ['error' => $e->getMessage()]); } } /** * Google Speech-to-Text 사용량 저장 * STT latest_long 모델: $0.009 / 15초 */ public static function saveSttUsage(string $menuName, int $durationSeconds): void { try { // latest_long 모델: $0.009 per 15 seconds = $0.0006 per second $costUsd = ceil($durationSeconds / 15) * 0.009; self::save('google-speech-to-text', $menuName, $durationSeconds, 0, $durationSeconds, $costUsd / max($durationSeconds, 1), 0); } catch (\Exception $e) { Log::warning('AI token usage save failed (STT)', ['error' => $e->getMessage()]); } } /** * 공통 저장 로직 */ private static function save( string $model, string $menuName, int $promptTokens, int $completionTokens, int $totalTokens, float $inputPricePerToken, float $outputPricePerToken, ): void { $costUsd = ($promptTokens * $inputPricePerToken) + ($completionTokens * $outputPricePerToken); $exchangeRate = (float) config('services.gemini.exchange_rate', 1400); $costKrw = $costUsd * $exchangeRate; $tenantId = session('selected_tenant_id', 1); AiTokenUsage::create([ 'tenant_id' => $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' => auth()->id(), ]); } }