Crie um assistente de voz com a plataforma Agents em um Raspberry Pi

Crie um assistente de voz com a plataforma Agents em um Raspberry Pi.

Tutorial · Pressupõe que você tenha concluído o guia de início rápido do ElevenAgents e tenha um Raspberry Pi com Python instalado.

Introdução

Neste tutorial, você aprenderá a criar um assistente de voz com o Agents Platform em execução em um Raspberry Pi. Assim como assistentes domésticos convencionais, como a Alexa no Amazon Echo, o Google Home ou a Siri em dispositivos Apple, seu assistente de voz Eleven ouvirá uma palavra de ativação — neste caso, “Hey Eleven” — e iniciará uma sessão do ElevenLabs Agents para ajudar o usuário.

Requisitos

  • Um Raspberry Pi 5 ou dispositivo semelhante.
  • Um microfone e um alto-falante.
  • Python 3.9 ou superior instalado na sua máquina.
  • Uma conta ElevenLabs com uma chave de API.

Configuração

Instalar dependências

Em sistemas baseados em Debian, você pode instalar as dependências com:

sudo apt-get update
sudo apt-get install libportaudio2 libportaudiocpp0 portaudio19-dev libasound-dev libsndfile1-dev -y

Criar o projeto

No seu Raspberry Pi, abra o terminal e crie um novo diretório para o projeto.

mkdir eleven-voice-assistant
cd eleven-voice-assistant

Crie um novo ambiente virtual e instale as dependências:

python -m venv .venv # Only required the first time you set up the project
source .venv/bin/activate

Instale as dependências:

pip install tflite-runtime
pip install librosa
pip install EfficientWord-Net
pip install elevenlabs
pip install "elevenlabs[pyaudio]"

Agora, crie um novo arquivo Python chamado hotword.py e adicione o código abaixo:

hotword.py
import os
import signal
import time
from eff_word_net.streams import SimpleMicStream
from eff_word_net.engine import HotwordDetector
from eff_word_net.audio_processing import Resnet50_Arc_loss
# from eff_word_net import samples_loc
from elevenlabs.client import ElevenLabs
from elevenlabs.conversational_ai.conversation import Conversation, ConversationInitiationData
from elevenlabs.conversational_ai.default_audio_interface import DefaultAudioInterface
convai_active = False
elevenlabs = ElevenLabs()
agent_id = os.getenv("ELEVENLABS_AGENT_ID")
api_key = os.getenv("ELEVENLABS_API_KEY")
dynamic_vars = {
'user_name': 'Thor',
'greeting': 'Hey'
}
config = ConversationInitiationData(
dynamic_variables=dynamic_vars
)
base_model = Resnet50_Arc_loss()
eleven_hw = HotwordDetector(
hotword="hey_eleven",
model = base_model,
reference_file=os.path.join("hotword_refs", "hey_eleven_ref.json"),
threshold=0.7,
relaxation_time=2
)
def create_conversation():
"""Create a new conversation instance"""
return Conversation(
# API client and agent ID.
elevenlabs,
agent_id,
config=config,
# Assume auth is required when API_KEY is set.
requires_auth=bool(api_key),
# Use the default audio interface.
audio_interface=DefaultAudioInterface(),
# Simple callbacks that print the conversation to the console.
callback_agent_response=lambda response: print(f"Agent: {response}"),
callback_agent_response_correction=lambda original, corrected: print(f"Agent: {original} -> {corrected}"),
callback_user_transcript=lambda transcript: print(f"User: {transcript}"),
# Uncomment if you want to see latency measurements.
# callback_latency_measurement=lambda latency: print(f"Latency: {latency}ms"),
)
def start_mic_stream():
"""Start or restart the microphone stream"""
global mic_stream
try:
# Always create a new stream instance
mic_stream = SimpleMicStream(
window_length_secs=1.5,
sliding_window_secs=0.75,
)
mic_stream.start_stream()
print("Microphone stream started")
except Exception as e:
print(f"Error starting microphone stream: {e}")
mic_stream = None
time.sleep(1) # Wait a bit before retrying
def stop_mic_stream():
"""Stop the microphone stream safely"""
global mic_stream
try:
if mic_stream:
# SimpleMicStream doesn't have a stop_stream method
# We'll just set it to None and recreate it next time
mic_stream = None
print("Microphone stream stopped")
except Exception as e:
print(f"Error stopping microphone stream: {e}")
# Initialize microphone stream
mic_stream = None
start_mic_stream()
print("Say Hey Eleven ")
while True:
if not convai_active:
try:
# Make sure we have a valid mic stream
if mic_stream is None:
start_mic_stream()
continue
frame = mic_stream.getFrame()
result = eleven_hw.scoreFrame(frame)
if result == None:
#no voice activity
continue
if result["match"]:
print("Wakeword uttered", result["confidence"])
# Stop the microphone stream to avoid conflicts
stop_mic_stream()
# Start ConvAI Session
print("Start ConvAI Session")
convai_active = True
try:
# Create a new conversation instance
conversation = create_conversation()
# Start the session
conversation.start_session()
# Set up signal handler for graceful shutdown
def signal_handler(sig, frame):
print("Received interrupt signal, ending session...")
try:
conversation.end_session()
except Exception as e:
print(f"Error ending session: {e}")
signal.signal(signal.SIGINT, signal_handler)
# Wait for session to end
conversation_id = conversation.wait_for_session_end()
print(f"Conversation ID: {conversation_id}")
except Exception as e:
print(f"Error during conversation: {e}")
finally:
# Cleanup
convai_active = False
print("Conversation ended, cleaning up...")
# Give some time for cleanup
time.sleep(1)
# Restart microphone stream
start_mic_stream()
print("Ready for next wake word...")
except Exception as e:
print(f"Error in wake word detection: {e}")
# Try to restart microphone stream if there's an error
mic_stream = None
time.sleep(1)
start_mic_stream()

Configuração do agente

1

Entrar na ElevenLabs

Acesse elevenlabs.io e entre na sua conta.

2

Criar um novo agente

Acesse Agents Platform > Agents e crie um novo agente a partir do modelo em branco.

3

Definir a primeira mensagem

Defina a primeira mensagem e especifique a variável dinâmica para a plataforma.

{{greeting}} {{user_name}}, Eleven here, what's up?
4

Definir o prompt do sistema

Defina o prompt do sistema. Você encontra nossa documentação de boas práticas aqui.

You are a helpful Agents Platform assistant with access to a weather tool. When users ask about
weather conditions, use the get_weather tool to fetch accurate, real-time data. The tool requires
a latitude and longitude - use your geographic knowledge to convert location names to coordinates
accurately.
Never ask users for coordinates - you must determine these yourself. Always report weather
information conversationally, referring to locations by name only. For weather requests:
1. Extract the location from the user's message
2. Convert the location to coordinates and call get_weather
3. Present the information naturally and helpfully
For non-weather queries, provide friendly assistance within your knowledge boundaries. Always be
concise, accurate, and helpful.
5

Configurar uma ferramenta de webhook

Vamos configurar uma ferramenta de webhook simples que buscará os dados meteorológicos para nós. Siga as etapas de configuração aqui para configurar a ferramenta.

Executar o app

Para executar o app, primeiro defina as variáveis de ambiente necessárias:

export ELEVENLABS_API_KEY=YOUR_API_KEY
export ELEVENLABS_AGENT_ID=YOUR_AGENT_ID

Depois, basta executar o seguinte comando:

python hotword.py

Agora diga “Hey Eleven” para iniciar a conversa. Boas conversas!

[Opcional] Treine sua palavra de ativação personalizada

Gerar áudio de treinamento

Para gerar os embeddings da palavra de ativação, você pode usar a ElevenLabs para gerar quatro amostras de treinamento. Basta acessar o Text To Speech no seu app da ElevenLabs e digitar sua palavra de ativação, por exemplo, “Hey Eleven”. Selecione uma voz e clique no botão “Generate”.

Depois que o áudio for gerado, baixe o arquivo de áudio e salve-o em uma pasta chamada hotword_training_audio na raiz do projeto. Repita esse processo mais três vezes com vozes diferentes.

Treinar a palavra de ativação

No terminal, com o ambiente virtual ativado, execute o comando abaixo para treinar a palavra de ativação:

python -m eff_word_net.generate_reference --input-dir hotword_training_audio --output-dir hotword_refs --wakeword hey_eleven --model-type resnet_50_arc

Isso gerará o arquivo hey_eleven_ref.json na pasta hotword_refs. Agora, basta atualizar o parâmetro reference_file na classe HotwordDetector em hotword.py para apontar para o novo arquivo de referência e pronto!

Próximas etapas