Raspberry Pi에서 Agents Platform으로 음성 어시스턴트 구축

Raspberry Pi에서 Agents Platform으로 음성 어시스턴트를 구축합니다.

튜토리얼 · ElevenAgents 빠른 시작을 완료했고 Python이 설치된 Raspberry Pi가 있다고 가정합니다.

소개

이 튜토리얼에서는 Raspberry Pi에서 실행되는 Agents Platform으로 음성 어시스턴트를 구축하는 방법을 알아봅니다. Amazon Echo의 Alexa, Google Home 또는 Apple 기기의 Siri 같은 일반적인 홈 어시스턴트와 마찬가지로, Eleven 음성 어시스턴트는 핫워드(여기서는 “Hey Eleven”)를 듣고 ElevenLabs Agents 세션을 시작하여 사용자를 지원합니다.

요구 사항

  • Raspberry Pi 5 또는 유사한 기기
  • 마이크와 스피커
  • 기기에 설치된 Python 3.9 이상
  • API 키가 있는 ElevenLabs 계정

설정

종속성 설치

Debian 기반 시스템에서는 다음 명령으로 종속성을 설치할 수 있습니다.

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

프로젝트 생성

Raspberry Pi에서 터미널을 열고 프로젝트용 새 디렉터리를 만듭니다.

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

새 가상 환경을 만들고 종속성을 설치합니다.

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

종속성을 설치합니다.

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

이제 hotword.py라는 새 Python 파일을 만들고 다음 코드를 추가합니다.

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()

에이전트 구성

1

ElevenLabs에 로그인

elevenlabs.io로 이동하여 계정에 로그인합니다.

2

새 에이전트 생성

Agents Platform > Agents로 이동하여 빈 템플릿으로 새 에이전트를 만듭니다.

3

첫 메시지 설정

첫 메시지를 설정하고 플랫폼의 동적 변수를 지정합니다.

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

시스템 프롬프트 설정

시스템 프롬프트를 설정합니다. 권장 사례 문서는 여기에서 확인할 수 있습니다.

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

웹훅 도구 설정

날씨 데이터를 가져오는 간단한 웹훅 도구를 설정하겠습니다. 도구 설정 방법은 여기의 단계를 따르세요.

앱 실행

앱을 실행하려면 먼저 필요한 환경 변수를 설정합니다.

export ELEVENLABS_API_KEY=YOUR_API_KEY
export ELEVENLABS_AGENT_ID=YOUR_AGENT_ID

그런 다음 다음 명령을 실행합니다.

python hotword.py

이제 “Hey Eleven”이라고 말해 대화를 시작하세요. 즐거운 대화 되세요!

[선택 사항] 맞춤 핫워드 학습

학습 오디오 생성

핫워드 임베딩을 생성하려면 ElevenLabs로 4개의 학습 샘플을 만들 수 있습니다. ElevenLabs 앱에서 텍스트 음성 변환으로 이동한 후 “Hey Eleven”과 같이 핫워드를 입력하세요. 음성을 선택하고 “Generate” 버튼을 클릭합니다.

오디오가 생성되면 오디오 파일을 다운로드하여 프로젝트 루트의 hotword_training_audio 폴더에 저장합니다. 다른 음성으로 이 과정을 3번 더 반복합니다.

핫워드 학습

가상 환경을 활성화한 상태에서 터미널에 다음 명령을 실행하여 핫워드를 학습합니다.

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

그러면 hotword_refs 폴더에 hey_eleven_ref.json 파일이 생성됩니다. 이제 hotword.py의 HotwordDetector 클래스에서 reference_file 매개변수가 새 참조 파일을 가리키도록 업데이트하면 됩니다!

다음 단계