|
| 1 | +import { PanelProvider } from '@/views/panel/backend/panel-provider' |
| 2 | +import { make_api_request } from '@/utils/make-api-request' |
| 3 | +import axios, { CancelTokenSource } from 'axios' |
| 4 | +import { Logger } from '@shared/utils/logger' |
| 5 | +import { dictionary } from '@shared/constants/dictionary' |
| 6 | + |
| 7 | +export class ApiManager { |
| 8 | + public api_call_cancel_token_source: CancelTokenSource | null = null |
| 9 | + |
| 10 | + constructor(private panel_provider: PanelProvider) {} |
| 11 | + |
| 12 | + public async get(params: { |
| 13 | + endpoint_url: string |
| 14 | + api_key?: string |
| 15 | + body: any |
| 16 | + }): Promise<{ response: string; thoughts?: string } | null> { |
| 17 | + const cancel_token_source = axios.CancelToken.source() |
| 18 | + this.api_call_cancel_token_source = cancel_token_source |
| 19 | + |
| 20 | + try { |
| 21 | + this.panel_provider.send_message({ |
| 22 | + command: 'SHOW_API_MANAGER_PROGRESS', |
| 23 | + title: `${dictionary.api_call.WAITING_FOR_RESPONSE}...` |
| 24 | + }) |
| 25 | + |
| 26 | + const result = await make_api_request({ |
| 27 | + endpoint_url: params.endpoint_url, |
| 28 | + api_key: params.api_key, |
| 29 | + body: params.body, |
| 30 | + cancellation_token: cancel_token_source.token, |
| 31 | + on_thinking_chunk: () => { |
| 32 | + this.panel_provider.send_message({ |
| 33 | + command: 'SHOW_API_MANAGER_PROGRESS', |
| 34 | + title: `${dictionary.api_call.THINKING}...` |
| 35 | + }) |
| 36 | + }, |
| 37 | + on_chunk: (tokens_per_second) => { |
| 38 | + this.panel_provider.send_message({ |
| 39 | + command: 'SHOW_API_MANAGER_PROGRESS', |
| 40 | + title: 'Receiving response...', |
| 41 | + tokens_per_second |
| 42 | + }) |
| 43 | + } |
| 44 | + }) |
| 45 | + return result |
| 46 | + } catch (error) { |
| 47 | + if (axios.isCancel(error)) { |
| 48 | + Logger.info({ |
| 49 | + function_name: 'make_api_call', |
| 50 | + message: 'API call cancelled by user' |
| 51 | + }) |
| 52 | + throw error // Re-throw cancellation error to be handled by caller |
| 53 | + } |
| 54 | + |
| 55 | + Logger.error({ |
| 56 | + function_name: 'make_api_call', |
| 57 | + message: 'API call error', |
| 58 | + data: error |
| 59 | + }) |
| 60 | + // Error messages are shown by make_api_request, so no need to show one here. |
| 61 | + return null |
| 62 | + } finally { |
| 63 | + this.panel_provider.send_message({ command: 'HIDE_API_MANAGER_PROGRESS' }) |
| 64 | + this.api_call_cancel_token_source = null |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + public cancel_api_call() { |
| 69 | + if (this.api_call_cancel_token_source) { |
| 70 | + this.api_call_cancel_token_source.cancel('Cancelled by user.') |
| 71 | + this.api_call_cancel_token_source = null |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments