import { OpenAi, createAiClient } from '@modal-sh/mio-ai'; import { EventEmitter } from 'events'; import { BaseTranscriptItem } from './transcript'; export type DataEventCallback = (event: string) => void; export type ErrorEventCallback = (event: Error) => void; export interface SummarizerEventEmitter extends NodeJS.EventEmitter { normalize(transcriptItems: T[]): Promise; summarize(transcript: string): void; on(eventType: 'data', callback: DataEventCallback): this; on(eventType: 'error', callback: ErrorEventCallback): this; on(eventType: 'end', callback: () => void): this; } export class SummarizerEventEmitterImpl extends EventEmitter { private readonly openAiClient: OpenAi.PlatformEventEmitter; constructor(params: OpenAi.Configuration) { super(); this.openAiClient = createAiClient({ platform: OpenAi.PLATFORM_ID, platformConfiguration: params, }); } normalize(transcript: T[]) { return new Promise((resolve, reject) => { this.openAiClient.once('data', (data) => { const normalizedTranscript = data.choices[0].text; resolve(normalizedTranscript); }); this.openAiClient.once('error', (error) => { reject(error); }); this.openAiClient.createEdit({ input: transcript.map((item) => item.text).join(' '), instruction: 'Put proper punctuation and correct capitalization', model: OpenAi.EditModel.TEXT_DAVINCI_EDIT_001, }); }); } summarize(normalizedTranscript: string) { const listener = (data: OpenAi.ChatCompletionChunkDataEvent) => { const theContent = data.choices[0].delta.content; if (typeof theContent !== 'string') { return; } this.emit('data', theContent) }; this.openAiClient.on('data', listener); this.openAiClient.once('error', (error) => { this.openAiClient.off('data', listener); this.emit('error', error); }); this.openAiClient.once('end', () => { this.openAiClient.off('data', listener); this.emit('end'); }); this.openAiClient.createChatCompletion({ model: OpenAi.ChatCompletionModel.GPT_3_5_TURBO, messages: [ { role: OpenAi.MessageRole.SYSTEM, content: 'You are working on video transcripts.', }, { role: OpenAi.MessageRole.USER, content: `Summarize the following transcript:\n\n${normalizedTranscript}`, }, ], }); } }