platformApi.ts 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. /**
  2. * 开放平台API服务
  3. *
  4. * 提供API Key管理、调用统计和日志查询功能
  5. * 需求: 7, 11, 12
  6. */
  7. import { authService } from './authService';
  8. const RAW_API_BASE = import.meta.env.VITE_API_BASE_URL || '';
  9. const DEFAULT_API_PATH = import.meta.env.VITE_API_BASE_PATH || '/api/v1';
  10. export const API_BASE = RAW_API_BASE;
  11. // API_BASE_FULL: 如果 RAW_API_BASE 已包含 /api/... 则直接使用,否则追加默认的路径
  12. export const API_BASE_FULL = (() => {
  13. if (!RAW_API_BASE) return DEFAULT_API_PATH;
  14. if (/\/api(\/|$)/.test(RAW_API_BASE)) return RAW_API_BASE;
  15. return RAW_API_BASE.replace(/\/+$/g, '') + DEFAULT_API_PATH;
  16. })();
  17. export interface ApiKey {
  18. id: number;
  19. api_key_prefix: string;
  20. name: string | null;
  21. status: 'active' | 'disabled';
  22. key_type: 'public' | 'local';
  23. last_used_at: string | null;
  24. created_at: string;
  25. }
  26. export interface ApiKeyCreateResponse {
  27. id: number;
  28. api_key: string;
  29. api_key_prefix: string;
  30. name: string | null;
  31. key_type: 'public' | 'local';
  32. created_at: string;
  33. }
  34. export interface TrendItem {
  35. date: string;
  36. count: number;
  37. cost: string;
  38. }
  39. export interface ModelDistItem {
  40. model_name: string;
  41. count: number;
  42. percentage: number;
  43. }
  44. export interface Stats {
  45. today_calls: number;
  46. month_calls: number;
  47. total_calls: number;
  48. today_cost: string;
  49. month_cost: string;
  50. trend_data: TrendItem[];
  51. model_distribution: ModelDistItem[];
  52. }
  53. export interface CallLog {
  54. id: number;
  55. model_name: string;
  56. is_local: boolean;
  57. input_tokens: number;
  58. output_tokens: number;
  59. bill: string;
  60. status: string;
  61. api_key_prefix: string;
  62. created_at: string;
  63. input_price: string | null;
  64. output_price: string | null;
  65. }
  66. export interface CallLogQuery {
  67. start_date?: string;
  68. end_date?: string;
  69. model_id?: number;
  70. api_key_id?: number;
  71. page?: number;
  72. page_size?: number;
  73. }
  74. export interface PaginatedResponse<T> {
  75. items: T[];
  76. total: number;
  77. page: number;
  78. page_size: number;
  79. total_pages: number;
  80. }
  81. interface ApiResponse<T> {
  82. code: number;
  83. message: string;
  84. data: T;
  85. }
  86. async function request<T>(url: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
  87. const token = authService.getToken();
  88. const headers: HeadersInit = {
  89. 'Content-Type': 'application/json',
  90. ...(token ? { Authorization: `Bearer ${token}` } : {}),
  91. ...options.headers,
  92. };
  93. const response = await fetch(`${API_BASE}${url}`, {
  94. ...options,
  95. headers,
  96. });
  97. if (!response.ok) {
  98. const error = await response.json().catch(() => ({ message: '请求失败' }));
  99. throw new Error(error.detail || error.message || '请求失败');
  100. }
  101. return response.json();
  102. }
  103. export const platformApi = {
  104. // API Key 管理
  105. async getApiKeys(): Promise<ApiKey[]> {
  106. const res = await request<ApiKey[]>('/api/platform/api-keys');
  107. return res.data;
  108. },
  109. async createApiKey(name?: string, keyType: 'public' | 'local' = 'public'): Promise<ApiKeyCreateResponse> {
  110. const res = await request<ApiKeyCreateResponse>('/api/platform/api-keys', {
  111. method: 'POST',
  112. body: JSON.stringify({ name, key_type: keyType }),
  113. });
  114. return res.data;
  115. },
  116. async updateApiKeyStatus(id: number, status: 'active' | 'disabled'): Promise<ApiKey> {
  117. const res = await request<ApiKey>(`/api/platform/api-keys/${id}`, {
  118. method: 'PUT',
  119. body: JSON.stringify({ status }),
  120. });
  121. return res.data;
  122. },
  123. async deleteApiKey(id: number): Promise<void> {
  124. await request<{ success: boolean }>(`/api/platform/api-keys/${id}`, {
  125. method: 'DELETE',
  126. });
  127. },
  128. // 统计
  129. async getStats(trendDays: number = 7, keyType?: 'public' | 'local'): Promise<Stats> {
  130. let url = `/api/platform/stats?trend_days=${trendDays}`;
  131. if (keyType) {
  132. url += `&key_type=${keyType}`;
  133. }
  134. const res = await request<Stats>(url);
  135. return res.data;
  136. },
  137. // 调用日志
  138. async getCallLogs(query: CallLogQuery & { key_type?: 'public' | 'local' } = {}): Promise<PaginatedResponse<CallLog>> {
  139. const params = new URLSearchParams();
  140. if (query.start_date) params.append('start_date', query.start_date);
  141. if (query.end_date) params.append('end_date', query.end_date);
  142. if (query.model_id) params.append('model_id', String(query.model_id));
  143. if (query.api_key_id) params.append('api_key_id', String(query.api_key_id));
  144. if (query.key_type) params.append('key_type', query.key_type);
  145. if (query.page) params.append('page', String(query.page));
  146. if (query.page_size) params.append('page_size', String(query.page_size));
  147. const url = `/api/platform/call-logs${params.toString() ? '?' + params.toString() : ''}`;
  148. const res = await request<PaginatedResponse<CallLog>>(url);
  149. return res.data;
  150. },
  151. };