Cliente TypeScript para la API de voz real de OpenAI.

npm install openai-realtime-api Este paquete es solo ESM. Requiere Node.js >= 18 , un entorno de navegador o un tiempo de ejecución JS equivalente (Deno, Bun, trabajadores de CF, etc.).
Importante
Todo el uso y los eventos son 100% compatibles con la versión Operai JS. La principal diferencia aparte de las correcciones de errores es que todos los eventos están completamente de tipo .
import { RealtimeClient } from 'openai-realtime-api'
// Create a new client; all params are optional; apiKey defaults to the
// `OPENAI_API_KEY` environment variable (when using Node.js).
const client = new RealtimeClient ( {
sessionConfig : {
instructions : 'You are a great, upbeat friend.' ,
voice : 'alloy'
}
} )
// Can change session config ahead of connecting.
client . updateSession ( {
turn_detection : null ,
input_audio_transcription : { model : 'whisper-1' }
} )
// Example of custom event handling
client . on ( 'conversation.updated' , ( event ) => {
// All events are fully-typed based on the event name.
// In this case, `event` will have the type `RealtimeCustomEvents.ConversationUpdatedEvent`
const { item , delta } = event
// Access the full list of conversation items.
const items = client . conversation . getItems ( )
} )
// Connect to the Realtime API.
await client . connect ( )
// Send a text message and trigger a response generation.
client . sendUserMessageContent ( [ { type : 'input_text' , text : 'How are you?' } ] )
// Wait for a completed response from the model.
// (`event` will be of type `RealtimeServerEvents.ResponseDoneEvent`)
const event = await client . realtime . waitForNext ( 'response.done' )Ver ejemplos para demostraciones más completas.
Consulte también la Guía Oficial de API de Operai RealTime y la referencia de API.
Para obtener más información sobre el uso, las herramientas y los eventos personalizados, consulte ReadMe de Openai. Tenga en cuenta que este paquete es 100% compatible con el paquete beta de OpenAI en términos de eventos oficiales y no oficiales. La única diferencia es que todos los eventos se escriben.
RealtimeClient toma un apiKey opcional que vale por defecto a process.env.OPENAI_API_KEY .
RealtimeClient toma una url opcional que se puede apuntar a un servidor de relé.
import { RealtimeClient } from 'openai-realtime-api'
// Create a browser client which points to a relay server.
const client = new RealtimeClient ( { url : RELAY_SERVER_URL } ) Alternativamente, puede usar apiKey con RealtimeClient en el navegador, pero también debe pasar dangerouslyAllowAPIKeyInBrowser: true .
import { RealtimeClient } from 'openai-realtime-api'
// Create a browser client which connects directly to the OpenAI realtime API
// with an unsafe, client-side API key.
const client = new RealtimeClient ( {
apiKey : process . env . OPENAI_API_KEY ,
dangerouslyAllowAPIKeyInBrowser : true
} ) Precaución
Recomendamos encarecidamente que no incluya su clave API en cualquier cliente (móvil o navegador). Puede ser útil para las pruebas locales, pero para la producción, debe usar un servidor de retransmisión.
import { RealtimeClient } from 'openai-realtime-api'
import { RealtimeRelay } from 'openai-realtime-api/node'
// Setting `relay: true` disables tool calls and directly modifying the session,
// since that will be the responsibility of the upstream client.
const client = new RealtimeClient ( { relay : true } )
const relay = new RealtimeRelay ( { client } )
relay . listen ( 8081 ) Tenga en cuenta que RealtimeRelay usa una ruta de importación diferente porque contiene código específico de Node.js.
Un ejemplo completo se incluye en ejemplos/nodo/relevo-server.ts.
Para ejecutar los ejemplos incluidos (requiere Node.js >= 18 ):
pnpm install.env con su OPENAI_API_KEY Puede establecer debug: true en el constructor RealtimeClient de estos ejemplos para imprimir el registro de eventos completo.
Demo de node.js simple usando el RealtimeClient que envía un mensaje de texto y espera una respuesta completa.
npx tsx examples/node/basic.ts Demo de Node.js simple usando el RealtimeClient que envía un mensaje de audio corto y espera una respuesta completa.
npx tsx examples/node/audio.ts Demo de nodo.js simple usando el RealtimeClient con un micrófono y un altavoz para simular una conversación completa y de ida y vuelta desde la terminal.
mic requiere Sox; En MacOS, puede ejecutar brew install soxnpx tsx examples/node/convo.ts Este ejemplo se ha importado de https://github.com/openai/openai-realtime-console (en commit 6ea4dba). El único cambio ha sido reemplazar @openai/realtime-api-beta con openai-realtime-api y arreglar algunos tipos.

Para ejecutar el ejemplo de la consola en tiempo real:
pnpm install
cd examples/openai-realtime-console
pnpm startMIT © Travis Fischer
Si le pareció interesante este proyecto, considere seguirme en Twitter.