LiveKit xAI Realtime Voice Agent

LiveKit xAI Realtime Voice Agent

LiveKit의 xAI Grok Voice Agent 플러그인을 LiteLLM Proxy와 함께 사용해 저지연 음성 AI 에이전트를 만들어 봐요.

LiveKit Agents 프레임워크는 실시간 음성/비디오 AI 애플리케이션을 만들기 위한 도구를 제공합니다. LiteLLM Proxy를 통해 라우팅하면 여러 실시간 음성 제공자에 대한 통합 접근, 비용 추적, rate limiting 등을 얻을 수 있어요.

출처: 문서

본문

빠른 시작

1. 의존성 설치

uv add livekit-agents[xai]

2. LiteLLM Proxy 시작

xAI realtime 모델로 설정 파일을 만드세요:

config.yaml

model_list:
  - model_name: grok-voice-agent
    litellm_params:
      model: xai/grok-voice-latest
      api_key: os.environ/XAI_API_KEY
    model_info:
      mode: realtimelitellm_settings:
  drop_params: Truegeneral_settings:
  master_key: os.environ/LITELLM_MASTER_KEY  # Change this to a secure key

프록시 시작:

litellm --config config.yaml --port 4000

3. LiveKit xAI 플러그인 구성

LiveKit의 xAI 플러그인이 여러분의 LiteLLM proxy를 가리키게 하세요:

from livekit.plugins import xai# Configure xAI to use LiteLLM proxymodel = xai.realtime.RealtimeModel(
    voice="ara",                      # Voice option
    api_key="sk-",               # Your LiteLLM proxy master key
    base_url="http://localhost:4000", # LiteLLM proxy URL)

완전한 예시

다음은 완전히 동작하는 예시입니다:

  • Python Client
  • LiveKit Agent
#!/usr/bin/env python3"""Simple xAI realtime voice agent through LiteLLM proxy."""import asyncioimport jsonimport websocketsPROXY_URL = "ws://localhost:4000/v1/realtime"API_KEY = "sk-"MODEL = "grok-voice-agent"async def run_voice_agent():    """Connect to xAI realtime API through LiteLLM proxy"""
    url = f"{PROXY_URL}?model={MODEL}"
    headers = {"Authorization": f"Bearer {API_KEY}"}
        async with websockets.connect(url, extra_headers=headers) as ws:
        # Wait for initial connection event
        initial = json.loads(await ws.recv())
        print(f"✅ Connected: {initial['type']}")
                # Send user message
        await ws.send(json.dumps({
            "type": "conversation.item.create",
            "item": {
                "type": "message",
                "role": "user",
                "content": [{
                    "type": "input_text",
                    "text": "Hello! Tell me a joke."
                }]
            }
        }))
                # Request response
        await ws.send(json.dumps({
            "type": "response.create",
            "response": {"modalities": ["text", "audio"]}
        }))
                # Collect response
        transcript = []
        async for message in ws:
            event = json.loads(message)
                        # Capture text response
            if event['type'] == 'response.output_audio_transcript.delta':
                transcript.append(event['delta'])
                print(event['delta'], end='', flush=True)
                        # Done when response completes
            elif event['type'] == 'response.done':
                break
                print(f"\n\n✅ Full response: {''.join(transcript)}")if __name__ == "__main__":    asyncio.run(run_voice_agent())
from livekit.agents import Agent, AgentSession, WorkerOptions, clifrom livekit.plugins import xaiclass VoiceAgent(Agent):    def __init__(self):        super().__init__(
            instructions="You are a helpful voice assistant.",
            llm=xai.realtime.RealtimeModel(
                voice="ara",
                api_key="sk-",
                base_url="http://localhost:4000",
            ),
        )if __name__ == "__main__":    cli.run_app(
        WorkerOptions(
            agent_factory=VoiceAgent,
        )
    )

예시 실행

LiteLLM Proxy 시작(아직 실행 중이 아니라면):

litellm --config config.yaml --port 4000

예시 실행:

python your_script.py

기대 출력

✅ Connected: session.createdHello! Here's a joke for you: Why don't scientists trust atoms? Because they make up everything!✅ Full response: Hello! Here's a joke for you: Why don't scientists trust atoms? Because they make up everything!

완전한 동작 예시

LiveKit Agent SDK Cookbook

더 알아보기

  • xAI Realtime API
  • LiveKit xAI Plugin
  • LiteLLM Realtime API

더 알아보기 (Learn more)