import { RealtimeClient } from '@openai/realtime-api-beta';const client = new RealtimeClient({ apiKey: 'your-api-key', // For browser environments, set this to true /* Warning: Use only in development or testing — exposes your API key */ dangerouslyAllowAPIKeyInBrowser: true});// Or use a relay server to protect your API keyconst client = new RealtimeClient({ url: 'your-relay-server-url'});
After creating the client, you can set instructions for your AI agent, configure various session parameters:
Copy
// Configure the session with multiple parametersclient.updateSession({ // Set system instructions for the AI instructions: 'You are a helpful assistant', // Set voice and language voice: 'monica', language: 'en', // Set up Voice Activity Detection turn_detection: { type: 'server_vad', threshold: 0.5, prefix_padding_ms: 300, silence_duration_ms: 500 }});
// Connect to the serviceawait client.connect();// Send a text messageclient.sendUserMessageContent([{ type: 'input_text', text: 'Hello!'}]);// Listen for responsesclient.on('conversation.updated', ({ item, delta }) => { if (delta?.audio) { // `delta.audio` contains raw audio chunks (typically in binary or base64 format). // You need to implement the `playAudio` function to handle playback, // e.g., using Web Audio API or any audio player of your choice. playAudio(delta.audio); } if (item.formatted.text) { // Handle text response console.log(item.formatted.text); }});
“Try this example script to quickly test and start conversing with a custom AI agent.”