Compartir a través de


APIs multimodales en tiempo real

La primera integración de API en tiempo real para kernel semántico se ha agregado, actualmente solo está disponible en Python y se considera experimental. Esto se debe a que los servicios subyacentes todavía se están desarrollando y están sujetos a cambios y es posible que tengamos que realizar cambios importantes en la API en kernel semántico, ya que aprendemos de los clientes a usar esto y a medida que agregamos otros proveedores de estos tipos de modelos y API.

Abstracción del cliente en tiempo real

Para admitir diferentes API en tiempo real de distintos proveedores, mediante protocolos diferentes, se ha agregado una nueva abstracción de cliente al kernel. Este cliente se usa para conectarse al servicio en tiempo real y enviar y recibir mensajes. El cliente es responsable de controlar la conexión al servicio, enviar mensajes y recibir mensajes. El cliente también es responsable de controlar los errores que se producen durante la conexión o el proceso de envío o recepción de mensajes. Teniendo en cuenta la forma en que funcionan estos modelos, se pueden ver más como agentes que como finalizaciones de chat convencionales; y por eso también aceptan instrucciones, en vez de depender únicamente de un mensaje del sistema, gestionan su propio estado interno y pueden ser invocados para realizar tareas en nuestro nombre.

API en tiempo real

Cualquier cliente en tiempo real implementa los métodos siguientes:

Método Descripción
create_session Crea una nueva sesión
update_session Actualiza una sesión existente
delete_session Elimina una sesión existente.
receive Se trata de un método de generador asincrónico que escucha los mensajes del servicio y los produce a medida que llegan.
send Envía un mensaje al servicio

Implementaciones de Python

La versión de Python del kernel semántico admite actualmente los siguientes clientes en tiempo real:

Cliente Protocolo Modalidades Función de llamadas habilitada Descripción
OpenAI WebSocket Texto y audio La API de OpenAI Realtime es una API basada en websocket que permite enviar y recibir mensajes en tiempo real, este conector usa el paquete de Python de OpenAI para conectarse y recibir y enviar mensajes.
OpenAI WebRTC Texto y audio La API de Tiempo real de OpenAI es una API basada en WebRTC que permite enviar y recibir mensajes en tiempo real, necesita una pista de audio compatible con webRTC en tiempo de creación de la sesión.
Azur WebSocket Texto y audio La API de Azure Realtime es una API basada en websocket que permite enviar y recibir mensajes en tiempo real, lo que usa el mismo paquete que el conector websocket de OpenAI.
Azur WebRTC Texto y audio La API de Azure Realtime es una API basada en WebRTC que permite enviar y recibir mensajes en tiempo real, lo que usa el mismo paquete que el conector WebRTC de OpenAI.

Empezar

Para empezar a trabajar con la API en tiempo real, debe instalar el semantic-kernel paquete.

pip install semantic-kernel

En función de cómo quiera controlar el audio, es posible que necesite paquetes adicionales para interactuar con altavoces y micrófonos, como pyaudio o sounddevice.

Clientes de Websocket

A continuación, puede crear un kernel y agregarle el cliente en tiempo real; esto muestra cómo hacerlo con una conexión AzureRealtimeWebsocket, puede reemplazar AzureRealtimeWebsocket por OpenAIRealtimeWebsocket sin realizar ningún cambio adicional.

from semantic_kernel.connectors.ai.open_ai import (
    AzureRealtimeWebsocket,
    AzureRealtimeExecutionSettings,
    ListenEvents,
)
from semantic_kernel.contents import RealtimeAudioEvent, RealtimeTextEvent

# this will use environment variables to get the api key, endpoint, api version and deployment name.
realtime_client = AzureRealtimeWebsocket()
settings = AzureRealtimeExecutionSettings(voice='alloy')
async with realtime_client(settings=settings, create_response=True):
    async for event in realtime_client.receive():
        match event:
            # receiving a piece of audio (and send it to a undefined audio player)
            case RealtimeAudioEvent():
                await audio_player.add_audio(event.audio)
            # receiving a piece of audio transcript
            case RealtimeTextEvent():
                # Semantic Kernel parses the transcript to a TextContent object captured in a RealtimeTextEvent
                print(event.text.text, end="")
            case _:
                # OpenAI Specific events
                if event.service_type == ListenEvents.SESSION_UPDATED:
                    print("Session updated")
                if event.service_type == ListenEvents.RESPONSE_CREATED:
                    print("\nMosscap (transcript): ", end="")

Hay dos aspectos importantes que hay que tener en cuenta, lo primero es que el realtime_client es un administrador de contexto asincrónico, lo que significa que puede usarlo en una función asincrónica y usar async with para crear la sesión. El segundo es que el método receive es un generador asincrónico, lo que significa que puede usarlo en un bucle for para recibir mensajes a medida que llegan.

Cliente WebRTC

La configuración de una conexión WebRTC es un poco más compleja y, por tanto, necesitamos un parámetro adicional al crear el cliente. Este parámetro, audio_track debe ser un objeto que implementa el protocolo MediaStreamTrack del paquete de aiortc, lo que también se muestra en los ejemplos que están vinculados a continuación.

Para crear un cliente que use WebRTC, haga lo siguiente:

from semantic_kernel.connectors.ai.open_ai import (
    ListenEvents,
    OpenAIRealtimeExecutionSettings,
    OpenAIRealtimeWebRTC,
)
from aiortc.mediastreams import MediaStreamTrack

class AudioRecorderWebRTC(MediaStreamTrack):
    # implement the MediaStreamTrack methods.

realtime_client = OpenAIRealtimeWebRTC(audio_track=AudioRecorderWebRTC())
# Create the settings for the session
settings = OpenAIRealtimeExecutionSettings(
    instructions="""
You are a chat bot. Your name is Mosscap and
you have one goal: figure out what people need.
Your full name, should you need to know it, is
Splendid Speckled Mosscap. You communicate
effectively, but you tend to answer with long
flowery prose.
""",
    voice="shimmer",
)
audio_player = AudioPlayer
async with realtime_client(settings=settings, create_response=True):
    async for event in realtime_client.receive():
        match event.event_type:
            # receiving a piece of audio (and send it to a undefined audio player)
            case "audio":
                await audio_player.add_audio(event.audio)
            case "text":
                # the model returns both audio and transcript of the audio, which we will print
                print(event.text.text, end="")
            case "service":
                # OpenAI Specific events
                if event.service_type == ListenEvents.SESSION_UPDATED:
                    print("Session updated")
                if event.service_type == ListenEvents.RESPONSE_CREATED:
                    print("\nMosscap (transcript): ", end="")

Ambos ejemplos reciben el audio como RealtimeAudioEvent y, a continuación, lo pasan a un objeto audio_player no especificado.

Nota: El cliente webRTC de Azure OpenAI tiene un parámetro adicional: region, esto hace referencia a la región de Azure donde se hospeda el servicio OpenAI. Actualmente solo se admiten eastus2 y swedencentral.

Callback de salida de audio

Junto a esto, tenemos un parámetro denominado audio_output_callback en el método receive y en la creación de la clase. Este callback se llamará primero antes de cualquier manejo adicional del audio y obtiene una matriz numpy de los datos de audio, en lugar de analizarlos como AudioContent y devolverlos como un RealtimeAudioEvent que luego puede manejar, que es lo que sucede anteriormente. Esto ha demostrado proporcionar una salida de audio más fluida porque hay menos latencia entre los datos de audio que entran y el momento en que se entregan al reproductor.

En este ejemplo se muestra cómo definir y usar el audio_output_callback:

from semantic_kernel.connectors.ai.open_ai import (
    ListenEvents,
    OpenAIRealtimeExecutionSettings,
    OpenAIRealtimeWebRTC,
)
from aiortc.mediastreams import MediaStreamTrack

class AudioRecorderWebRTC(MediaStreamTrack):
    # implement the MediaStreamTrack methods.

class AudioPlayer:
    async def play_audio(self, content: np.ndarray):
        # implement the audio player

realtime_client = OpenAIRealtimeWebRTC(audio_track=AudioRecorderWebRTC())
# Create the settings for the session
settings = OpenAIRealtimeExecutionSettings(
    instructions="""
You are a chat bot. Your name is Mosscap and
you have one goal: figure out what people need.
Your full name, should you need to know it, is
Splendid Speckled Mosscap. You communicate
effectively, but you tend to answer with long
flowery prose.
""",
    voice="shimmer",
)
audio_player = AudioPlayer
async with realtime_client(settings=settings, create_response=True):
    async for event in realtime_client.receive(audio_output_callback=audio_player.play_audio):
        match event.event_type:
            # no need to handle case: "audio"
            case "text":
                # the model returns both audio and transcript of the audio, which we will print
                print(event.text.text, end="")
            case "service":
                # OpenAI Specific events
                if event.service_type == ListenEvents.SESSION_UPDATED:
                    print("Session updated")
                if event.service_type == ListenEvents.RESPONSE_CREATED:
                    print("\nMosscap (transcript): ", end="")

Muestras

Hay cuatro ejemplos en nuestro repositorio, cubren los conceptos básicos mediante websockets y WebRTC, así como una configuración más compleja, incluida la llamada a funciones. Por último, hay una demostración más compleja que utiliza Azure Communication Services para permitir realizar llamadas a la API de tiempo real mejorada del Kernel Semántico.

Próximamente

Más información próximamente.

Próximamente

Más información próximamente.