该存储库包含一个参考客户端又称示例库,用于连接OpenAI的实时API。该库处于Beta,不应被视为最终实现。您可以使用它来轻松原型对话应用程序。
立即使用API播放的最简单方法是使用实时控制台,它使用参考客户端提供了功能齐全的API检查器,其中包含语音可视化示例等。
该库是在JavaScript和Typescript代码库中构建的,用于使用服务器端(Node.js)和浏览器(React,Vue)。在Beta时,要安装库,您需要直接从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?` } ] ) ; 您可以直接从浏览器中使用此客户端,例如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接口的原始图。我们建议您从RealtimeClient开始,但是更高级的用户可能更愿意更接近金属。
RealtimeClientconversation.interrupted realtime.event conversation.item.completed conversation.updated conversation.item.appendedRealtimeAPIclient.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()并将回调设置为第二个参数。回调将使用该工具的参数执行,结果将自动发送回模型。
// 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()这样的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' ) ; 使用RealtimeClient ,我们将事件开销从服务器事件减少到五个主要事件,这些事件对于您的应用程序控制流量最重要。这些事件不是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 ) ;
}
} ) ;您将需要确保拥有一个.env文件,其中OPENAI_API_KEY=设置以运行测试。从那里开始,运行测试套件很容易。
$ npm test要使用调试日志运行测试(将发送到Websocket发送并接收到的日志事件),请使用:
$ npm test -- --debug感谢您检查实时API。很想听听您的来信。特别感谢实时API团队使这一切成为可能。