Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 Style: RFC-113 Provider Model Usage Statistics (#8453)

Rylan Cai0851028205ec
diff --git a/locales/ar/auth.json b/locales/ar/auth.json
index 6a3b1984848..453ef3b1a31 100644
--- a/locales/ar/auth.json
+++ b/locales/ar/auth.json
@@ -145,6 +145,50 @@
"apikey": "إدارة مفاتيح API",
"profile": "الملف الشخصي",
"security": "الأمان",
- "stats": "الإحصائيات"
+ "stats": "الإحصائيات",
+ "usage": "إحصاءات الاستخدام"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "قائمة النماذج",
+ "models": "النماذج النشطة",
+ "providerTable": "قائمة المزودين",
+ "providers": "المزودون النشطون",
+ "table": {
+ "calls": "عدد الاستدعاءات",
+ "model": "النموذج",
+ "provider": "المزود",
+ "spend": "التكلفة"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "استدعاءات النموذج",
+ "title": "إنفاق هذا الشهر"
+ },
+ "today": {
+ "title": "إنفاق اليوم",
+ "yesterday": "أمس"
+ }
+ },
+ "table": {
+ "actions": "إجراءات",
+ "createdAt": "وقت الاستخدام",
+ "inputTokens": "رموز الإدخال",
+ "model": "النموذج",
+ "outputTokens": "رموز الإخراج",
+ "spend": "التكلفة",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "نوع الاستدعاء"
+ },
+ "trends": {
+ "spend": "المبلغ",
+ "tokens": "الرموز"
+ },
+ "welcome": {
+ "model": "النموذج",
+ "provider": "المزود"
+ }
}
}
diff --git a/locales/bg-BG/auth.json b/locales/bg-BG/auth.json
index 33f0f8d5888..493962d6386 100644
--- a/locales/bg-BG/auth.json
+++ b/locales/bg-BG/auth.json
@@ -145,6 +145,50 @@
"apikey": "Управление на API ключове",
"profile": "Профил",
"security": "Сигурност",
- "stats": "Статистика"
+ "stats": "Статистика",
+ "usage": "Статистика за използване"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "Списък с модели",
+ "models": "Активни модели",
+ "providerTable": "Списък с доставчици",
+ "providers": "Активни доставчици",
+ "table": {
+ "calls": "Брой извиквания",
+ "model": "Модел",
+ "provider": "Доставчик",
+ "spend": "Разходи"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "Извиквания на модела",
+ "title": "Разходи за този месец"
+ },
+ "today": {
+ "title": "Разходи за днес",
+ "yesterday": "Вчера"
+ }
+ },
+ "table": {
+ "actions": "Действия",
+ "createdAt": "Време на използване",
+ "inputTokens": "Входни токени",
+ "model": "Модел",
+ "outputTokens": "Изходни токени",
+ "spend": "Разходи",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "Тип извикване"
+ },
+ "trends": {
+ "spend": "Сума",
+ "tokens": "Токени"
+ },
+ "welcome": {
+ "model": "Модел",
+ "provider": "Доставчик"
+ }
}
}
diff --git a/locales/de-DE/auth.json b/locales/de-DE/auth.json
index e8643c0404d..606e953a7c9 100644
--- a/locales/de-DE/auth.json
+++ b/locales/de-DE/auth.json
@@ -145,6 +145,50 @@
"apikey": "API-Schlüssel Verwaltung",
"profile": "Profil",
"security": "Sicherheit",
- "stats": "Statistiken"
+ "stats": "Statistiken",
+ "usage": "Nutzungsstatistik"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "Modellliste",
+ "models": "Aktive Modelle",
+ "providerTable": "Anbieterliste",
+ "providers": "Aktive Anbieter",
+ "table": {
+ "calls": "Anzahl der Aufrufe",
+ "model": "Modell",
+ "provider": "Anbieter",
+ "spend": "Kosten"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "Modellaufrufe",
+ "title": "Ausgaben dieses Monats"
+ },
+ "today": {
+ "title": "Heutige Ausgaben",
+ "yesterday": "Gestern"
+ }
+ },
+ "table": {
+ "actions": "Aktionen",
+ "createdAt": "Nutzungszeit",
+ "inputTokens": "Eingabe-Token",
+ "model": "Modell",
+ "outputTokens": "Ausgabe-Token",
+ "spend": "Kosten",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "Aufruftyp"
+ },
+ "trends": {
+ "spend": "Betrag",
+ "tokens": "Token"
+ },
+ "welcome": {
+ "model": "Modell",
+ "provider": "Anbieter"
+ }
}
}
diff --git a/locales/en-US/auth.json b/locales/en-US/auth.json
index 53ce155dbc7..c464d8c4a2d 100644
--- a/locales/en-US/auth.json
+++ b/locales/en-US/auth.json
@@ -145,6 +145,50 @@
"apikey": "API Key Management",
"profile": "Profile",
"security": "Security",
- "stats": "Statistics"
+ "stats": "Statistics",
+ "usage": "Usage Statistics"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "Model List",
+ "models": "Active Models",
+ "providerTable": "Provider List",
+ "providers": "Active Providers",
+ "table": {
+ "calls": "Calls",
+ "model": "Model",
+ "provider": "Provider",
+ "spend": "Spend"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "Model Calls",
+ "title": "This Month's Spend"
+ },
+ "today": {
+ "title": "Today's Spend",
+ "yesterday": "Yesterday"
+ }
+ },
+ "table": {
+ "actions": "Actions",
+ "createdAt": "Usage Time",
+ "inputTokens": "Input Tokens",
+ "model": "Model",
+ "outputTokens": "Output Tokens",
+ "spend": "Spend",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "Call Type"
+ },
+ "trends": {
+ "spend": "Amount",
+ "tokens": "Tokens"
+ },
+ "welcome": {
+ "model": "Model",
+ "provider": "Provider"
+ }
}
}
diff --git a/locales/es-ES/auth.json b/locales/es-ES/auth.json
index 0d77e1de9cc..d469482d1f7 100644
--- a/locales/es-ES/auth.json
+++ b/locales/es-ES/auth.json
@@ -145,6 +145,50 @@
"apikey": "Gestión de Claves API",
"profile": "Perfil",
"security": "Seguridad",
- "stats": "Estadísticas"
+ "stats": "Estadísticas",
+ "usage": "Estadísticas de uso"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "Lista de modelos",
+ "models": "Modelos activos",
+ "providerTable": "Lista de proveedores",
+ "providers": "Proveedores activos",
+ "table": {
+ "calls": "Número de llamadas",
+ "model": "Modelo",
+ "provider": "Proveedor",
+ "spend": "Gasto"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "Llamadas del modelo",
+ "title": "Gastos de este mes"
+ },
+ "today": {
+ "title": "Gasto de hoy",
+ "yesterday": "Ayer"
+ }
+ },
+ "table": {
+ "actions": "Acciones",
+ "createdAt": "Fecha de uso",
+ "inputTokens": "Tokens de entrada",
+ "model": "Modelo",
+ "outputTokens": "Tokens de salida",
+ "spend": "Gasto",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "Tipo de llamada"
+ },
+ "trends": {
+ "spend": "Importe",
+ "tokens": "Tokens"
+ },
+ "welcome": {
+ "model": "Modelo",
+ "provider": "Proveedor"
+ }
}
}
diff --git a/locales/fa-IR/auth.json b/locales/fa-IR/auth.json
index 05e72706b0a..dafe1e1f729 100644
--- a/locales/fa-IR/auth.json
+++ b/locales/fa-IR/auth.json
@@ -145,6 +145,50 @@
"apikey": "مدیریت کلید API",
"profile": "پروفایل",
"security": "امنیت",
- "stats": "آمار"
+ "stats": "آمار",
+ "usage": "آمار مصرف"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "فهرست مدل‌ها",
+ "models": "مدل‌های فعال",
+ "providerTable": "فهرست ارائه‌دهندگان",
+ "providers": "ارائه‌دهندگان فعال",
+ "table": {
+ "calls": "تعداد فراخوانی‌ها",
+ "model": "مدل",
+ "provider": "ارائه‌دهنده",
+ "spend": "هزینه"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "فراخوانی‌های مدل",
+ "title": "هزینه ماه جاری"
+ },
+ "today": {
+ "title": "هزینه امروز",
+ "yesterday": "دیروز"
+ }
+ },
+ "table": {
+ "actions": "عملیات",
+ "createdAt": "زمان استفاده",
+ "inputTokens": "توکن‌های ورودی",
+ "model": "مدل",
+ "outputTokens": "توکن‌های خروجی",
+ "spend": "هزینه",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "نوع فراخوانی"
+ },
+ "trends": {
+ "spend": "مبلغ",
+ "tokens": "توکن‌ها"
+ },
+ "welcome": {
+ "model": "مدل",
+ "provider": "ارائه‌دهنده"
+ }
}
}
diff --git a/locales/fr-FR/auth.json b/locales/fr-FR/auth.json
index 03c5c7da20f..b2c2ebaf7b3 100644
--- a/locales/fr-FR/auth.json
+++ b/locales/fr-FR/auth.json
@@ -145,6 +145,50 @@
"apikey": "Gestion des clés API",
"profile": "Profil",
"security": "Sécurité",
- "stats": "Statistiques"
+ "stats": "Statistiques",
+ "usage": "Statistiques d'utilisation"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "Liste des modèles",
+ "models": "Modèles actifs",
+ "providerTable": "Liste des fournisseurs",
+ "providers": "Fournisseurs actifs",
+ "table": {
+ "calls": "Nombre d'appels",
+ "model": "Modèle",
+ "provider": "Fournisseur",
+ "spend": "Dépenses"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "Appels par modèle",
+ "title": "Dépenses du mois"
+ },
+ "today": {
+ "title": "Dépenses d'aujourd'hui",
+ "yesterday": "Hier"
+ }
+ },
+ "table": {
+ "actions": "Actions",
+ "createdAt": "Date d'utilisation",
+ "inputTokens": "Tokens d'entrée",
+ "model": "Modèle",
+ "outputTokens": "Tokens de sortie",
+ "spend": "Dépenses",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "Type d'appel"
+ },
+ "trends": {
+ "spend": "Montant",
+ "tokens": "Tokens"
+ },
+ "welcome": {
+ "model": "Modèle",
+ "provider": "Fournisseur"
+ }
}
}
diff --git a/locales/it-IT/auth.json b/locales/it-IT/auth.json
index abafb0badbd..984bb8b7cf4 100644
--- a/locales/it-IT/auth.json
+++ b/locales/it-IT/auth.json
@@ -145,6 +145,50 @@
"apikey": "Gestione Chiavi API",
"profile": "Profilo",
"security": "Sicurezza",
- "stats": "Statistiche"
+ "stats": "Statistiche",
+ "usage": "Statistiche di utilizzo"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "Elenco modelli",
+ "models": "Modelli attivi",
+ "providerTable": "Elenco fornitori",
+ "providers": "Fornitori attivi",
+ "table": {
+ "calls": "Numero di chiamate",
+ "model": "Modello",
+ "provider": "Fornitore",
+ "spend": "Spesa"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "Chiamate modello",
+ "title": "Spesa del mese"
+ },
+ "today": {
+ "title": "Spesa di oggi",
+ "yesterday": "Ieri"
+ }
+ },
+ "table": {
+ "actions": "Azioni",
+ "createdAt": "Data d'uso",
+ "inputTokens": "Token in ingresso",
+ "model": "Modello",
+ "outputTokens": "Token in uscita",
+ "spend": "Spesa",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "Tipo di chiamata"
+ },
+ "trends": {
+ "spend": "Importo",
+ "tokens": "Token"
+ },
+ "welcome": {
+ "model": "Modello",
+ "provider": "Fornitore"
+ }
}
}
diff --git a/locales/ja-JP/auth.json b/locales/ja-JP/auth.json
index 7dc6f494837..9698e195493 100644
--- a/locales/ja-JP/auth.json
+++ b/locales/ja-JP/auth.json
@@ -145,6 +145,50 @@
"apikey": "APIキー管理",
"profile": "プロフィール",
"security": "セキュリティ",
- "stats": "統計"
+ "stats": "統計",
+ "usage": "使用量の統計"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "モデル一覧",
+ "models": "アクティブモデル",
+ "providerTable": "プロバイダー一覧",
+ "providers": "アクティブプロバイダー",
+ "table": {
+ "calls": "呼び出し回数",
+ "model": "モデル",
+ "provider": "プロバイダー",
+ "spend": "費用"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "モデル呼び出し回数",
+ "title": "今月の費用"
+ },
+ "today": {
+ "title": "今日の費用",
+ "yesterday": "昨日"
+ }
+ },
+ "table": {
+ "actions": "操作",
+ "createdAt": "使用時間",
+ "inputTokens": "入力トークン",
+ "model": "モデル",
+ "outputTokens": "出力トークン",
+ "spend": "費用",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "呼び出しタイプ"
+ },
+ "trends": {
+ "spend": "金額",
+ "tokens": "トークン"
+ },
+ "welcome": {
+ "model": "モデル",
+ "provider": "プロバイダー"
+ }
}
}
diff --git a/locales/ko-KR/auth.json b/locales/ko-KR/auth.json
index dedeb27b651..d633ed6fec1 100644
--- a/locales/ko-KR/auth.json
+++ b/locales/ko-KR/auth.json
@@ -145,6 +145,50 @@
"apikey": "API 키 관리",
"profile": "프로필",
"security": "보안",
- "stats": "통계"
+ "stats": "통계",
+ "usage": "사용량 통계"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "모델 목록",
+ "models": "활성 모델",
+ "providerTable": "제공업체 목록",
+ "providers": "활성 제공업체",
+ "table": {
+ "calls": "호출 횟수",
+ "model": "모델",
+ "provider": "제공업체",
+ "spend": "비용"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "모델 호출",
+ "title": "이번 달 비용"
+ },
+ "today": {
+ "title": "오늘 비용",
+ "yesterday": "어제"
+ }
+ },
+ "table": {
+ "actions": "작업",
+ "createdAt": "사용 시간",
+ "inputTokens": "입력 토큰",
+ "model": "모델",
+ "outputTokens": "출력 토큰",
+ "spend": "비용",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "호출 유형"
+ },
+ "trends": {
+ "spend": "금액",
+ "tokens": "토큰"
+ },
+ "welcome": {
+ "model": "모델",
+ "provider": "제공업체"
+ }
}
}
diff --git a/locales/nl-NL/auth.json b/locales/nl-NL/auth.json
index 91236ac3d7d..fbd031e4f45 100644
--- a/locales/nl-NL/auth.json
+++ b/locales/nl-NL/auth.json
@@ -145,6 +145,50 @@
"apikey": "API-sleutelbeheer",
"profile": "Profiel",
"security": "Beveiliging",
- "stats": "Statistieken"
+ "stats": "Statistieken",
+ "usage": "Gebruikstatistieken"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "Modellenlijst",
+ "models": "Actieve modellen",
+ "providerTable": "Aanbiederslijst",
+ "providers": "Actieve aanbieders",
+ "table": {
+ "calls": "Aantal oproepen",
+ "model": "Model",
+ "provider": "Aanbieder",
+ "spend": "Kosten"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "Modeloproepen",
+ "title": "Kosten deze maand"
+ },
+ "today": {
+ "title": "Kosten vandaag",
+ "yesterday": "Gisteren"
+ }
+ },
+ "table": {
+ "actions": "Acties",
+ "createdAt": "Gebruikstijd",
+ "inputTokens": "Invoertokens",
+ "model": "Model",
+ "outputTokens": "Uitvoertokens",
+ "spend": "Kosten",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "Oproeptype"
+ },
+ "trends": {
+ "spend": "Bedrag",
+ "tokens": "Tokens"
+ },
+ "welcome": {
+ "model": "Model",
+ "provider": "Aanbieder"
+ }
}
}
diff --git a/locales/pl-PL/auth.json b/locales/pl-PL/auth.json
index b25b6af3430..97989535894 100644
--- a/locales/pl-PL/auth.json
+++ b/locales/pl-PL/auth.json
@@ -145,6 +145,50 @@
"apikey": "Zarządzanie kluczami API",
"profile": "Profil",
"security": "Bezpieczeństwo",
- "stats": "Statystyki"
+ "stats": "Statystyki",
+ "usage": "Statystyki użycia"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "Lista modeli",
+ "models": "Aktywne modele",
+ "providerTable": "Lista dostawców",
+ "providers": "Aktywni dostawcy",
+ "table": {
+ "calls": "Liczba wywołań",
+ "model": "Model",
+ "provider": "Dostawca",
+ "spend": "Koszt"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "Wywołania modelu",
+ "title": "Wydatki w tym miesiącu"
+ },
+ "today": {
+ "title": "Wydatki dzisiaj",
+ "yesterday": "Wczoraj"
+ }
+ },
+ "table": {
+ "actions": "Akcje",
+ "createdAt": "Czas użycia",
+ "inputTokens": "Tokeny wejściowe",
+ "model": "Model",
+ "outputTokens": "Tokeny wyjściowe",
+ "spend": "Koszt",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "Typ wywołania"
+ },
+ "trends": {
+ "spend": "Kwota",
+ "tokens": "Tokeny"
+ },
+ "welcome": {
+ "model": "Model",
+ "provider": "Dostawca"
+ }
}
}
diff --git a/locales/pt-BR/auth.json b/locales/pt-BR/auth.json
index 6c4ab41c584..81cd5820a20 100644
--- a/locales/pt-BR/auth.json
+++ b/locales/pt-BR/auth.json
@@ -145,6 +145,50 @@
"apikey": "Gerenciamento de Chave API",
"profile": "Perfil",
"security": "Segurança",
- "stats": "Estatísticas"
+ "stats": "Estatísticas",
+ "usage": "Estatísticas de uso"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "Lista de modelos",
+ "models": "Modelos ativos",
+ "providerTable": "Lista de provedores",
+ "providers": "Provedores ativos",
+ "table": {
+ "calls": "Número de chamadas",
+ "model": "Modelo",
+ "provider": "Provedor",
+ "spend": "Gasto"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "Chamadas do modelo",
+ "title": "Gastos deste mês"
+ },
+ "today": {
+ "title": "Gastos de hoje",
+ "yesterday": "Ontem"
+ }
+ },
+ "table": {
+ "actions": "Ações",
+ "createdAt": "Data de uso",
+ "inputTokens": "Tokens de entrada",
+ "model": "Modelo",
+ "outputTokens": "Tokens de saída",
+ "spend": "Gasto",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "Tipo de chamada"
+ },
+ "trends": {
+ "spend": "Valor",
+ "tokens": "Tokens"
+ },
+ "welcome": {
+ "model": "Modelo",
+ "provider": "Provedor"
+ }
}
}
diff --git a/locales/ru-RU/auth.json b/locales/ru-RU/auth.json
index 5445e16ce42..a082abdaa4c 100644
--- a/locales/ru-RU/auth.json
+++ b/locales/ru-RU/auth.json
@@ -145,6 +145,50 @@
"apikey": "Управление API ключами",
"profile": "Профиль",
"security": "Безопасность",
- "stats": "Статистика"
+ "stats": "Статистика",
+ "usage": "Статистика использования"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "Список моделей",
+ "models": "Активные модели",
+ "providerTable": "Список поставщиков",
+ "providers": "Активные поставщики",
+ "table": {
+ "calls": "Количество вызовов",
+ "model": "Модель",
+ "provider": "Поставщик",
+ "spend": "Расходы"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "Вызовы модели",
+ "title": "Расходы за месяц"
+ },
+ "today": {
+ "title": "Сегодняшние расходы",
+ "yesterday": "Вчера"
+ }
+ },
+ "table": {
+ "actions": "Действия",
+ "createdAt": "Время использования",
+ "inputTokens": "Входные токены",
+ "model": "Модель",
+ "outputTokens": "Выходные токены",
+ "spend": "Расходы",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "Тип вызова"
+ },
+ "trends": {
+ "spend": "Сумма",
+ "tokens": "Токены"
+ },
+ "welcome": {
+ "model": "Модель",
+ "provider": "Поставщик"
+ }
}
}
diff --git a/locales/tr-TR/auth.json b/locales/tr-TR/auth.json
index 44866bc849c..f047f493bc8 100644
--- a/locales/tr-TR/auth.json
+++ b/locales/tr-TR/auth.json
@@ -145,6 +145,50 @@
"apikey": "API Anahtarı Yönetimi",
"profile": "Profil",
"security": "Güvenlik",
- "stats": "İstatistikler"
+ "stats": "İstatistikler",
+ "usage": "Kullanım İstatistikleri"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "Model listesi",
+ "models": "Aktif modeller",
+ "providerTable": "Sağlayıcı listesi",
+ "providers": "Aktif sağlayıcılar",
+ "table": {
+ "calls": "Çağrı sayısı",
+ "model": "Model",
+ "provider": "Sağlayıcı",
+ "spend": "Harcamalar"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "Model çağrıları",
+ "title": "Bu ayki harcama"
+ },
+ "today": {
+ "title": "Bugünkü harcama",
+ "yesterday": "Dün"
+ }
+ },
+ "table": {
+ "actions": "İşlemler",
+ "createdAt": "Kullanım zamanı",
+ "inputTokens": "Girdi Tokenleri",
+ "model": "Model",
+ "outputTokens": "Çıktı Tokenleri",
+ "spend": "Harcamalar",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "Çağrı türü"
+ },
+ "trends": {
+ "spend": "Tutar",
+ "tokens": "Tokenler"
+ },
+ "welcome": {
+ "model": "Model",
+ "provider": "Sağlayıcı"
+ }
}
}
diff --git a/locales/vi-VN/auth.json b/locales/vi-VN/auth.json
index 4f62e55b68b..7c4b1d494b8 100644
--- a/locales/vi-VN/auth.json
+++ b/locales/vi-VN/auth.json
@@ -145,6 +145,50 @@
"apikey": "Quản lý API Key",
"profile": "Hồ sơ",
"security": "Bảo mật",
- "stats": "Thống kê"
+ "stats": "Thống kê",
+ "usage": "Thống kê sử dụng"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "Danh sách mô hình",
+ "models": "Mô hình hoạt động",
+ "providerTable": "Danh sách nhà cung cấp",
+ "providers": "Nhà cung cấp hoạt động",
+ "table": {
+ "calls": "Số lần gọi",
+ "model": "Mô hình",
+ "provider": "Nhà cung cấp",
+ "spend": "Chi phí"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "Lượt gọi mô hình",
+ "title": "Chi phí tháng này"
+ },
+ "today": {
+ "title": "Chi phí hôm nay",
+ "yesterday": "Hôm qua"
+ }
+ },
+ "table": {
+ "actions": "Hành động",
+ "createdAt": "Thời gian sử dụng",
+ "inputTokens": "Token đầu vào",
+ "model": "Mô hình",
+ "outputTokens": "Token đầu ra",
+ "spend": "Chi phí",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "Loại gọi"
+ },
+ "trends": {
+ "spend": "Số tiền",
+ "tokens": "Token"
+ },
+ "welcome": {
+ "model": "Mô hình",
+ "provider": "Nhà cung cấp"
+ }
}
}
diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.json
index f8a561446e2..d9683f8b2a9 100644
--- a/locales/zh-CN/auth.json
+++ b/locales/zh-CN/auth.json
@@ -145,6 +145,50 @@
"apikey": "API Key 管理",
"profile": "个人资料",
"security": "安全",
- "stats": "数据统计"
+ "stats": "数据统计",
+ "usage": "用量统计"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "模型列表",
+ "models": "活跃模型",
+ "providerTable": "提供商列表",
+ "providers": "活跃提供商",
+ "table": {
+ "calls": "调用次数",
+ "model": "模型",
+ "provider": "提供商",
+ "spend": "花费"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "模型调用",
+ "title": "本月花费"
+ },
+ "today": {
+ "title": "今日花费",
+ "yesterday": "昨日"
+ }
+ },
+ "table": {
+ "actions": "操作",
+ "createdAt": "使用时间",
+ "inputTokens": "输入 Token",
+ "model": "模型",
+ "outputTokens": "输出 Token",
+ "spend": "花费",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "调用类型"
+ },
+ "trends": {
+ "spend": "金额",
+ "tokens": "Token"
+ },
+ "welcome": {
+ "model": "模型",
+ "provider": "提供商"
+ }
}
}
diff --git a/locales/zh-TW/auth.json b/locales/zh-TW/auth.json
index 61dd3813ca8..3fee68566e6 100644
--- a/locales/zh-TW/auth.json
+++ b/locales/zh-TW/auth.json
@@ -145,6 +145,50 @@
"apikey": "API Key 管理",
"profile": "個人資料",
"security": "安全",
- "stats": "數據統計"
+ "stats": "數據統計",
+ "usage": "用量統計"
+ },
+ "usage": {
+ "activeModels": {
+ "modelTable": "模型列表",
+ "models": "活躍模型",
+ "providerTable": "供應商列表",
+ "providers": "活躍供應商",
+ "table": {
+ "calls": "調用次數",
+ "model": "模型",
+ "provider": "供應商",
+ "spend": "花費"
+ }
+ },
+ "cards": {
+ "month": {
+ "modelCalls": "模型調用",
+ "title": "本月花費"
+ },
+ "today": {
+ "title": "今日花費",
+ "yesterday": "昨日"
+ }
+ },
+ "table": {
+ "actions": "操作",
+ "createdAt": "使用時間",
+ "inputTokens": "輸入 Token",
+ "model": "模型",
+ "outputTokens": "輸出 Token",
+ "spend": "花費",
+ "tps": "TPS",
+ "ttft": "TTFT",
+ "type": "調用類型"
+ },
+ "trends": {
+ "spend": "金額",
+ "tokens": "Token"
+ },
+ "welcome": {
+ "model": "模型",
+ "provider": "供應商"
+ }
}
}
diff --git a/packages/types/src/usage/usageRecord.ts b/packages/types/src/usage/usageRecord.ts
new file mode 100644
index 00000000000..96be6beedcb
--- /dev/null
+++ b/packages/types/src/usage/usageRecord.ts
@@ -0,0 +1,54 @@
+import { MessageMetadata } from '../message';
+
+export interface UsageRecordItem {
+ createdAt: Date;
+ /**
+ * ID
+ **/
+ id: string;
+ inputStartAt?: Date | null;
+ /**
+ * Meta information
+ **/
+ metadata?: MessageMetadata | null;
+ /**
+ * Model id
+ */
+ model: string;
+ outputFinishAt?: Date | null;
+ outputStartAt?: Date | null;
+ /**
+ * Provider id
+ */
+ provider: string;
+ /**
+ * Spend
+ **/
+ spend: number;
+ /**
+ * Usage details
+ **/
+ totalInputTokens?: number | null;
+ totalOutputTokens?: number | null;
+ totalTokens?: number | null;
+ /**
+ * Performance details
+ **/
+ tps?: number | null;
+ ttft?: number | null;
+ /**
+ * Call types
+ **/
+ type: string;
+ updatedAt: Date;
+ userId: string;
+}
+
+export type UsageLog = {
+ date: number;
+ day: string;
+ records: UsageRecordItem[];
+ totalRequests: number;
+ totalSpend: number;
+ totalTokens: number;
+};
diff --git a/src/app/[variants]/(main)/profile/hooks/useCategory.tsx b/src/app/[variants]/(main)/profile/hooks/useCategory.tsx
index 70f651919d3..801eddc1607 100644
--- a/src/app/[variants]/(main)/profile/hooks/useCategory.tsx
+++ b/src/app/[variants]/(main)/profile/hooks/useCategory.tsx
@@ -1,5 +1,5 @@
import { Icon } from '@lobehub/ui';
-import { ChartColumnBigIcon, KeyIcon, ShieldCheck, UserCircle } from 'lucide-react';
+import { BadgeCentIcon, ChartColumnBigIcon, KeyIcon, ShieldCheck, UserCircle } from 'lucide-react';
import Link from 'next/link';
import { useTranslation } from 'react-i18next';
@@ -54,6 +54,15 @@ export const useCategory = () => {
</Link>
),
},
+ {
+ icon: <Icon icon={BadgeCentIcon} />,
+ key: ProfileTabs.Usage,
+ label: (
+ <Link href={'/profile/usage'} onClick={(e) => e.preventDefault()}>
+ {t('tab.usage')}
+ </Link>
+ ),
+ },
].filter(Boolean) as MenuProps['items'];
return cateItems;
diff --git a/src/app/[variants]/(main)/profile/usage/Client.tsx b/src/app/[variants]/(main)/profile/usage/Client.tsx
new file mode 100644
index 00000000000..02c32a8d04a
--- /dev/null
+++ b/src/app/[variants]/(main)/profile/usage/Client.tsx
@@ -0,0 +1,114 @@
+'use client';
+
+import { Icon, Segmented } from '@lobehub/ui';
+import { Col, DatePicker, DatePickerProps, Row } from 'antd';
+import dayjs from 'dayjs';
+import { Brain, Codesandbox } from 'lucide-react';
+import { memo, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { usageService } from '@/services/usage';
+import { UsageLog } from '@/types/usage/usageRecord';
+
+import Welcome from '../stats/features/Welcome';
+import UsageCards from './features/UsageCards';
+import UsageTable from './features/UsageTable';
+import UsageTrends from './features/UsageTrends';
+
+export interface UsageChartProps {
+ data?: UsageLog[];
+ dateStrings?: string;
+ groupBy?: GroupBy;
+ inShare?: boolean;
+ isLoading?: boolean;
+ mobile?: boolean;
+}
+
+export enum GroupBy {
+ Model = 'model',
+ Provider = 'provider',
+}
+
+const Client = memo<{ mobile?: boolean }>(({ mobile }) => {
+ const { t, i18n } = useTranslation('auth');
+ dayjs.locale(i18n.language);
+
+ const [groupBy, setGroupBy] = useState<GroupBy>(GroupBy.Model);
+ const [dateRange, setDateRange] = useState<dayjs.Dayjs>(dayjs(new Date()));
+ const [dateStrings, setDateStrings] = useState<string>();
+
+ const { data, isLoading, mutate } = useClientDataSWR('usage-stat', async () =>
+ usageService.findAndGroupByDay(dateStrings),
+ );
+
+ useEffect(() => {
+ if (dateStrings) {
+ mutate();
+ }
+ }, [dateStrings]);
+
+ const handleDateChange: DatePickerProps['onChange'] = (dates, dateStrings) => {
+ setDateRange(dates);
+ if (typeof dateStrings === 'string') {
+ setDateStrings(dateStrings);
+ }
+ };
+
+ return (
+ <Flexbox gap={mobile ? 0 : 24}>
+ <Flexbox>
+ <Row>
+ <Col span={16}>
+ {mobile ? (
+ <Welcome mobile />
+ ) : (
+ <Flexbox align={'flex-start'} gap={16} horizontal justify={'space-between'}>
+ <Welcome />
+ </Flexbox>
+ )}
+ </Col>
+ <Col span={8}>
+ <Flexbox gap={16} horizontal>
+ <Segmented
+ onChange={(v) => setGroupBy(v as GroupBy)}
+ options={[
+ {
+ icon: <Icon icon={Codesandbox} />,
+ label: t('usage.welcome.model'),
+ value: GroupBy.Model,
+ },
+ {
+ icon: <Icon icon={Brain} />,
+ label: t('usage.welcome.provider'),
+ value: GroupBy.Provider,
+ },
+ ]}
+ value={groupBy}
+ />
+ <DatePicker onChange={handleDateChange} picker="month" value={dateRange} />
+ </Flexbox>
+ </Col>
+ </Row>
+ </Flexbox>
+ <Flexbox>
+ <UsageCards data={data} groupBy={groupBy} isLoading={isLoading} />
+ </Flexbox>
+ <Flexbox>
+ <Row gutter={[16, 16]}>
+ <Col span={24}>
+ <UsageTrends data={data} groupBy={groupBy} isLoading={isLoading} />
+ </Col>
+ </Row>
+ </Flexbox>
+ <Row>
+ <Col span={24}>
+ <UsageTable dateStrings={dateStrings} />
+ </Col>
+ </Row>
+ </Flexbox>
+ );
+});
+
+export default Client;
diff --git a/src/app/[variants]/(main)/profile/usage/features/UsageCards/ActiveModels/ModelTable.tsx b/src/app/[variants]/(main)/profile/usage/features/UsageCards/ActiveModels/ModelTable.tsx
new file mode 100644
index 00000000000..5f94f9d54a1
--- /dev/null
+++ b/src/app/[variants]/(main)/profile/usage/features/UsageCards/ActiveModels/ModelTable.tsx
@@ -0,0 +1,175 @@
+import { CategoryBar, useThemeColorRange } from '@lobehub/charts';
+import { ModelIcon, ProviderIcon } from '@lobehub/icons';
+import { Collapse, Tag } from '@lobehub/ui';
+import { Skeleton } from 'antd';
+import { useTheme } from 'antd-style';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import InlineTable from '@/components/InlineTable';
+import { UsageLog } from '@/types/usage/usageRecord';
+import { formatPrice } from '@/utils/format';
+
+import { GroupBy, UsageChartProps } from '../../../Client';
+
+interface WeightGroup {
+ id: string;
+ spend: number | string;
+ weight: number;
+}
+
+const formatData = (
+ data: UsageLog[],
+ groupBy: GroupBy,
+): {
+ childrens: WeightGroup[];
+ id: string;
+ totalSpend: number;
+}[] => {
+ if (!data || data?.length === 0) return [];
+
+ const requestLogs = data.flatMap((log) => log.records);
+ const groupedLogs = requestLogs.reduce((acc, log) => {
+ const key = groupBy === GroupBy.Model ? log.model : log.provider;
+ if (!acc.has(key)) {
+ acc.set(key, []);
+ }
+ acc.get(key)?.push(log);
+ return acc;
+ }, new Map<string, UsageLog['records']>());
+
+ return Array.from(groupedLogs.entries())
+ .map(([key, logs]) => {
+ // 此处的 logs 为多日的 log,需要进行 sum
+ // 如果当前的 groupBy 是 Model,则 logs 应该按照 Provider 进行分组
+ const spend = logs.reduce((acc, log) => {
+ const key = groupBy === GroupBy.Model ? log.provider : log.model;
+ acc.set(key, (acc.get(key) || 0) + log.spend);
+ return acc;
+ }, new Map<string, number>());
+
+ const totalSpend = logs.reduce((total, log) => total + (log.spend || 0), 0);
+
+ const spendWithWeight = Array.from(
+ spend.entries().map(([key, value]) => {
+ return {
+ id: key,
+ spend: value,
+ weight: totalSpend > 0 ? value / totalSpend : 0,
+ };
+ }),
+ );
+
+ return {
+ childrens: spendWithWeight.sort((a, b) => b.weight - a.weight),
+ id: key,
+ totalSpend: totalSpend,
+ };
+ })
+ .sort((a, b) => b.totalSpend - a.totalSpend);
+};
+
+const ModelTable = memo<UsageChartProps>(({ data, isLoading, groupBy }) => {
+ const { t } = useTranslation('auth');
+ const theme = useTheme();
+ const themeColorRange = useThemeColorRange();
+
+ const formattedData = useMemo(
+ () => formatData(data || [], groupBy || GroupBy.Model),
+ [data, groupBy],
+ );
+
+ console.log('ModelTable', groupBy, formattedData);
+
+ return isLoading ? (
+ <Skeleton active paragraph={{ rows: 8 }} title={false} />
+ ) : (
+ <Collapse
+ defaultActiveKey={formattedData.map((item) => item.id)}
+ expandIconPosition={'end'}
+ gap={16}
+ items={formattedData.map((item) => {
+ const key = item.id;
+ return {
+ children: (
+ <Flexbox>
+ <CategoryBar
+ colors={themeColorRange}
+ showLabels={false}
+ size={2}
+ values={item.childrens.map((item) => item.weight)}
+ />
+ <InlineTable
+ columns={[
+ {
+ dataIndex: 'id',
+ key: 'id',
+ render: (value, record, index) => {
+ return (
+ <Flexbox align={'center'} gap={12} horizontal key={value}>
+ {groupBy === GroupBy.Provider ? (
+ <ProviderIcon
+ provider={record.id}
+ style={{
+ boxShadow: `0 0 0 2px ${theme.colorBgContainer}, 0 0 0 4px ${themeColorRange[index]}`,
+ boxSizing: 'content-box',
+ }}
+ />
+ ) : (
+ <ModelIcon
+ model={record.id}
+ style={{
+ boxShadow: `0 0 0 2px ${theme.colorBgContainer}, 0 0 0 4px ${themeColorRange[index]}`,
+ boxSizing: 'content-box',
+ }}
+ />
+ )}
+ {value}
+ </Flexbox>
+ );
+ },
+ title:
+ groupBy === GroupBy.Model
+ ? t('usage.activeModels.table.provider')
+ : t('usage.activeModels.table.model'),
+ width: 200,
+ },
+ {
+ dataIndex: 'spend',
+ key: 'spend',
+ render: (value) => {
+ return `$${formatPrice(value)}`;
+ },
+ title: t('usage.activeModels.table.spend'),
+ },
+ ]}
+ dataSource={item.childrens}
+ hoverToActive={false}
+ loading={isLoading}
+ rowKey={(record) => record.id}
+ />
+ </Flexbox>
+ ),
+ extra: <Tag>{item?.childrens?.length ?? 0}</Tag>,
+ key,
+ label: (
+ <Flexbox align={'center'} gap={8} horizontal>
+ {groupBy === GroupBy.Model ? (
+ <ModelIcon model={key} size={24} />
+ ) : (
+ <ProviderIcon provider={key} size={24} />
+ )}
+ {key}
+ </Flexbox>
+ ),
+ };
+ })}
+ padding={{
+ body: 0,
+ }}
+ />
+ );
+});
+
+export default ModelTable;
diff --git a/src/app/[variants]/(main)/profile/usage/features/UsageCards/ActiveModels/index.tsx b/src/app/[variants]/(main)/profile/usage/features/UsageCards/ActiveModels/index.tsx
new file mode 100644
index 00000000000..3c3ea62ed70
--- /dev/null
+++ b/src/app/[variants]/(main)/profile/usage/features/UsageCards/ActiveModels/index.tsx
@@ -0,0 +1,126 @@
+import { ModelIcon, ProviderIcon } from '@lobehub/icons';
+import { ActionIcon, Modal } from '@lobehub/ui';
+import { useTheme } from 'antd-style';
+import { MaximizeIcon } from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import StatisticCard from '@/components/StatisticCard';
+import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';
+import { UsageLog } from '@/types/usage/usageRecord';
+import { formatNumber } from '@/utils/format';
+
+import { GroupBy, UsageChartProps } from '../../../Client';
+import ModelTable from './ModelTable';
+
+const computeList = (data: UsageLog[], groupBy: GroupBy): string[] => {
+ if (!data || data?.length === 0) return [];
+
+ return Array.from(
+ data.reduce((acc, log) => {
+ if (log.records) {
+ for (const item of log.records) {
+ if (groupBy === GroupBy.Model && item.model?.length !== 0) {
+ acc.add(item.model);
+ }
+ if (groupBy === GroupBy.Provider && item.provider?.length !== 0) {
+ acc.add(item.provider);
+ }
+ }
+ }
+ return acc;
+ }, new Set<string>()),
+ );
+};
+
+const ActiveModels = memo<UsageChartProps>(({ data, isLoading, groupBy }) => {
+ const { t } = useTranslation('auth');
+ const theme = useTheme();
+
+ const [open, setOpen] = useState(false);
+
+ const iconList = useMemo(
+ () => computeList(data || [], groupBy || GroupBy.Model),
+ [data, groupBy],
+ );
+
+ return (
+ <>
+ <StatisticCard
+ extra={
+ <ActionIcon
+ icon={MaximizeIcon}
+ onClick={() => setOpen(true)}
+ title={
+ groupBy === GroupBy.Model
+ ? t('usage.activeModels.modelTable')
+ : t('usage.activeModels.providerTable')
+ }
+ />
+ }
+ key={groupBy}
+ loading={isLoading}
+ statistic={{
+ description: (
+ <Flexbox horizontal wrap={'wrap'}>
+ {iconList.map((item, i) => {
+ if (!item) return null;
+ return groupBy === GroupBy.Model ? (
+ <ModelIcon
+ key={item}
+ model={item}
+ size={18}
+ style={{
+ border: `2px solid ${theme.colorBgContainer}`,
+ boxSizing: 'content-box',
+ marginRight: -8,
+ zIndex: i + 1,
+ }}
+ />
+ ) : (
+ <ProviderIcon
+ key={item}
+ provider={item}
+ size={18}
+ style={{
+ border: `2px solid ${theme.colorBgContainer}`,
+ boxSizing: 'content-box',
+ marginRight: -8,
+ zIndex: i + 1,
+ }}
+ />
+ );
+ })}
+ </Flexbox>
+ ),
+ precision: 0,
+ value: formatNumber(iconList?.length ?? 0),
+ }}
+ title={
+ <TitleWithPercentage
+ title={
+ groupBy === GroupBy.Model
+ ? t('usage.activeModels.models')
+ : t('usage.activeModels.providers')
+ }
+ />
+ }
+ />
+ <Modal
+ footer={null}
+ onCancel={() => setOpen(false)}
+ open={open}
+ title={
+ groupBy === GroupBy.Model
+ ? t('usage.activeModels.modelTable')
+ : t('usage.activeModels.providerTable')
+ }
+ >
+ <ModelTable data={data} groupBy={groupBy} isLoading={isLoading} />
+ </Modal>
+ </>
+ );
+});
+
+export default ActiveModels;
diff --git a/src/app/[variants]/(main)/profile/usage/features/UsageCards/MonthSpend.tsx b/src/app/[variants]/(main)/profile/usage/features/UsageCards/MonthSpend.tsx
new file mode 100644
index 00000000000..9c0f1cefddc
--- /dev/null
+++ b/src/app/[variants]/(main)/profile/usage/features/UsageCards/MonthSpend.tsx
@@ -0,0 +1,53 @@
+'use client';
+
+import { useTheme } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import Statistic from '@/components/Statistic';
+import StatisticCard from '@/components/StatisticCard';
+import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';
+import { UsageLog } from '@/types/usage/usageRecord';
+import { formatNumber } from '@/utils/format';
+
+import { UsageChartProps } from '../../Client';
+
+const computeMonth = (
+ data: UsageLog[],
+): {
+ calls: number | string;
+ spend: number | string;
+} => {
+ if (!data || data?.length === 0) return { calls: 0, spend: 0 };
+
+ const spend = data.reduce((acc, log) => acc + (log.totalSpend || 0), 0);
+ const calls = data.reduce((acc, log) => acc + (log.records?.length ?? 0), 0);
+
+ return {
+ calls: formatNumber(calls),
+ spend: formatNumber(spend),
+ };
+};
+
+const MonthSpend = memo<UsageChartProps>(({ data, isLoading }) => {
+ const { t } = useTranslation('auth');
+ const theme = useTheme();
+
+ const { spend, calls } = computeMonth(data || []);
+
+ return (
+ <StatisticCard
+ highlight={theme.blue}
+ loading={isLoading}
+ statistic={{
+ description: <Statistic title={t('usage.cards.month.modelCalls')} value={calls} />,
+ precision: 2,
+ prefix: '$',
+ value: spend,
+ }}
+ title={<TitleWithPercentage title={t('usage.cards.month.title')} />}
+ />
+ );
+});
+
+export default MonthSpend;
diff --git a/src/app/[variants]/(main)/profile/usage/features/UsageCards/TodaySpend.tsx b/src/app/[variants]/(main)/profile/usage/features/UsageCards/TodaySpend.tsx
new file mode 100644
index 00000000000..88fbcee66e9
--- /dev/null
+++ b/src/app/[variants]/(main)/profile/usage/features/UsageCards/TodaySpend.tsx
@@ -0,0 +1,67 @@
+'use client';
+
+import { useTheme } from 'antd-style';
+import dayjs from 'dayjs';
+import utc from 'dayjs/plugin/utc';
+import isToday from 'dayjs/plugin/isToday';
+import isYesterday from 'dayjs/plugin/isYesterday';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import Statistic from '@/components/Statistic';
+import StatisticCard from '@/components/StatisticCard';
+import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';
+import { UsageLog } from '@/types/usage/usageRecord';
+import { formatNumber } from '@/utils/format';
+
+import { UsageChartProps } from '../../Client';
+
+dayjs.extend(utc);
+dayjs.extend(isToday);
+dayjs.extend(isYesterday);
+
+const computeSpend = (
+ data: UsageLog[],
+): {
+ today: number | string;
+ yesterday: number | string;
+} => {
+ if (!data || data?.length === 0) return { today: 0, yesterday: 0 };
+
+ const today = data.find((log) => dayjs.utc(log.day).isToday())?.totalSpend ?? 0;
+ const yesterday = data.find((log) => dayjs.utc(log.day).isYesterday())?.totalSpend ?? 0;
+
+ return {
+ today: formatNumber(today),
+ yesterday: formatNumber(yesterday),
+ };
+};
+
+const TodaySpend = memo<UsageChartProps>(({ data, isLoading }) => {
+ const { t } = useTranslation('auth');
+ const theme = useTheme();
+
+ const { today, yesterday } = computeSpend(data || []);
+
+ return (
+ <StatisticCard
+ highlight={theme.green}
+ loading={isLoading}
+ statistic={{
+ description: <Statistic title={t('usage.cards.today.yesterday')} value={yesterday} />,
+ precision: 2,
+ prefix: '$',
+ value: today,
+ }}
+ title={
+ <TitleWithPercentage
+ count={typeof today === 'number' ? today : 0}
+ prvCount={typeof yesterday === 'number' ? yesterday : 0}
+ title={t('usage.cards.today.title')}
+ />
+ }
+ />
+ );
+});
+
+export default TodaySpend;
diff --git a/src/app/[variants]/(main)/profile/usage/features/UsageCards/index.tsx b/src/app/[variants]/(main)/profile/usage/features/UsageCards/index.tsx
new file mode 100644
index 00000000000..d5c65784422
--- /dev/null
+++ b/src/app/[variants]/(main)/profile/usage/features/UsageCards/index.tsx
@@ -0,0 +1,19 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { UsageChartProps } from '../../Client';
+import ActiveModels from './ActiveModels';
+import MonthSpend from './MonthSpend';
+import TodaySpend from './TodaySpend';
+
+const UsageCards = memo<UsageChartProps>(({ isLoading, data, groupBy }) => {
+ return (
+ <Flexbox gap={16} horizontal>
+ <TodaySpend data={data} isLoading={isLoading} />
+ <MonthSpend data={data} isLoading={isLoading} />
+ <ActiveModels data={data} groupBy={groupBy} isLoading={isLoading} />
+ </Flexbox>
+ );
+});
+
+export default UsageCards;
diff --git a/src/app/[variants]/(main)/profile/usage/features/UsageTable.tsx b/src/app/[variants]/(main)/profile/usage/features/UsageTable.tsx
new file mode 100644
index 00000000000..a53ef586c96
--- /dev/null
+++ b/src/app/[variants]/(main)/profile/usage/features/UsageTable.tsx
@@ -0,0 +1,145 @@
+import { ProviderIcon } from '@lobehub/icons';
+import { Tag } from '@lobehub/ui';
+import { Table, TableColumnType, Typography } from 'antd';
+import { useTheme } from 'antd-style';
+import { parseAsInteger, useQueryState } from 'nuqs';
+import { memo, useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { usageService } from '@/services/usage';
+import { formatDate, formatNumber } from '@/utils/format';
+
+import { UsageChartProps } from '../Client';
+
+const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {
+ const theme = useTheme();
+ const { t } = useTranslation('auth');
+
+ const { data, isLoading, mutate } = useClientDataSWR('usage-logs', async () =>
+ usageService.findByMonth(dateStrings),
+ );
+
+ const [currentPage, setCurrentPage] = useQueryState(
+ 'current',
+ parseAsInteger.withDefault(1).withOptions({ clearOnDefault: true }),
+ );
+ const [pageSize, setPageSize] = useQueryState(
+ 'pageSize',
+ parseAsInteger.withDefault(5).withOptions({ clearOnDefault: true }),
+ );
+
+ useEffect(() => {
+ if (dateStrings) {
+ mutate();
+ }
+ }, [dateStrings]);
+
+ const columns: TableColumnType<any>[] = [
+ {
+ hidden: true,
+ key: 'id',
+ title: 'ID',
+ },
+ {
+ dataIndex: 'model',
+ key: 'model',
+ render: (value, record) => (
+ <Flexbox align={'start'} gap={16} horizontal>
+ <ProviderIcon
+ provider={record.provider}
+ size={18}
+ style={{
+ border: `2px solid ${theme.colorBgContainer}`,
+ boxSizing: 'content-box',
+ marginRight: -8,
+ }}
+ />
+ <Typography.Text>
+ {value?.length > 12 ? `${value.slice(0, 12)}...` : value}
+ </Typography.Text>
+ </Flexbox>
+ ),
+ title: t('usage.table.model'),
+ },
+ {
+ dataIndex: 'type',
+ filters: [
+ {
+ text: 'Chat',
+ value: 'chat',
+ },
+ ],
+ key: 'type',
+ onFilter: (value, record) => record.callType === value,
+ render: (value) => {
+ return <Tag>{value}</Tag>;
+ },
+ title: t('usage.table.type'),
+ },
+ {
+ dataIndex: 'totalInputTokens',
+ key: 'inputTokens',
+ title: t('usage.table.inputTokens'),
+ },
+ {
+ dataIndex: 'totalOutputTokens',
+ key: 'outputTokens',
+ title: t('usage.table.outputTokens'),
+ },
+ {
+ dataIndex: 'tps',
+ key: 'tps',
+ render: (value) => formatNumber(value, 2),
+ title: t('usage.table.tps'),
+ },
+ {
+ dataIndex: 'ttft',
+ key: 'ttft',
+ render: (value) => formatNumber(value / 1000, 2),
+ title: t('usage.table.ttft'),
+ },
+ {
+ dataIndex: 'spend',
+ key: 'spend',
+ render: (value) => {
+ return `$${formatNumber(value, 6)}`;
+ },
+ title: t('usage.table.spend'),
+ },
+ {
+ dataIndex: 'createdAt',
+ key: 'createdAt',
+ render: (value) => {
+ return formatDate(new Date(value));
+ },
+ sortDirections: ['descend'],
+ sorter: (a, b) => a.createdAt - b.createdAt,
+ title: t('usage.table.createdAt'),
+ },
+ ];
+
+ return (
+ <Table
+ columns={columns}
+ dataSource={data}
+ key="id"
+ loading={isLoading}
+ pagination={{
+ current: currentPage,
+ onChange: (page) => {
+ setCurrentPage(page);
+ },
+ onShowSizeChange: (current, size) => {
+ setCurrentPage(current);
+ setPageSize(size);
+ },
+ pageSize,
+ }}
+ size="small"
+ />
+ );
+});
+
+export default UsageTable;
diff --git a/src/app/[variants]/(main)/profile/usage/features/UsageTrends.tsx b/src/app/[variants]/(main)/profile/usage/features/UsageTrends.tsx
new file mode 100644
index 00000000000..9fb62fd5879
--- /dev/null
+++ b/src/app/[variants]/(main)/profile/usage/features/UsageTrends.tsx
@@ -0,0 +1,107 @@
+import { type BarChartProps } from '@lobehub/charts';
+import { Segmented } from '@lobehub/ui';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import StatisticCard from '@/components/StatisticCard';
+import { UsageLog } from '@/types/usage/usageRecord';
+import { formatNumber } from '@/utils/format';
+
+import { GroupBy, UsageChartProps } from '../Client';
+import { UsageBarChart } from './components/UsageBarChart';
+
+const groupByType = (
+ data: UsageLog[],
+ type: 'spend' | 'token',
+ groupBy: GroupBy,
+): { categories: string[]; data: BarChartProps['data'] } => {
+ if (!data || data?.length === 0) return { categories: [], data: [] };
+ let formattedData: BarChartProps['data'] = [];
+ let cate: Map<string, number> = data.reduce((acc, log) => {
+ if (log.records) {
+ for (const item of log.records) {
+ if (groupBy === GroupBy.Model && item.model) {
+ acc.set(item.model, 0);
+ } else if (groupBy === GroupBy.Provider && item.provider) {
+ acc.set(item.provider, 0);
+ }
+ }
+ }
+ return acc;
+ }, new Map<string, number>());
+ const categories: string[] = Array.from(cate.keys());
+ formattedData = data.map((log) => {
+ const totalObj = {
+ day: log.day,
+ total: type === 'spend' ? log.totalSpend : log.totalTokens,
+ };
+ let todayCate = new Map<string, number>(cate);
+ for (const item of log.records) {
+ const value = type === 'spend' ? item.spend || 0 : item.totalTokens || 0;
+ const key = groupBy === GroupBy.Model ? item.model : item.provider;
+ let displayValue = (todayCate.get(key) || 0) + value;
+ if (type === 'spend') {
+ const formattedNum = formatNumber((todayCate.get(key) || 0) + value, 2);
+ if (typeof formattedNum !== 'string') {
+ displayValue = formattedNum;
+ }
+ }
+ todayCate.set(key, displayValue);
+ }
+ return {
+ ...totalObj,
+ ...Object.fromEntries(todayCate.entries()),
+ };
+ });
+ return {
+ categories,
+ data: formattedData,
+ };
+};
+
+enum ShowType {
+ Spend = 'spend',
+ Token = 'token',
+}
+
+const UsageTrends = memo<UsageChartProps>(({ isLoading, data, groupBy }) => {
+ const { t } = useTranslation('auth');
+
+ const [type, setType] = useState<ShowType>(ShowType.Spend);
+
+ const { categories: spendCate, data: spendData } = groupByType(
+ data || [],
+ 'spend',
+ groupBy || GroupBy.Model,
+ );
+ const { categories: tokenCate, data: tokenData } = groupByType(
+ data || [],
+ 'token',
+ groupBy || GroupBy.Model,
+ );
+ return (
+ <StatisticCard
+ chart={
+ data &&
+ (type === ShowType.Spend ? (
+ <UsageBarChart categories={spendCate} data={spendData} index="day" />
+ ) : (
+ <UsageBarChart categories={tokenCate} data={tokenData} index="day" />
+ ))
+ }
+ extra={
+ <Segmented
+ onChange={(value) => setType(value as ShowType)}
+ options={[
+ { label: t('usage.trends.spend'), value: ShowType.Spend },
+ { label: t('usage.trends.tokens'), value: ShowType.Token },
+ ]}
+ value={type}
+ />
+ }
+ loading={isLoading}
+ />
+ );
+});
+
+export default UsageTrends;
diff --git a/src/app/[variants]/(main)/profile/usage/features/components/UsageBarChart.tsx b/src/app/[variants]/(main)/profile/usage/features/components/UsageBarChart.tsx
new file mode 100644
index 00000000000..8405bbd3218
--- /dev/null
+++ b/src/app/[variants]/(main)/profile/usage/features/components/UsageBarChart.tsx
@@ -0,0 +1,48 @@
+import { Divider, Typography } from 'antd'
+import { Flexbox } from 'react-layout-kit';
+import { BarChart, ChartTooltipFrame, ChartTooltipRow, type BarChartProps } from '@lobehub/charts';
+
+export const UsageBarChart = ({ ...props }: BarChartProps) => (
+ <BarChart
+ {...props}
+ customTooltip={({ active, payload, label, valueFormatter }) => {
+ if (active && payload) {
+ return (
+ <ChartTooltipFrame>
+ <Flexbox
+ horizontal
+ justify={'space-between'}
+ paddingBlock={8}
+ paddingInline={16}
+ >
+ <Typography.Paragraph ellipsis style={{ margin: 0 }}>
+ {label}
+ </Typography.Paragraph>
+ <span style={{ fontWeight: 'bold' }}>
+ {payload.reduce((acc: number, cur: any) => acc + cur.value, 0)}
+ </span>
+ </Flexbox>
+ <Divider style={{ margin: 0 }} />
+ <Flexbox
+ gap={4}
+ paddingBlock={8}
+ paddingInline={16}
+ style={{ flexDirection: 'column-reverse', marginTop: 4 }}
+ >
+ {payload.map(({ value, color, name }: any, idx: number) => (
+ typeof value === 'number' && value > 0 ?
+ <ChartTooltipRow
+ color={color}
+ key={`id-${idx}`}
+ name={name}
+ value={(valueFormatter as any)?.(value)}
+ /> : null
+ ))}
+ </Flexbox>
+ </ChartTooltipFrame>
+ );
+ }
+ return null;
+ }}
+ />
+)
\ No newline at end of file
diff --git a/src/app/[variants]/(main)/profile/usage/page.tsx b/src/app/[variants]/(main)/profile/usage/page.tsx
new file mode 100644
index 00000000000..280c35922b2
--- /dev/null
+++ b/src/app/[variants]/(main)/profile/usage/page.tsx
@@ -0,0 +1,23 @@
+import { metadataModule } from '@/server/metadata';
+import { translation } from '@/server/translation';
+import { DynamicLayoutProps } from '@/types/next';
+import { RouteVariants } from '@/utils/server/routeVariants';
+
+import Client from './Client';
+
+export const generateMetadata = async (props: DynamicLayoutProps) => {
+ const locale = await RouteVariants.getLocale(props);
+ const { t } = await translation('auth', locale);
+ return metadataModule.generate({
+ description: t('header.desc'),
+ title: t('tab.usage'),
+ url: '/profile/usage',
+ });
+};
+
+const Page = async (props: DynamicLayoutProps) => {
+ const mobile = await RouteVariants.getIsMobile(props);
+ return <Client mobile={mobile} />;
+};
+
+export default Page;
diff --git a/src/locales/default/auth.ts b/src/locales/default/auth.ts
index f8f89e79056..6ef95aeeeae 100644
--- a/src/locales/default/auth.ts
+++ b/src/locales/default/auth.ts
@@ -147,5 +147,49 @@ export default {
profile: '个人资料',
security: '安全',
stats: '数据统计',
+ usage: '用量统计',
+ },
+ usage: {
+ activeModels: {
+ modelTable: '模型列表',
+ models: '活跃模型',
+ providerTable: '提供商列表',
+ providers: '活跃提供商',
+ table: {
+ calls: '调用次数',
+ model: '模型',
+ provider: '提供商',
+ spend: '花费',
+ },
+ },
+ cards: {
+ month: {
+ modelCalls: '模型调用',
+ title: '本月花费',
+ },
+ today: {
+ title: '今日花费',
+ yesterday: '昨日',
+ },
+ },
+ table: {
+ actions: '操作',
+ createdAt: '使用时间',
+ inputTokens: '输入 Token',
+ model: '模型',
+ outputTokens: '输出 Token',
+ spend: '花费',
+ tps: 'TPS',
+ ttft: 'TTFT',
+ type: '调用类型',
+ },
+ trends: {
+ spend: '金额',
+ tokens: 'Token',
+ },
+ welcome: {
+ model: '模型',
+ provider: '提供商',
+ },
},
};
diff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.ts
index a238d480243..c1a7ece2549 100644
--- a/src/server/routers/lambda/index.ts
+++ b/src/server/routers/lambda/index.ts
@@ -31,6 +31,7 @@ import { threadRouter } from './thread';
import { topicRouter } from './topic';
import { uploadRouter } from './upload';
import { userRouter } from './user';
+import { usageRouter } from './usage';
export const lambdaRouter = router({
agent: agentRouter,
@@ -62,6 +63,7 @@ export const lambdaRouter = router({
topic: topicRouter,
upload: uploadRouter,
user: userRouter,
+ usage: usageRouter,
});
export type LambdaRouter = typeof lambdaRouter;
diff --git a/src/server/routers/lambda/usage.ts b/src/server/routers/lambda/usage.ts
new file mode 100644
index 00000000000..8c281e6d643
--- /dev/null
+++ b/src/server/routers/lambda/usage.ts
@@ -0,0 +1,27 @@
+import { z } from 'zod';
+import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { UsageRecordService } from '@/server/services/usage';
+
+const usageProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts
+ return opts.next({
+ ctx: {
+ usageRecordService: new UsageRecordService(ctx.serverDB, ctx.userId),
+ },
+ });
+});
+
+export const usageRouter = router({
+ findByMonth: usageProcedure.input(z.object({
+ mo: z.string().optional(),
+ })).query(async ({ ctx, input }) => {
+ return await ctx.usageRecordService.findByMonth(input.mo);
+ }),
+
+ findAndGroupByDay: usageProcedure.input(z.object({
+ mo: z.string().optional(),
+ })).query(async ({ ctx, input }) => {
+ return await ctx.usageRecordService.findAndGroupByDay(input.mo);
+ }),
+})
\ No newline at end of file
diff --git a/src/server/services/usage/index.test.ts b/src/server/services/usage/index.test.ts
new file mode 100644
index 00000000000..7161f930088
--- /dev/null
+++ b/src/server/services/usage/index.test.ts
@@ -0,0 +1,310 @@
+import dayjs from 'dayjs';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { LobeChatDatabase } from '@/database/type';
+import { MessageMetadata } from '@/types/message';
+
+import { UsageRecordService } from './index';
+
+describe('UsageRecordService', () => {
+ let service: UsageRecordService;
+ let mockDb: LobeChatDatabase;
+ const userId = 'test-user-id';
+
+ // Helper function to setup query chain mock
+ const setupQueryChainMock = (mockMessages: any[]) => {
+ const mockOrderBy = vi.fn().mockResolvedValue(mockMessages);
+ const mockWhere = vi.fn().mockReturnValue({ orderBy: mockOrderBy });
+ const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });
+ mockDb.select = vi.fn().mockReturnValue({ from: mockFrom });
+ };
+
+ beforeEach(() => {
+ // Create a fresh mock for each test
+ const mockOrderBy = vi.fn();
+ const mockWhere = vi.fn().mockReturnValue({ orderBy: mockOrderBy });
+ const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });
+ const mockSelect = vi.fn().mockReturnValue({ from: mockFrom });
+
+ mockDb = {
+ select: mockSelect,
+ } as unknown as LobeChatDatabase;
+
+ service = new UsageRecordService(mockDb, userId);
+ });
+
+ describe('findByMonth', () => {
+ it('should return usage records for the current month when no month is provided', async () => {
+ const mockMessages = [
+ {
+ id: 'msg-1',
+ userId: userId,
+ role: 'assistant',
+ provider: 'openai',
+ model: 'gpt-4',
+ createdAt: new Date(),
+ metadata: {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ tps: 10,
+ ttft: 500,
+ } as MessageMetadata,
+ },
+ ];
+
+ setupQueryChainMock(mockMessages);
+
+ const result = await service.findByMonth();
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ id: 'msg-1',
+ model: 'gpt-4',
+ provider: 'openai',
+ spend: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150,
+ tps: 10,
+ ttft: 500,
+ type: 'chat',
+ userId: userId,
+ });
+ });
+
+ it('should return usage records for a specific month', async () => {
+ const mockMessages = [
+ {
+ id: 'msg-1',
+ userId: userId,
+ role: 'assistant',
+ provider: 'anthropic',
+ model: 'claude-3',
+ createdAt: new Date('2024-01-15'),
+ metadata: {
+ cost: 0.03,
+ totalInputTokens: 80,
+ totalOutputTokens: 40,
+ } as MessageMetadata,
+ },
+ ];
+
+ setupQueryChainMock(mockMessages);
+
+ const result = await service.findByMonth('2024-01');
+
+ expect(result[0].model).toBe('claude-3');
+ expect(result[0].spend).toBe(0.03);
+ });
+
+ it('should handle messages with missing metadata fields', async () => {
+ const mockMessages = [
+ {
+ id: 'msg-1',
+ userId: userId,
+ role: 'assistant',
+ provider: 'openai',
+ model: 'gpt-3.5-turbo',
+ createdAt: new Date(),
+ metadata: {} as MessageMetadata,
+ },
+ ];
+
+ setupQueryChainMock(mockMessages);
+
+ const result = await service.findByMonth();
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ spend: 0,
+ totalInputTokens: 0,
+ totalOutputTokens: 0,
+ totalTokens: 0,
+ tps: 0,
+ ttft: 0,
+ });
+ });
+
+ it('should return empty array when no messages found', async () => {
+ setupQueryChainMock([]);
+
+ const result = await service.findByMonth();
+
+ expect(result).toHaveLength(0);
+ });
+ });
+
+ describe('findAndGroupByDay', () => {
+ it('should group usage records by day for current month', async () => {
+ const date1 = dayjs().startOf('month').toDate();
+ const date2 = dayjs().startOf('month').add(1, 'day').toDate();
+
+ const mockMessages = [
+ {
+ id: 'msg-1',
+ userId: userId,
+ role: 'assistant',
+ provider: 'openai',
+ model: 'gpt-4',
+ createdAt: date1,
+ metadata: {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ } as MessageMetadata,
+ },
+ {
+ id: 'msg-2',
+ userId: userId,
+ role: 'assistant',
+ provider: 'openai',
+ model: 'gpt-4',
+ createdAt: date1,
+ metadata: {
+ cost: 0.03,
+ totalInputTokens: 60,
+ totalOutputTokens: 30,
+ } as MessageMetadata,
+ },
+ {
+ id: 'msg-3',
+ userId: userId,
+ role: 'assistant',
+ provider: 'anthropic',
+ model: 'claude-3',
+ createdAt: date2,
+ metadata: {
+ cost: 0.02,
+ totalInputTokens: 40,
+ totalOutputTokens: 20,
+ } as MessageMetadata,
+ },
+ ];
+
+ setupQueryChainMock(mockMessages);
+
+ const result = await service.findAndGroupByDay();
+
+ expect(result.length).toBeGreaterThan(0);
+
+ // Check that days with records have correct aggregations
+ const dayWithRecords = result.find((log) => log.totalRequests > 0);
+ if (dayWithRecords) {
+ expect(dayWithRecords.totalSpend).toBeGreaterThan(0);
+ expect(dayWithRecords.totalTokens).toBeGreaterThan(0);
+ expect(dayWithRecords.records.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('should pad missing days with zero values', async () => {
+ const firstDay = dayjs().startOf('month');
+
+ const mockMessages = [
+ {
+ id: 'msg-1',
+ userId: userId,
+ role: 'assistant',
+ provider: 'openai',
+ model: 'gpt-4',
+ createdAt: firstDay.toDate(),
+ metadata: {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ } as MessageMetadata,
+ },
+ ];
+
+ setupQueryChainMock(mockMessages);
+
+ const result = await service.findAndGroupByDay();
+
+ // Should have entries for every day in the month
+ const daysInMonth = dayjs().endOf('month').date();
+ expect(result.length).toBeGreaterThanOrEqual(daysInMonth - 1);
+
+ // Check that padded days have zero values
+ const paddedDay = result.find((log) => log.totalRequests === 0);
+ if (paddedDay) {
+ expect(paddedDay.totalSpend).toBe(0);
+ expect(paddedDay.totalTokens).toBe(0);
+ expect(paddedDay.records).toHaveLength(0);
+ }
+ });
+
+ it('should calculate correct totals for days with multiple records', async () => {
+ const testDate = dayjs().startOf('month').toDate();
+
+ const mockMessages = [
+ {
+ id: 'msg-1',
+ userId: userId,
+ role: 'assistant',
+ provider: 'openai',
+ model: 'gpt-4',
+ createdAt: testDate,
+ metadata: {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ } as MessageMetadata,
+ },
+ {
+ id: 'msg-2',
+ userId: userId,
+ role: 'assistant',
+ provider: 'openai',
+ model: 'gpt-4',
+ createdAt: testDate,
+ metadata: {
+ cost: 0.03,
+ totalInputTokens: 60,
+ totalOutputTokens: 30,
+ } as MessageMetadata,
+ },
+ ];
+
+ setupQueryChainMock(mockMessages);
+
+ const result = await service.findAndGroupByDay();
+
+ const dayLog = result.find((log) => log.totalRequests === 2);
+
+ if (dayLog) {
+ expect(dayLog.totalSpend).toBe(0.08);
+ expect(dayLog.totalTokens).toBe(240); // (100+50) + (60+30)
+ expect(dayLog.totalRequests).toBe(2);
+ expect(dayLog.records).toHaveLength(2);
+ }
+ });
+
+ it('should handle specific month parameter', async () => {
+ const mockMessages = [
+ {
+ id: 'msg-1',
+ userId: userId,
+ role: 'assistant',
+ provider: 'openai',
+ model: 'gpt-4',
+ createdAt: new Date('2024-01-15'),
+ metadata: {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ } as MessageMetadata,
+ },
+ ];
+
+ setupQueryChainMock(mockMessages);
+
+ const result = await service.findAndGroupByDay('2024-01');
+
+ expect(result.length).toBeGreaterThan(0);
+ // All days should be from January 2024
+ result.forEach((log) => {
+ expect(log.day).toMatch(/^2024-01/);
+ });
+ });
+ });
+});
diff --git a/src/server/services/usage/index.ts b/src/server/services/usage/index.ts
new file mode 100644
index 00000000000..6abb084bcc4
--- /dev/null
+++ b/src/server/services/usage/index.ts
@@ -0,0 +1,164 @@
+import dayjs from 'dayjs';
+import debug from 'debug';
+import { desc, eq } from 'drizzle-orm';
+
+import { messages } from '@/database/schemas';
+import { LobeChatDatabase } from '@/database/type';
+import { genRangeWhere, genWhere } from '@/database/utils/genWhere';
+import { MessageMetadata } from '@/types/message';
+import { UsageLog, UsageRecordItem } from '@/types/usage/usageRecord';
+import { formatDate } from '@/utils/format';
+
+const log = debug('lobe-usage:service');
+
+export class UsageRecordService {
+ private userId: string;
+ private db: LobeChatDatabase;
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.userId = userId;
+ this.db = db;
+ }
+
+ /**
+ * @description Find usage records by month.
+ * @param mo Month
+ * @returns UsageRecordItem[]
+ */
+ findByMonth = async (mo?: string): Promise<UsageRecordItem[]> => {
+ // 设置 startAt 和 endAt
+ let startAt: string;
+ let endAt: string;
+ if (mo) {
+ // mo 格式: "YYYY-MM"
+ startAt = dayjs(mo, 'YYYY-MM').startOf('month').format('YYYY-MM-DD');
+ endAt = dayjs(mo, 'YYYY-MM').endOf('month').format('YYYY-MM-DD');
+ } else {
+ startAt = dayjs().startOf('month').format('YYYY-MM-DD');
+ endAt = dayjs().endOf('month').format('YYYY-MM-DD');
+ }
+
+ // TODO: To extend to support other features
+ // - Functionality:
+ // - More type of usage, e.g. image generation, file processing, summary, search engine.
+ // - More dimension for analysis, e.g. relational analysis.
+ // - Performance: Computing asynchronously for performance.
+ // For now, we only support chat messages for normal users for PoC.
+
+ const spends = await this.db
+ .select({
+ createdAt: messages.createdAt,
+ id: messages.id,
+ metadata: messages.metadata,
+ model: messages.model,
+ provider: messages.provider,
+ role: messages.role,
+ updatedAt: messages.createdAt,
+ userId: messages.userId,
+ })
+ .from(messages)
+ .where(
+ genWhere([
+ eq(messages.userId, this.userId),
+ eq(messages.role, 'assistant'),
+ genRangeWhere([startAt, endAt], messages.createdAt, (date) => date.toDate()),
+ ]),
+ )
+ .orderBy(desc(messages.createdAt));
+ return spends.map((spend) => {
+ const metadata = spend.metadata as MessageMetadata;
+ return {
+ createdAt: spend.createdAt,
+ id: spend.id,
+ metadata: spend.metadata,
+ model: spend.model,
+ provider: spend.provider,
+ spend: metadata?.cost || 0, // Messages do not have a direct cost associated
+ totalInputTokens: metadata?.totalInputTokens || 0,
+ totalOutputTokens: metadata?.totalOutputTokens || 0,
+ totalTokens: (metadata?.totalInputTokens || 0) + (metadata?.totalOutputTokens || 0),
+ tps: metadata?.tps || 0,
+ ttft: metadata?.ttft || 0,
+ type: 'chat', // Default to 'chat' for messages
+ updatedAt: spend.createdAt,
+ userId: spend.userId,
+ } as UsageRecordItem;
+ });
+ };
+
+ findAndGroupByDay = async (mo?: string): Promise<UsageLog[]> => {
+ // 设置 startAt 和 endAt
+ let startAt: string;
+ let endAt: string;
+ if (mo) {
+ // mo 格式: "YYYY-MM"
+ startAt = dayjs(mo, 'YYYY-MM').startOf('month').format('YYYY-MM-DD');
+ endAt = dayjs(mo, 'YYYY-MM').endOf('month').format('YYYY-MM-DD');
+ } else {
+ startAt = dayjs().startOf('month').format('YYYY-MM-DD');
+ endAt = dayjs().endOf('month').format('YYYY-MM-DD');
+ }
+ const spends = await this.findByMonth(mo);
+ // Clustering by time
+ let usages = new Map<string, { date: Date; logs: UsageRecordItem[] }>();
+ spends.forEach((spend) => {
+ if (!usages.has(formatDate(spend.createdAt))) {
+ usages.set(formatDate(spend.createdAt), { date: spend.createdAt, logs: [spend] });
+ return;
+ }
+ usages.get(formatDate(spend.createdAt))?.logs.push(spend);
+ });
+ // Calculate usage
+ let usageLogs: UsageLog[] = [];
+ usages.forEach((spends, date) => {
+ const totalSpend = spends.logs.reduce((acc, spend) => acc + spend.spend, 0);
+ const totalTokens = spends.logs.reduce((acc, spend) => (spend.totalTokens || 0) + acc, 0);
+ const totalRequests = spends.logs?.length ?? 0;
+ log(
+ 'date',
+ date,
+ 'totalSpend',
+ totalSpend,
+ 'totalTokens',
+ totalTokens,
+ 'totalRequests',
+ totalRequests,
+ );
+ usageLogs.push({
+ date: spends.date.getTime(),
+ day: date,
+ records: spends.logs,
+ totalRequests,
+ totalSpend,
+ totalTokens, // Store the formatted date as a string
+ });
+ });
+ // Padding to ensure the date range is complete
+ const startDate = dayjs(startAt);
+ const endDate = dayjs(endAt);
+ const paddedUsageLogs: UsageLog[] = [];
+ // For every day in the range, check if it exists in usageLogs
+ // If exists, use it; if not, create a new log with 0 values
+ log(
+ 'Padding usage logs from',
+ startDate.format('YYYY-MM-DD'),
+ 'to',
+ endDate.format('YYYY-MM-DD'),
+ );
+ for (let date = startDate; date.isBefore(endDate); date = date.add(1, 'day')) {
+ const log = usageLogs.find((log) => log.day === date.format('YYYY-MM-DD'));
+ if (log) {
+ paddedUsageLogs.push(log);
+ } else {
+ paddedUsageLogs.push({
+ date: date.toDate().getTime(),
+ day: date.format('YYYY-MM-DD'),
+ records: [],
+ totalRequests: 0,
+ totalSpend: 0,
+ totalTokens: 0,
+ });
+ }
+ }
+ return paddedUsageLogs;
+ };
+}
diff --git a/src/services/usage.ts b/src/services/usage.ts
new file mode 100644
index 00000000000..11981bfe66a
--- /dev/null
+++ b/src/services/usage.ts
@@ -0,0 +1,13 @@
+import { lambdaClient } from "@/libs/trpc/client";
+
+class UsageService {
+ findByMonth = async (mo?: string) => {
+ return lambdaClient.usage.findByMonth.query({ mo });
+ };
+
+ findAndGroupByDay = async (mo?: string) => {
+ return lambdaClient.usage.findAndGroupByDay.query({ mo });
+ }
+}
+
+export const usageService = new UsageService();
\ No newline at end of file
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 9b395f8ac77..a7f0761d863 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -50,6 +50,7 @@ export enum ProfileTabs {
Profile = 'profile',
Security = 'security',
Stats = 'stats',
+ Usage = 'usage',
}
export interface SystemStatus {