|
| 1 | +import OpenAI from 'openai'; |
| 2 | +import { |
| 3 | + OpenAIRealtimeSIP, |
| 4 | + RealtimeAgent, |
| 5 | + RealtimeSession, |
| 6 | + type RealtimeSessionOptions, |
| 7 | +} from '@openai/agents/realtime'; |
| 8 | + |
| 9 | +const openai = new OpenAI({ |
| 10 | + apiKey: process.env.OPENAI_API_KEY!, |
| 11 | + webhookSecret: process.env.OPENAI_WEBHOOK_SECRET!, |
| 12 | +}); |
| 13 | + |
| 14 | +const agent = new RealtimeAgent({ |
| 15 | + name: 'Receptionist', |
| 16 | + instructions: |
| 17 | + 'Welcome the caller, answer scheduling questions, and hand off if the caller requests a human.', |
| 18 | +}); |
| 19 | + |
| 20 | +const sessionOptions: Partial<RealtimeSessionOptions> = { |
| 21 | + model: 'gpt-realtime', |
| 22 | + config: { |
| 23 | + audio: { |
| 24 | + input: { |
| 25 | + turnDetection: { type: 'semantic_vad', interruptResponse: true }, |
| 26 | + }, |
| 27 | + }, |
| 28 | + }, |
| 29 | +}; |
| 30 | + |
| 31 | +export async function acceptIncomingCall(callId: string): Promise<void> { |
| 32 | + const initialConfig = await OpenAIRealtimeSIP.buildInitialConfig( |
| 33 | + agent, |
| 34 | + sessionOptions, |
| 35 | + ); |
| 36 | + await openai.realtime.calls.accept(callId, initialConfig); |
| 37 | +} |
| 38 | + |
| 39 | +export async function attachRealtimeSession( |
| 40 | + callId: string, |
| 41 | +): Promise<RealtimeSession> { |
| 42 | + const session = new RealtimeSession(agent, { |
| 43 | + transport: new OpenAIRealtimeSIP(), |
| 44 | + ...sessionOptions, |
| 45 | + }); |
| 46 | + |
| 47 | + session.on('history_added', (item) => { |
| 48 | + console.log('Realtime update:', item.type); |
| 49 | + }); |
| 50 | + |
| 51 | + await session.connect({ |
| 52 | + apiKey: process.env.OPENAI_API_KEY!, |
| 53 | + callId, |
| 54 | + }); |
| 55 | + |
| 56 | + return session; |
| 57 | +} |
0 commit comments