|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- 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<T = unknown> extends NodeJS.EventEmitter {
- normalize(transcriptItems: T[]): Promise<string>;
- 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<T extends BaseTranscriptItem> 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<string>((resolve, reject) => {
- this.openAiClient.once<OpenAi.CreateEditDataEvent>('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<OpenAi.ChatCompletionChunkDataEvent>('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}`,
- },
- ],
- });
- }
- }
|