Repositori ini berisi klien referensi alias perpustakaan sampel untuk menghubungkan ke API realtime OpenAI. Perpustakaan ini dalam beta dan tidak boleh diperlakukan sebagai implementasi akhir. Anda dapat menggunakannya untuk dengan mudah membuat prototipe aplikasi percakapan.
Cara termudah untuk segera bermain dengan API adalah dengan menggunakan konsol realtime , menggunakan klien referensi untuk memberikan inspektur API yang berfungsi penuh dengan contoh visualisasi suara dan banyak lagi.
Perpustakaan ini dibangun untuk digunakan baik sisi-server (Node.js) dan di browser (React, Vue), baik dalam javascript dan basis kode naskah. Saat dalam beta, untuk menginstal perpustakaan Anda harus npm install langsung dari repositori GitHub.
$ npm i openai/openai-realtime-api-beta --save import { RealtimeClient } from '@openai/realtime-api-beta' ;
const client = new RealtimeClient ( { apiKey : process . env . OPENAI_API_KEY } ) ;
// Can set parameters ahead of connecting, either separately or all at once
client . updateSession ( { instructions : 'You are a great, upbeat friend.' } ) ;
client . updateSession ( { voice : 'alloy' } ) ;
client . updateSession ( {
turn_detection : { type : 'none' } , // or 'server_vad'
input_audio_transcription : { model : 'whisper-1' } ,
} ) ;
// Set up event handling
client . on ( 'conversation.updated' , ( event ) => {
const { item , delta } = event ;
const items = client . conversation . getItems ( ) ;
/**
* item is the current item being updated
* delta can be null or populated
* you can fetch a full list of items at any time
*/
} ) ;
// Connect to Realtime API
await client . connect ( ) ;
// Send a item and triggers a generation
client . sendUserMessageContent ( [ { type : 'input_text' , text : `How are you?` } ] ) ; Anda dapat menggunakan klien ini langsung dari browser di misalnya aplikasi reaksi atau vue. Kami tidak merekomendasikan ini, kunci API Anda berisiko jika Anda terhubung ke OpenAi langsung dari browser. Untuk instantiate klien di lingkungan browser, gunakan:
import { RealtimeClient } from '@openai/realtime-api-beta' ;
const client = new RealtimeClient ( {
apiKey : process . env . OPENAI_API_KEY ,
dangerouslyAllowAPIKeyInBrowser : true ,
} ) ;Jika Anda menjalankan server relay Anda sendiri, misalnya dengan konsol realtime, Anda malah dapat terhubung ke URL server relay seperti demikian:
const client = new RealtimeClient ( { url : RELAY_SERVER_URL } ) ; Di perpustakaan ini, ada tiga primitif untuk berinteraksi dengan API realtime. Kami merekomendasikan untuk memulai dengan RealtimeClient , tetapi pengguna yang lebih maju mungkin lebih nyaman bekerja lebih dekat ke logam.
RealtimeClientrealtime.event conversation.updated khusus.updated, conversation.item.appended , conversation.item.completed conversation.interruptedRealtimeAPIclient.realtimeserver.{event_name} dan client.{event_name} , masing -masingRealtimeConversationclient.conversationKlien dilengkapi dengan beberapa utilitas dasar yang membuatnya mudah untuk membangun aplikasi realtime dengan cepat.
Mengirim pesan ke server dari pengguna itu mudah.
client . sendUserMessageContent ( [ { type : 'input_text' , text : `How are you?` } ] ) ;
// or (empty audio)
client . sendUserMessageContent ( [
{ type : 'input_audio' , audio : new Int16Array ( 0 ) } ,
] ) ; Untuk mengirim audio streaming, gunakan metode .appendInputAudio() . Jika Anda berada di turn_detection: 'disabled' , maka Anda perlu menggunakan .createResponse() untuk memberi tahu model untuk merespons.
// Send user audio, must be Int16Array or ArrayBuffer
// Default audio format is pcm16 with sample rate of 24,000 Hz
// This populates 1s of noise in 0.1s chunks
for ( let i = 0 ; i < 10 ; i ++ ) {
const data = new Int16Array ( 2400 ) ;
for ( let n = 0 ; n < 2400 ; n ++ ) {
const value = Math . floor ( ( Math . random ( ) * 2 - 1 ) * 0x8000 ) ;
data [ n ] = value ;
}
client . appendInputAudio ( data ) ;
}
// Pending audio is committed and model is asked to generate
client . createResponse ( ) ; Bekerja dengan alat itu mudah. Panggil saja .addTool() dan atur panggilan balik sebagai parameter kedua. Callback akan dieksekusi dengan parameter untuk alat, dan hasilnya akan secara otomatis dikirim kembali ke model.
// We can add tools as well, with callbacks specified
client . addTool (
{
name : 'get_weather' ,
description :
'Retrieves the weather for a given lat, lng coordinate pair. Specify a label for the location.' ,
parameters : {
type : 'object' ,
properties : {
lat : {
type : 'number' ,
description : 'Latitude' ,
} ,
lng : {
type : 'number' ,
description : 'Longitude' ,
} ,
location : {
type : 'string' ,
description : 'Name of the location' ,
} ,
} ,
required : [ 'lat' , 'lng' , 'location' ] ,
} ,
} ,
async ( { lat , lng , location } ) => {
const result = await fetch (
`https://api.open-meteo.com/v1/forecast?latitude= ${ lat } &longitude= ${ lng } ¤t=temperature_2m,wind_speed_10m` ,
) ;
const json = await result . json ( ) ;
return json ;
} ,
) ; Metode .addTool() secara otomatis menjalankan pawang alat dan memicu respons pada penyelesaian pawang. Terkadang Anda mungkin tidak menginginkan itu, misalnya: menggunakan alat untuk menghasilkan skema yang Anda gunakan untuk tujuan lain.
Dalam hal ini, kami dapat menggunakan item tools dengan updateSession . Dalam hal ini Anda harus menentukan type: 'function' , yang tidak diperlukan untuk .addTool() .
Catatan: Alat yang ditambahkan dengan .addTool() tidak akan ditimpa saat memperbarui sesi secara manual seperti ini, tetapi setiap perubahan updateSession() akan mengganti perubahan updateSession() . Alat yang ditambahkan melalui .addTool() tetap bertahan dan ditambahkan ke apa pun yang ditetapkan secara manual di sini.
client . updateSession ( {
tools : [
{
type : 'function' ,
name : 'get_weather' ,
description :
'Retrieves the weather for a given lat, lng coordinate pair. Specify a label for the location.' ,
parameters : {
type : 'object' ,
properties : {
lat : {
type : 'number' ,
description : 'Latitude' ,
} ,
lng : {
type : 'number' ,
description : 'Longitude' ,
} ,
location : {
type : 'string' ,
description : 'Name of the location' ,
} ,
} ,
required : [ 'lat' , 'lng' , 'location' ] ,
} ,
} ,
] ,
} ) ;Kemudian, untuk menangani panggilan fungsi ...
client . on ( 'conversation.updated' , ( { item , delta } ) => {
if ( item . type === 'function_call' ) {
// do something
if ( delta . arguments ) {
// populating the arguments
}
}
} ) ;
client . on ( 'conversation.item.completed' , ( { item } ) => {
if ( item . type === 'function_call' ) {
// your function call is complete, execute some custom code
}
} ) ; Anda mungkin ingin mengganggu model secara manual, terutama di turn_detection: 'disabled' . Untuk melakukan ini, kita dapat menggunakan:
// id is the id of the item currently being generated
// sampleCount is the number of audio samples that have been heard by the listener
client . cancelResponse ( id , sampleCount ) ; Metode ini akan menyebabkan model untuk segera menghentikan pembuatan, tetapi juga memotong item yang dimainkan dengan menghapus semua audio setelah sampleCount dan membersihkan respons teks. Dengan menggunakan metode ini, Anda dapat mengganggu model dan mencegahnya "mengingat" apa pun yang dihasilkannya di depan di mana keadaan pengguna berada.
Jika Anda memerlukan lebih banyak kontrol manual dan ingin mengirim acara klien khusus sesuai dengan referensi API Acara Klien Realtime, Anda dapat menggunakan client.realtime.send() So So:
// manually send a function call output
client . realtime . send ( 'conversation.item.create' , {
item : {
type : 'function_call_output' ,
call_id : 'my-call-id' ,
output : '{function_succeeded:true}' ,
} ,
} ) ;
client . realtime . send ( 'response.create' ) ; Dengan RealtimeClient kami telah mengurangi overhead acara dari acara server menjadi lima acara utama yang paling penting untuk aliran kontrol aplikasi Anda. Peristiwa ini bukan bagian dari spesifikasi API itu sendiri, tetapi membungkus logika untuk membuat pengembangan aplikasi lebih mudah.
// errors like connection failures
client . on ( 'error' , ( event ) => {
// do thing
} ) ;
// in VAD mode, the user starts speaking
// we can use this to stop audio playback of a previous response if necessary
client . on ( 'conversation.interrupted' , ( ) => {
/* do something */
} ) ;
// includes all changes to conversations
// delta may be populated
client . on ( 'conversation.updated' , ( { item , delta } ) => {
// get all items, e.g. if you need to update a chat window
const items = client . conversation . getItems ( ) ;
switch ( item . type ) {
case 'message' :
// system, user, or assistant message (item.role)
break ;
case 'function_call' :
// always a function call from the model
break ;
case 'function_call_output' :
// always a response from the user / application
break ;
}
if ( delta ) {
// Only one of the following will be populated for any given event
// delta.audio = Int16Array, audio added
// delta.transcript = string, transcript added
// delta.arguments = string, function arguments added
}
} ) ;
// only triggered after item added to conversation
client . on ( 'conversation.item.appended' , ( { item } ) => {
/* item status can be 'in_progress' or 'completed' */
} ) ;
// only triggered after item completed in conversation
// will always be triggered after conversation.item.appended
client . on ( 'conversation.item.completed' , ( { item } ) => {
/* item status will always be 'completed' */
} ) ; Jika Anda ingin lebih banyak kontrol atas pengembangan aplikasi Anda, Anda dapat menggunakan acara realtime.event dan memilih hanya untuk menanggapi acara server . Dokumentasi lengkap untuk acara ini tersedia di Realtime Server Events API Referensi.
// all events, can use for logging, debugging, or manual event handling
client . on ( 'realtime.event' , ( { time , source , event } ) => {
// time is an ISO timestamp
// source is 'client' or 'server'
// event is the raw event payload (json)
if ( source === 'server' ) {
doSomething ( event ) ;
}
} ) ; Anda perlu memastikan Anda memiliki file .env dengan OPENAI_API_KEY= diatur untuk menjalankan tes. Dari sana, menjalankan test suite itu mudah.
$ npm testUntuk menjalankan tes dengan log debug (akan mencatat acara yang dikirim ke dan diterima dari WebSocket), gunakan:
$ npm test -- --debugTerima kasih telah memeriksa API Realtime. Ingin sekali mendengar dari Anda. Terima kasih khusus kepada tim API Realtime yang telah memungkinkan ini.