このリポジトリには、OpenAIのリアルタイムAPIに接続するためのリファレンスクライアント別名サンプルライブラリが含まれています。このライブラリはベータ版であり、最終的な実装として扱われるべきではありません。これを使用して、会話アプリを簡単にプロトタイプすることができます。
APIですぐに再生する最も簡単な方法は、リアルタイムコンソールを使用することです。参照クライアントを使用して、音声視覚化などの例を備えた完全に機能するAPIインスペクターを提供します。
このライブラリは、JavaScriptとTypeScriptコードベースの両方で、サーバー側(node.js)とブラウザー(React、Vue)の両方で使用されるように構築されています。ベータ版では、ライブラリをインストールするには、githubリポジトリから直接npm install必要があります。
$ 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?` } ] ) ; このクライアントは、EG ReactまたはVueアプリのブラウザから直接使用できます。これをお勧めしません。ブラウザから直接Openaiに接続すると、APIキーが危険にさらされています。ブラウザ環境でクライアントをインスタンス化するには、以下を使用してください。
import { RealtimeClient } from '@openai/realtime-api-beta' ;
const client = new RealtimeClient ( {
apiKey : process . env . OPENAI_API_KEY ,
dangerouslyAllowAPIKeyInBrowser : true ,
} ) ;リアルタイムコンソールを使用して、独自のリレーサーバーを実行している場合は、代わりにリレーサーバーURLに接続できます。
const client = new RealtimeClient ( { url : RELAY_SERVER_URL } ) ;このライブラリには、リアルタイムAPIとのインターフェースのための3つのプリミティブがあります。 RealtimeClientから始めることをお勧めしますが、より高度なユーザーは金属に近づき、より快適に動作することができます。
RealtimeClientconversation.updated 、 conversation.item.appended 、 conversation.item.completed 、 conversation.interrupted and realtime.eventイベントを持っています。RealtimeAPIclient.realtimeとして存在しますserver.{event_name}およびclient.{event_name}RealtimeConversationclient.conversationとして存在しますクライアントには、リアルタイムアプリをすばやく簡単に作成できる基本的なユーティリティがパッケージ化されています。
ユーザーからサーバーにメッセージを送信するのは簡単です。
client . sendUserMessageContent ( [ { type : 'input_text' , text : `How are you?` } ] ) ;
// or (empty audio)
client . sendUserMessageContent ( [
{ type : 'input_audio' , audio : new Int16Array ( 0 ) } ,
] ) ; ストリーミングオーディオを送信するには、 .appendInputAudio()メソッドを使用します。 turn_detection: 'disabled'モードの場合、 .createResponse()を使用してモデルに応答するように指示する必要があります。
// 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 ( ) ; ツールを使用するのは簡単です。 .addTool()を呼び出し、2番目のパラメーターとしてコールバックを設定します。コールバックはツールのパラメーターで実行され、結果は自動的にモデルに送信されます。
// 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 ;
} ,
) ;.addTool()メソッドは、ツールハンドラーを自動的に実行し、ハンドラーの完了に関する応答をトリガーします。たとえば、それを望んでいない場合があります。ツールを使用して、他の目的で使用するスキーマを生成します。
この場合、 updateSessionのtoolsアイテムを使用できます。この場合type: 'function' .addTool()には必要ありません。
注: .addTool()で追加されたツールは、このように手動でセッションを更新するときにオーバーライドされませんが、すべてのupdateSession()変更は、以前のupdateSession()の変更をオーバーライドします。 .addTool()を介して追加されたツールは、ここで手動で設定されたものに固執し、追加されます。
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' ] ,
} ,
} ,
] ,
} ) ;次に、関数呼び出しを処理するために...
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
}
} ) ; 特にturn_detection: 'disabled'モード。これを行うには、使用できます。
// 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 ) ;この方法により、モデルはすぐに生成を停止しますが、 sampleCount後にすべてのオーディオを削除してテキスト応答をクリアすることにより、再生されるアイテムを切り捨てます。この方法を使用することにより、モデルを中断し、ユーザーの状態がどこにあるかよりも先の生成されたものを「覚える」ことを防ぐことができます。
より手動制御が必要で、リアルタイムクライアントイベントAPIリファレンスに従ってカスタムクライアントイベントを送信する場合は、 client.realtime.send()を使用できます。
// 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' ) ; RealtimeClientを使用すると、イベントの間接費をサーバーイベントから5つのメインイベントに縮小し、アプリケーションコントロールフローにとって最も重要です。これらのイベントは、API仕様自体の一部ではなく、ロジックをラップしてアプリケーション開発を容易にします。
// 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' */
} ) ;アプリケーション開発をさらに制御したい場合は、 realtime.eventイベントを使用して、サーバーイベントに応答するためだけに選択できます。これらのイベントの完全なドキュメントは、リアルタイムサーバーイベントAPIリファレンスで入手できます。
// 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 ) ;
}
} ) ;テストを実行するために、 OPENAI_API_KEY=設定された.envファイルがあることを確認する必要があります。そこから、テストスイートを実行するのは簡単です。
$ npm testデバッグログでテストを実行するには(WebSocketから送信および受信したイベントをログにします)、使用します。
$ npm test -- --debugリアルタイムAPIをチェックしていただきありがとうございます。あなたから聞いてみたいです。これをすべて可能にしてくれたリアルタイムAPIチームに感謝します。