Skip to content

Commit de54193

Browse files
Python: Introducing Realtime Clients for OpenAI and Azure OpenAI (microsoft#10127)
### Motivation and Context <!-- Thank you for your contribution to the semantic-kernel repo! Please help reviewers and future users, providing the following information: 1. Why is this change required? 2. What problem does it solve? 3. What scenario does it contribute to? 4. If it fixes an open issue, please link to the issue here. --> Implements the OpenAI Realtime API with Semantic Kernel ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds a RealtimeClientBase Adds RealtimeEvents Adds OpenAI and Azure Realtime clients Closes: microsoft#10108 ### Contribution Checklist <!-- Before submitting this PR, please make sure: --> - [x] The code builds clean without any errors or warnings - [x] The PR follows the [SK Contribution Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md) and the [pre-submission formatting script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts) raises no violations - [x] All unit tests pass, and I have added new tests where possible - [x] I didn't break anyone 😄 --------- Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
1 parent 4eb4493 commit de54193

42 files changed

Lines changed: 3772 additions & 79 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎python/.cspell.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
"logprobs",
4848
"mistralai",
4949
"mongocluster",
50+
"nd",
5051
"ndarray",
5152
"nopep",
5253
"NOSQL",
@@ -73,4 +74,4 @@
7374
"vertexai",
7475
"Weaviate"
7576
]
76-
}
77+
}

‎python/.vscode/launch.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"request": "launch",
1111
"program": "${file}",
1212
"console": "integratedTerminal",
13-
"justMyCode": true
13+
"justMyCode": false
1414
},
1515
{
1616
"name": "Python FastAPI app with Dapr",

‎python/pyproject.toml‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,10 @@ dapr = [
128128
"dapr-ext-fastapi>=1.14.0",
129129
"flask-dapr>=1.14.0"
130130
]
131+
realtime = [
132+
"websockets >= 13, < 15",
133+
"aiortc>=1.9.0",
134+
]
131135

132136
[tool.uv]
133137
prerelease = "if-necessary-or-explicit"
@@ -225,5 +229,3 @@ name = "semantic_kernel"
225229
[build-system]
226230
requires = ["flit-core >= 3.9,<4.0"]
227231
build-backend = "flit_core.buildapi"
228-
229-
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Realtime Multi-modal API Samples
2+
3+
These samples are more complex then most because of the nature of these API's. They are designed to be run in real-time and require a microphone and speaker to be connected to your computer.
4+
5+
To run these samples, you will need to have the following setup:
6+
7+
- Environment variables for OpenAI (websocket or WebRTC), with your key and OPENAI_REALTIME_MODEL_ID set.
8+
- Environment variables for Azure (websocket only), set with your endpoint, optionally a key and AZURE_OPENAI_REALTIME_DEPLOYMENT_NAME set. The API version needs to be at least `2024-10-01-preview`.
9+
- To run the sample with a simple version of a class that handles the incoming and outgoing sound you need to install the following packages in your environment:
10+
- semantic-kernel[realtime]
11+
- pyaudio
12+
- sounddevice
13+
- pydub
14+
e.g. pip install pyaudio sounddevice pydub semantic_kernel[realtime]
15+
16+
The samples all run as python scripts, that can either be started directly or through your IDE.
17+
18+
All demos have a similar output, where the instructions are printed, each new *response item* from the API is put into a new `Mosscap (transcript):` line. The nature of these api's is such that the transcript arrives before the spoken audio, so if you interrupt the audio the transcript will not match the audio.
19+
20+
The realtime api's work by sending event from the server to you and sending events back to the server, this is fully asynchronous. The samples show you can listen to the events being sent by the server and some are handled by the code in the samples, others are not. For instance one could add a clause in the match case in the receive loop that logs the usage that is part of the `response.done` event.
21+
22+
For more info on the events, go to our documentation, as well as the documentation of [OpenAI](https://platform.openai.com/docs/guides/realtime) and [Azure](https://learn.microsoft.com/en-us/azure/ai-services/openai/realtime-audio-quickstart?tabs=keyless%2Cmacos&pivots=programming-language-python).
23+
24+
## Simple chat samples
25+
26+
### [Simple chat with realtime websocket](./simple_realtime_chat_websocket.py)
27+
28+
This sample uses the websocket api with Azure OpenAI to run a simple interaction based on voice. If you want to use this sample with OpenAI, just change AzureRealtimeWebsocket into OpenAIRealtimeWebsocket.
29+
30+
### [Simple chat with realtime WebRTC](./simple_realtime_chat_webrtc.py)
31+
32+
This sample uses the WebRTC api with OpenAI to run a simple interaction based on voice. Because of the way the WebRTC protocol works this needs a different player and recorder than the websocket version.
33+
34+
## Function calling samples
35+
36+
The following two samples use function calling with the following functions:
37+
38+
- get_weather: This function will return the weather for a given city, it is randomly generated and not based on any real data.
39+
- get_time: This function will return the current time and date.
40+
- goodbye: This function will end the conversation.
41+
42+
A line is logged whenever one of these functions is called.
43+
44+
### [Chat with function calling Websocket](./realtime_chat_with_function_calling_websocket.py)
45+
46+
This sample uses the websocket api with Azure OpenAI to run the interaction with the voice model, but now with function calling.
47+
48+
### [Chat with function calling WebRTC](./realtime_chat_with_function_calling_webrtc.py)
49+
50+
This sample uses the WebRTC api with OpenAI to run the interaction with the voice model, but now with function calling.
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
3+
import asyncio
4+
import logging
5+
from datetime import datetime
6+
from random import randint
7+
8+
from samples.concepts.realtime.utils import AudioPlayerWebRTC, AudioRecorderWebRTC, check_audio_devices
9+
from semantic_kernel import Kernel
10+
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
11+
from semantic_kernel.connectors.ai.open_ai import (
12+
ListenEvents,
13+
OpenAIRealtimeExecutionSettings,
14+
OpenAIRealtimeWebRTC,
15+
TurnDetection,
16+
)
17+
from semantic_kernel.contents import ChatHistory
18+
from semantic_kernel.contents.realtime_events import RealtimeTextEvent
19+
from semantic_kernel.functions import kernel_function
20+
21+
logging.basicConfig(level=logging.WARNING)
22+
utils_log = logging.getLogger("samples.concepts.realtime.utils")
23+
utils_log.setLevel(logging.INFO)
24+
logger = logging.getLogger(__name__)
25+
logger.setLevel(logging.INFO)
26+
27+
"""
28+
This simple sample demonstrates how to use the OpenAI Realtime API to create
29+
a chat bot that can listen and respond directly through audio.
30+
It requires installing:
31+
- semantic-kernel[realtime]
32+
- pyaudio
33+
- sounddevice
34+
- pydub
35+
e.g. pip install pyaudio sounddevice pydub semantic_kernel[realtime]
36+
37+
For more details of the exact setup, see the README.md in the realtime folder.
38+
"""
39+
40+
# The characterics of your speaker and microphone are a big factor in a smooth conversation
41+
# so you may need to try out different devices for each.
42+
# you can also play around with the turn_detection settings to get the best results.
43+
# It has device id's set in the AudioRecorderStream and AudioPlayerAsync classes,
44+
# so you may need to adjust these for your system.
45+
# you can disable the check for available devices by commenting the line below
46+
check_audio_devices()
47+
48+
49+
@kernel_function
50+
def get_weather(location: str) -> str:
51+
"""Get the weather for a location."""
52+
weather_conditions = ("sunny", "hot", "cloudy", "raining", "freezing", "snowing")
53+
weather = weather_conditions[randint(0, len(weather_conditions) - 1)] # nosec
54+
logger.info(f"@ Getting weather for {location}: {weather}")
55+
return f"The weather in {location} is {weather}."
56+
57+
58+
@kernel_function
59+
def get_date_time() -> str:
60+
"""Get the current date and time."""
61+
logger.info("@ Getting current datetime")
62+
return f"The current date and time is {datetime.now().isoformat()}."
63+
64+
65+
@kernel_function
66+
def goodbye():
67+
"""When the user is done, say goodbye and then call this function."""
68+
logger.info("@ Goodbye has been called!")
69+
raise KeyboardInterrupt
70+
71+
72+
async def main() -> None:
73+
print_transcript = True
74+
# create the Kernel and add a simple function for function calling.
75+
kernel = Kernel()
76+
kernel.add_functions(plugin_name="helpers", functions=[goodbye, get_weather, get_date_time])
77+
78+
# create the audio player and audio track
79+
# both take a device_id parameter, which is the index of the device to use, if None the default device is used
80+
audio_player = AudioPlayerWebRTC()
81+
# create the realtime client and optionally add the audio output function, this is optional
82+
# and can also be passed in the receive method
83+
realtime_client = OpenAIRealtimeWebRTC(audio_track=AudioRecorderWebRTC())
84+
85+
# Create the settings for the session
86+
# The realtime api, does not use a system message, but takes instructions as a parameter for a session
87+
# Another important setting is to tune the server_vad turn detection
88+
# if this is turned off (by setting turn_detection=None), you will have to send
89+
# the "input_audio_buffer.commit" and "response.create" event to the realtime api
90+
# to signal the end of the user's turn and start the response.
91+
# manual VAD is not part of this sample
92+
# for more info: https://platform.openai.com/docs/api-reference/realtime-sessions/create#realtime-sessions-create-turn_detection
93+
settings = OpenAIRealtimeExecutionSettings(
94+
instructions="""
95+
You are a chat bot. Your name is Mosscap and
96+
you have one goal: figure out what people need.
97+
Your full name, should you need to know it, is
98+
Splendid Speckled Mosscap. You communicate
99+
effectively, but you tend to answer with long
100+
flowery prose.
101+
""",
102+
voice="alloy",
103+
turn_detection=TurnDetection(type="server_vad", create_response=True, silence_duration_ms=800, threshold=0.8),
104+
function_choice_behavior=FunctionChoiceBehavior.Auto(),
105+
)
106+
# and we can add a chat history to conversation after starting it
107+
chat_history = ChatHistory()
108+
chat_history.add_user_message("Hi there, who are you?")
109+
chat_history.add_assistant_message("I am Mosscap, a chat bot. I'm trying to figure out what people need.")
110+
111+
# the context manager calls the create_session method on the client and starts listening to the audio stream
112+
async with (
113+
audio_player,
114+
realtime_client(
115+
settings=settings,
116+
chat_history=chat_history,
117+
kernel=kernel,
118+
create_response=True,
119+
),
120+
):
121+
async for event in realtime_client.receive(audio_output_callback=audio_player.client_callback):
122+
match event:
123+
case RealtimeTextEvent():
124+
if print_transcript:
125+
print(event.text.text, end="")
126+
case _:
127+
# OpenAI Specific events
128+
match event.service_type:
129+
case ListenEvents.RESPONSE_CREATED:
130+
if print_transcript:
131+
print("\nMosscap (transcript): ", end="")
132+
case ListenEvents.ERROR:
133+
logger.error(event.service_event)
134+
135+
136+
if __name__ == "__main__":
137+
print(
138+
"Instructions: The model will start speaking immediately,"
139+
"this can be turned off by removing `create_response=True` above."
140+
"The model will detect when you stop and automatically generate a response. "
141+
"Press ctrl + c to stop the program."
142+
)
143+
asyncio.run(main())
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
3+
import asyncio
4+
import logging
5+
from datetime import datetime
6+
from random import randint
7+
8+
from samples.concepts.realtime.utils import AudioPlayerWebsocket, AudioRecorderWebsocket
9+
from semantic_kernel import Kernel
10+
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
11+
from semantic_kernel.connectors.ai.open_ai import (
12+
AzureRealtimeExecutionSettings,
13+
AzureRealtimeWebsocket,
14+
ListenEvents,
15+
TurnDetection,
16+
)
17+
from semantic_kernel.contents import ChatHistory
18+
from semantic_kernel.contents.realtime_events import RealtimeTextEvent
19+
from semantic_kernel.functions import kernel_function
20+
21+
logger = logging.getLogger(__name__)
22+
logger.setLevel(logging.DEBUG)
23+
24+
"""
25+
This simple sample demonstrates how to use the OpenAI Realtime API to create
26+
a chat bot that can listen and respond directly through audio.
27+
It requires installing:
28+
- semantic-kernel[realtime]
29+
- pyaudio
30+
- sounddevice
31+
- pydub
32+
e.g. pip install pyaudio sounddevice pydub semantic_kernel[realtime]
33+
34+
For more details of the exact setup, see the README.md in the realtime folder.
35+
"""
36+
37+
38+
@kernel_function
39+
def get_weather(location: str) -> str:
40+
"""Get the weather for a location."""
41+
weather_conditions = ("sunny", "hot", "cloudy", "raining", "freezing", "snowing")
42+
weather = weather_conditions[randint(0, len(weather_conditions) - 1)] # nosec
43+
logger.info(f"@ Getting weather for {location}: {weather}")
44+
return f"The weather in {location} is {weather}."
45+
46+
47+
@kernel_function
48+
def get_date_time() -> str:
49+
"""Get the current date and time."""
50+
logger.info("@ Getting current datetime")
51+
return f"The current date and time is {datetime.now().isoformat()}."
52+
53+
54+
@kernel_function
55+
def goodbye():
56+
"""When the user is done, say goodbye and then call this function."""
57+
logger.info("@ Goodbye has been called!")
58+
raise KeyboardInterrupt
59+
60+
61+
async def main() -> None:
62+
print_transcript = True
63+
# create the Kernel and add a simple function for function calling.
64+
kernel = Kernel()
65+
kernel.add_functions(plugin_name="helpers", functions=[goodbye, get_weather, get_date_time])
66+
67+
# create the realtime client, in this the Azure Websocket client, there are also OpenAI Websocket and WebRTC clients
68+
# See 02b-chat_with_function_calling_webrtc.py for an example of the WebRTC client
69+
realtime_client = AzureRealtimeWebsocket()
70+
# create the audio player and audio track
71+
# both take a device_id parameter, which is the index of the device to use, if None the default device is used
72+
audio_player = AudioPlayerWebsocket()
73+
audio_recorder = AudioRecorderWebsocket(realtime_client=realtime_client)
74+
75+
# Create the settings for the session
76+
# The realtime api, does not use a system message, but takes instructions as a parameter for a session
77+
# Another important setting is to tune the server_vad turn detection
78+
# if this is turned off (by setting turn_detection=None), you will have to send
79+
# the "input_audio_buffer.commit" and "response.create" event to the realtime api
80+
# to signal the end of the user's turn and start the response.
81+
# manual VAD is not part of this sample
82+
# for more info: https://platform.openai.com/docs/api-reference/realtime-sessions/create#realtime-sessions-create-turn_detection
83+
settings = AzureRealtimeExecutionSettings(
84+
instructions="""
85+
You are a chat bot. Your name is Mosscap and
86+
you have one goal: figure out what people need.
87+
Your full name, should you need to know it, is
88+
Splendid Speckled Mosscap. You communicate
89+
effectively, but you tend to answer with long
90+
flowery prose.
91+
""",
92+
# see https://platform.openai.com/docs/api-reference/realtime-sessions/create#realtime-sessions-create-voice for the full list of voices # noqa: E501
93+
voice="alloy",
94+
turn_detection=TurnDetection(type="server_vad", create_response=True, silence_duration_ms=800, threshold=0.8),
95+
function_choice_behavior=FunctionChoiceBehavior.Auto(),
96+
)
97+
# and we can add a chat history to conversation to seed the conversation
98+
chat_history = ChatHistory()
99+
chat_history.add_user_message("Hi there, I'm based in Amsterdam.")
100+
chat_history.add_assistant_message(
101+
"I am Mosscap, a chat bot. I'm trying to figure out what people need, "
102+
"I can tell you what the weather is or the time."
103+
)
104+
105+
# the context manager calls the create_session method on the client and starts listening to the audio stream
106+
async with (
107+
audio_player,
108+
audio_recorder,
109+
realtime_client(
110+
settings=settings,
111+
chat_history=chat_history,
112+
kernel=kernel,
113+
create_response=True,
114+
),
115+
):
116+
# the audio_output_callback can be added here or in the client constructor
117+
# using this gives the smoothest experience
118+
async for event in realtime_client.receive(audio_output_callback=audio_player.client_callback):
119+
match event:
120+
case RealtimeTextEvent():
121+
if print_transcript:
122+
print(event.text.text, end="")
123+
case _:
124+
# OpenAI Specific events
125+
match event.service_type:
126+
case ListenEvents.RESPONSE_CREATED:
127+
if print_transcript:
128+
print("\nMosscap (transcript): ", end="")
129+
case ListenEvents.ERROR:
130+
print(event.service_event)
131+
logger.error(event.service_event)
132+
133+
134+
if __name__ == "__main__":
135+
print(
136+
"Instructions: The model will start speaking immediately,"
137+
"this can be turned off by removing `create_response=True` above."
138+
"The model will detect when you stop and automatically generate a response. "
139+
"Press ctrl + c to stop the program."
140+
)
141+
asyncio.run(main())

0 commit comments

Comments
 (0)