| 1 | import { Injectable, Logger } from '@nestjs/common' |
| 2 | import axios, { AxiosInstance, AxiosResponse } from 'axios' |
| 3 | import { AiAvailabilityService } from '../../../ai-availability' |
| 4 | import { GrokConfig } from './grok.config' |
| 5 | import { |
| 6 | GrokCreateVideoRequest, |
| 7 | GrokCreateVideoResponse, |
| 8 | GrokEditVideoRequest, |
| 9 | GrokGetVideoStatusResponse, |
| 10 | } from './grok.interface' |
| 11 | |
| 12 | @Injectable() |
| 13 | export class GrokLibService { |
| 14 | private readonly logger = new Logger(GrokLibService.name) |
| 15 | private readonly httpClient: AxiosInstance |
| 16 | |
| 17 | constructor( |
| 18 | private readonly config: GrokConfig, |
| 19 | private readonly aiAvailability: AiAvailabilityService, |
| 20 | ) { |
| 21 | this.httpClient = this._createHttpClient() |
| 22 | } |
| 23 | |
| 24 | private async withAvailability<T>(operation: string, fn: () => Promise<T>, model?: string): Promise<T> { |
| 25 | return this.aiAvailability.execute( |
| 26 | { provider: 'grok', operation, model }, |
| 27 | fn, |
| 28 | ) |
| 29 | } |
| 30 | |
| 31 | private _createHttpClient(): AxiosInstance { |
| 32 | const baseURL = this.config.proxyUrl |
| 33 | ? `${this.config.proxyUrl}/${this.config.baseUrl}` |
| 34 | : this.config.baseUrl |
| 35 | |
| 36 | return axios.create({ |
| 37 | baseURL, |
| 38 | timeout: 60000, |
| 39 | headers: { |
| 40 | 'Content-Type': 'application/json', |
| 41 | 'Authorization': `Bearer ${this.config.apiKey}`, |
| 42 | }, |
| 43 | }) |
| 44 | } |
| 45 | |
| 46 | async createVideo(request: GrokCreateVideoRequest): Promise<GrokCreateVideoResponse> { |
| 47 | return this.withAvailability('createVideo', async () => { |
| 48 | const response: AxiosResponse<GrokCreateVideoResponse> = await this.httpClient.post( |
| 49 | '/v1/videos/generations', |
| 50 | request, |
| 51 | ) |
| 52 | return response.data |
| 53 | }, request.model) |
| 54 | } |
| 55 | |
| 56 | async editVideo(request: GrokEditVideoRequest): Promise<GrokCreateVideoResponse> { |
| 57 | return this.withAvailability('editVideo', async () => { |
| 58 | this.logger.log({ path: '--------GrokLibService editVideo request----------', request }) |
| 59 | const response: AxiosResponse<GrokCreateVideoResponse> = await this.httpClient.post( |
| 60 | '/v1/videos/edits', |
| 61 | request, |
| 62 | ) |
| 63 | return response.data |
| 64 | }, request.model) |
| 65 | } |
| 66 | |
| 67 | async getVideoStatus(requestId: string): Promise<GrokGetVideoStatusResponse> { |
| 68 | return this.withAvailability('getVideoStatus', async () => { |
| 69 | const response: AxiosResponse<GrokGetVideoStatusResponse> = await this.httpClient.get( |
| 70 | `/v1/videos/${requestId}`, |
| 71 | ) |
| 72 | return response.data |
| 73 | }) |
| 74 | } |
| 75 | } |
| 76 |