|
1 | 1 | import { VideoApi } from './gen/video/VideoApi'; |
2 | 2 | import { StreamCall } from './StreamCall'; |
| 3 | +import type { StreamClient } from './StreamClient'; |
| 4 | +import type { ApiConfig } from './types'; |
| 5 | +import type { |
| 6 | + RealtimeClient, |
| 7 | + createRealtimeClient, |
| 8 | +} from '@stream-io/openai-realtime-api'; |
3 | 9 |
|
4 | 10 | export class StreamVideoClient extends VideoApi { |
| 11 | + private streamClient: StreamClient; |
| 12 | + |
| 13 | + constructor({ |
| 14 | + streamClient, |
| 15 | + ...apiConfig |
| 16 | + }: ApiConfig & { streamClient: StreamClient }) { |
| 17 | + super(apiConfig); |
| 18 | + this.streamClient = streamClient; |
| 19 | + } |
| 20 | + |
5 | 21 | call = (type: string, id: string) => { |
6 | 22 | return new StreamCall(this, type, id); |
7 | 23 | }; |
| 24 | + |
| 25 | + connectOpenAi = async (options: { |
| 26 | + call: StreamCall; |
| 27 | + agentUserId: string; |
| 28 | + openAiApiKey: string; |
| 29 | + validityInSeconds: number; |
| 30 | + }): Promise<RealtimeClient> => { |
| 31 | + let doCreateRealtimeClient: typeof createRealtimeClient; |
| 32 | + |
| 33 | + try { |
| 34 | + doCreateRealtimeClient = (await import('@stream-io/openai-realtime-api')) |
| 35 | + .createRealtimeClient; |
| 36 | + } catch { |
| 37 | + throw new Error( |
| 38 | + 'Cannot create Realtime API client. Is @stream-io/openai-realtime-api installed?', |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + if (!options.agentUserId) { |
| 43 | + throw new Error('"agentUserId" must by specified in options'); |
| 44 | + } |
| 45 | + |
| 46 | + const token = this.streamClient.generateCallToken({ |
| 47 | + user_id: options.agentUserId, |
| 48 | + call_cids: [options.call.cid], |
| 49 | + validity_in_seconds: options.validityInSeconds, |
| 50 | + }); |
| 51 | + |
| 52 | + const realtimeClient = doCreateRealtimeClient({ |
| 53 | + baseUrl: this.apiConfig.baseUrl, |
| 54 | + call: options.call, |
| 55 | + streamApiKey: this.apiConfig.apiKey, |
| 56 | + streamUserToken: token, |
| 57 | + openAiApiKey: options.openAiApiKey, |
| 58 | + }); |
| 59 | + |
| 60 | + await realtimeClient.connect(); |
| 61 | + return realtimeClient; |
| 62 | + }; |
8 | 63 | } |
0 commit comments