OpenAI Realtime API Python Code: Understanding the Low-Level Sample Code for Azure’s Realtime Audio Python Code

OpenAI Realtime API Python Code: Understanding the Low-Level Sample Code for Azure’s Realtime Audio Python Code

Introduction

The "gpt-4o-realtime-preview" has been launched. In addition to textual content and audio enter/output, it additionally permits customized perform calling through perform calling.

As of October 2, 2024, there are points resembling 403 errors, and it appears the API shouldn’t be usable. This article shall be up to date as soon as it turns into accessible.

OpenAI has offered a JavaScript code pattern on its web site. Additionally, Azure has additionally revealed a Python code pattern on GitHub.

In this text, we’ll analyze Azure’s pattern code, "low_level_sample.py," to know the way it works.

Libraries

The required libraries are as follows:

python-dotenv  
soundfile  
numpy  
scipy  

Code Explanation

foremost Function

In the foremost perform, it first hundreds the dotenv file to retrieve the API key and endpoint:

load_dotenv()  

Next, it checks the arguments. This file is executed utilizing the command python low_level_sample.py <audio file> <azure|openai>. You can select both OpenAI or Azure OpenAI because the API:

if len(sys.argv) < 2:  
    print("Usage: python pattern.py <audio file> <azure|openai>")  
    print("If second argument shouldn't be offered, it is going to default to azure")  
    sys.exit(1)  

Then, it makes use of asyncio to run the method asynchronously:

file_path = sys.argv[1]  
if len(sys.argv) == 3 and sys.argv[2] == "openai":  
    asyncio.run(with_openai(file_path))  
else:  
    asyncio.run(with_azure_openai(file_path))  

Next, let us take a look at the with_openai perform.

with_openai Function

The API key and mannequin title are retrieved from surroundings variables.

Then, an occasion of RTLowLevelConsumer is created:

async with RTLowLevelConsumer(key_credential=AzureKeyCredential(key), mannequin=mannequin) as shopper:  

Next, a message is added:

await shopper.ship(  
    SessionUpdateMessage(session=SessionUpdateParams(turn_detection=ServerVAD(sort="server_vad")))  
)  

Here, we specify "server_vad" for Voice Activity Detection (VAD). Although "server_vad" is the one choice at the moment accessible, you’ll be able to set choices like detection threshold and allowable silence period:

class ServerVAD(BaseModel):  
    sort: Literal["server_vad"] = "server_vad"  
    threshold: Optional[Annotated[float, Field(strict=True, ge=0.0, le=1.0)]] = None  
    prefix_padding_ms: Optional[int] = None  
    silence_duration_ms: Optional[int] = None  

The message is then transformed to JSON earlier than being despatched:

async def ship(self, message: UserMessageType):  
    message_json = message.model_dump_json()  
    await self.ws.send_str(message_json)  

The model_dump_json methodology is outlined in Pydantic.BaseModel and converts the mannequin right into a JSON string. The ensuing JSON seems to be like this:

{ "event_id": null, "sort": "session.replace", "session": { "mannequin": null, "modalities": null, "voice": null, "directions": null, "input_audio_format": null, "output_audio_format": null, "input_audio_transcription": null, "turn_detection": { "sort": "server_vad", "threshold": null, "prefix_padding_ms": null, "silence_duration_ms": null }, "instruments": null, "tool_choice": null, "temperature": null, "max_response_output_tokens": null } } 

This is distributed to session.replace to configure the session. You can specify system directions within the "directions" area. For instance, to set a system immediate, you’ll be able to modify the code like this:

await shopper.ship(  
    SessionUpdateMessage(  
        session=SessionUpdateParams(  
            directions="<your system directions>",  
            turn_detection=ServerVAD(sort="server_vad")  
        )  
    )  
)  

Next, asyncio.collect is used to run each send_audio and receive_messages features concurrently:

await asyncio.collect(send_audio(shopper, audio_file_path), receive_messages(shopper))  

In the send_audio perform, the audio file is learn utilizing soundfile, base64 encoded, after which despatched as InputAudioBufferAppendMessage:

...  

audio_data, original_sample_rate = sf.learn(audio_file_path, dtype="int16", **extra_params)  

...  

audio_bytes = audio_data.tobytes()  

for i in vary(0, len(audio_bytes), bytes_per_chunk):  
    chunk = audio_bytes[i : i + bytes_per_chunk]  
    base64_audio = base64.b64encode(chunk).decode("utf-8")  
    await shopper.ship(InputAudioBufferAppendMessage(audio=base64_audio))  

The audio knowledge is distributed to input_audio_buffer.append.

In the receive_messages perform, responses primarily based on the processed audio knowledge from the send_audio perform are acquired.

The session is established at "/openai/realtime", and messages are acquired asynchronously:

message = await shopper.recv()  

The case construction handles totally different message sorts. The message sorts are defined right here. Below are a few of the essential ones:

input_audio_buffer.dedicated

When the server-side Voice Activity Detection (VAD) detects that the consumer’s speech has ended, the input_audio_buffer.dedicated message is distributed.

input_audio_buffer.speech_started

When the AI response begins, input_audio_buffer.speech_started is distributed. You can retrieve the beginning time utilizing message.audio_start_ms.

input_audio_buffer.speech_stopped

When the AI response finishes, input_audio_buffer.speech_stopped is distributed. You can retrieve the tip time utilizing message.audio_end_ms.

By monitoring speech occasions, it’s potential to set off spontaneous responses. For occasion, utilizing response.create, the AI can generate a response with out ready for additional consumer enter when a interval of silence is detected.

dialog.merchandise.created

This can be utilized to handle dialog historical past.

response.created

When a response is created, response.created is distributed. For streaming processing, you should use response.textual content.delta and response.audio.delta.

The low_level_sample.py script doesn’t deal with audio output. To output audio, it is advisable to retrieve the audio knowledge and use instruments like pyaudio for playback. Here’s how you can deal with the audio knowledge:

audio_bytes = base64.b64decode(chunk.knowledge)
audio_data.prolong(audio_bytes)
if audio_data is not null:
    print(prefix, f"Audio acquired with size: {len(audio_data)}")
    with open(os.path.be part of(out_dir, f"{merchandise.id}.wav"), "wb") as out:
        audio_array = np.frombuffer(audio_data, dtype=np.int16)

I hope this text helps along with your growth.

If you discovered it helpful, I might recognize a constructive ranking.

Thank you!

HI-FI News

through DEV Community https://dev.to

October 2, 2024 at 12:33PM