what is the right way to build multilingual agent ...
# ask-ai
n
what is the right way to build multilingual agent using non realtime llms?
t
Thanks for reaching out, Nikhil. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to build a multilingual agent that uses non‑realtime LLMs. Below is a clear, practical architecture and key steps you can implement with LiveKit components. Core architecture (STT → language detection/turn detection → LLM → TTS) 1. STT: Use a multilingual STT (or one with automatic detection) so incoming speech is transcribed with language metadata. Example providers: Deepgram (multi), ElevenLabs Scribe, AssemblyAI. 2. Turn detection: Use a multilingual turn detector (
MultilingualModel
) so the agent knows when to send full utterances to the LLM and handle interruptions or code-switching. 3. Language routing / tagging: Attach the detected language to the transcript before sending to the LLM. For mixed-language utterances, prefer STT that supports code‑switching or include short language tags in the prompt. 4. LLM (non‑realtime): Send the tagged transcript and conversation context to your non‑realtime LLM. In system or prompt instructions, specify that the assistant should reply in the user’s detected language (or a target language you choose). Keep concise context to limit latency and costs. 5. TTS: Select a TTS voice that matches the response language and locale. Generate audio from the LLM response and play it back to the user. 6. Session management: Use an AgentSession-like workflow to orchestrate STT, turn detection, LLM calls, and TTS, and to store short-term context for subsequent turns. Practical tips and best practices • Always include language metadata with each user turn so the LLM can preserve the language in its reply. • For low latency with non‑realtime LLMs, keep prompts focused and avoid sending entire transcripts each turn — send only recent turns plus critical context. • If you must support code‑switching, rely on STT that labels language segments or detect language at sentence/subsentence level and tag fragments before aggregation. • Use the multilingual turn detector to avoid premature cutoffs and to handle interruptions gracefully. • Dynamically choose TTS voice & locale per response so playback sounds native. • If you need deterministic translations instead of native replies, insert a translate step (source → translate → LLM in target language → TTS) and tag that workflow explicitly. If you’d like, I can: • Suggest concrete prompt templates that preserve language tags for non‑realtime LLMs. • Provide a minimal AgentSession code example wiring STT, MultilingualModel turn detection, an LLM call, and TTS. Which would you prefer? Sources: LiveKit turn detector plugin | LiveKit docs | Gladia STT plugin guide | LiveKit Docs | Deepgram STT | LiveKit docs | Speech-to-text (STT) models | LiveKit Docs | ElevenLabs STT | LiveKit docs
n
can you provide code?
t
Which language do you want the example in — Python or JavaScript?
n
python
t
Below is a concise Python example wiring a multilingual STT → turn detection → non‑realtime LLM → TTS pipeline using LiveKit-style components (AgentSession,
MultilingualModel
, an STT provider, an LLM client, and TTS). This is a minimal, runnable outline you can adapt to real providers and keys.
Copy code
# Minimal multilingual agent pipeline (non-realtime LLM)
# - Replace provider clients and keys with your actual SDKs
# - Focus: STT -> Multilingual turn detection -> LLM -> TTS

from typing import Dict, Any
import time

# --- Placeholder provider client wrappers (replace with actual SDKs) ---
class STTClient:
    def __init__(self, model="deepgram/nova-3:multi"):
        self.model = model
    def transcribe(self, audio_bytes: bytes) -> Dict[str, Any]:
        # Return structure: {"text": "...", "language": "es", "segments": [...]}
        raise NotImplementedError

class TurnDetector:
    def __init__(self):
        # Use MultilingualModel equivalent
        pass
    def is_end_of_turn(self, stt_result: Dict[str, Any]) -> bool:
        # Inspect VAD/segments to decide end of turn
        raise NotImplementedError

class LLMClient:
    def __init__(self, model="gpt-4o"):
        self.model = model
    def generate(self, prompt: str, language: str) -> str:
        # Non-realtime call: returns response text in desired language
        raise NotImplementedError

class TTSClient:
    def __init__(self):
        pass
    def synthesize(self, text: str, language: str) -> bytes:
        # Return audio bytes matching language/voice
        raise NotImplementedError

# --- Orchestration: AgentSession-like flow ---
class MultilingualAgent:
    def __init__(self, stt: STTClient, turn_detector: TurnDetector, llm: LLMClient, tts: TTSClient):
        self.stt = stt
        self.turn_detector = turn_detector
        self.llm = llm
        self.tts = tts
        self.short_term_context = []  # keep recent turns

    def handle_audio_chunk(self, audio_bytes: bytes):
        # 1) STT -> get transcript + language metadata
        stt_result = self.stt.transcribe(audio_bytes)
        text = stt_result.get("text", "").strip()
        language = stt_result.get("language", "en")

        if not text:
            return None

        # 2) Turn detection: wait until end-of-turn before invoking LLM
        if not self.turn_detector.is_end_of_turn(stt_result):
            # buffer or continue collecting audio
            return None

        # 3) Create a prompt with language tag and short context
        # Keep only recent N turns to limit token usage
        recent_context = "\n".join(self.short_term_context[-6:])
        prompt = (
            f"[User language: {language}]\n"
            f"{recent_context}\n"
            f"User: {text}\n\n"
            f"Assistant (respond in {language}):"
        )

        # 4) Non-realtime LLM call
        response_text = self.llm.generate(prompt=prompt, language=language)

        # 5) Append to context
        self.short_term_context.append(f"User: {text}")
        self.short_term_context.append(f"Assistant: {response_text}")

        # 6) TTS synthesis matching language
        audio_out = self.tts.synthesize(response_text, language=language)

        # 7) Return or play audio_out to the user
        return {"text": response_text, "audio_bytes": audio_out, "language": language}

# --- Example usage with pseudo-implementations ---
if __name__ == "__main__":
    # Replace these with actual provider clients
    stt = STTClient(model="deepgram/nova-3:multi")
    turn_detector = TurnDetector()  # wrap MultilingualModel logic
    llm = LLMClient(model="gpt-4o")
    tts = TTSClient()

    agent = MultilingualAgent(stt=stt, turn_detector=turn_detector, llm=llm, tts=tts)

    # Simulate incoming audio chunks (in practice, collect microphone or stream chunks)
    fake_audio_chunks = [b"...audio chunk 1...", b"...audio chunk 2..."]

    for chunk in fake_audio_chunks:
        result = agent.handle_audio_chunk(chunk)
        if result:
            print(f"Detected language: {result['language']}")
            print("Assistant reply:", result["text"])
            # play result["audio_bytes"] via audio output device
        time.sleep(0.2)
If you want, I can: • Provide concrete implementations for
STTClient
,
TurnDetector
(using the MultilingualModel API),
LLMClient
(OpenAI/other SDK), and
TTSClient
(ElevenLabs/Cartesia). • Add handling for code‑switching by segment-level language tagging and merging before prompting. Which concrete providers would you like me to wire in (e.g., Deepgram + OpenAI + ElevenLabs)?
n
i want deepgram as both stt and tts
t
Below is a focused, runnable Python example wiring Deepgram for both STT (multilingual) and TTS, with a non‑realtime LLM call. It uses LiveKit Agents-style classes (Deepgram plugin wrappers shown) — replace placeholder API calls with your actual SDK calls/keys.
Copy code
# multilingual_agent_deepgram.py
# Minimal example: Deepgram STT (multilingual) -> non-realtime LLM -> Deepgram TTS
# Replace placeholder implementations with real SDK calls and set your keys in env.

import os
import asyncio
from typing import Dict, Any

# --- Replace these with actual SDK imports / LiveKit plugin classes if available ---
# Example names follow LiveKit plugin patterns: deepgram.STTv2, deepgram.TTS, openai.LLM
# Here we provide simple wrappers to show wiring.

class DeepgramSTT:
    def __init__(self, model: str = "nova-3", language: str = "multi"):
        self.model = model
        self.language = language
        # init deepgram client with DEEPGRAM_API_KEY from env if using SDK

    def transcribe(self, audio_bytes: bytes) -> Dict[str, Any]:
        """
        Return dict:
          {"text": "transcript", "language": "es", "segments": [...]}
        Implement with Deepgram API: use model=self.model and language=self.language.
        """
        # TODO: call Deepgram STT API and return structured result
        raise NotImplementedError

class DeepgramTTS:
    def __init__(self, model: str = "aura-asteria-en", voice: str = None):
        self.model = model
        self.voice = voice

    def synthesize(self, text: str, language: str = "en") -> bytes:
        """
        Return audio bytes synthesized by Deepgram TTS.
        Choose voice/model appropriate for `language`.
        """
        # TODO: call Deepgram TTS API, return audio bytes
        raise NotImplementedError

class NonRealtimeLLM:
    def __init__(self, model: str = "gpt-4o-mini"):
        self.model = model
        # init OpenAI or other LLM client with keys

    def generate(self, prompt: str) -> str:
        """
        Make a non-realtime (request/response) call to your LLM and return text.
        Keep prompts concise; include language tag in prompt.
        """
        # TODO: implement call to OpenAI / other LLM and return response text
        raise NotImplementedError

# --- Turn detection: simple silence-based or segment-based decision ---
class MultilingualTurnDetector:
    def __init__(self):
        pass

    def is_end_of_turn(self, stt_result: Dict[str, Any]) -> bool:
        """
        Use STT segments, VAD, or MultilingualModel to determine end-of-turn.
        For this example, assume STT result includes segments and final flag.
        """
        # Example: stt_result could contain {"is_final": True}
        return bool(stt_result.get("is_final"))

# --- Orchestration ---
class MultilingualAgent:
    def __init__(self, stt: DeepgramSTT, llm: NonRealtimeLLM, tts: DeepgramTTS, turn_detector: MultilingualTurnDetector):
        self.stt = stt
        self.llm = llm
        self.tts = tts
        self.turn_detector = turn_detector
        self.context = []  # recent conversation turns

    async def handle_audio_chunk(self, audio_bytes: bytes):
        # 1) STT -> transcript + language metadata
        stt_result = self.stt.transcribe(audio_bytes)
        text = stt_result.get("text", "").strip()
        language = stt_result.get("language", "en")

        if not text:
            return None

        # 2) Wait until end-of-turn
        if not self.turn_detector.is_end_of_turn(stt_result):
            return None

        # 3) Build prompt with language tag and short context
        recent = "\n".join(self.context[-6:])
        prompt = (
            f"[User language: {language}]\n"
            f"{recent}\n"
            f"User: {text}\n\n"
            f"Assistant (reply in {language}):"
        )

        # 4) Non‑realtime LLM call
        response_text = self.llm.generate(prompt)

        # 5) Update context
        self.context.append(f"User: {text}")
        self.context.append(f"Assistant: {response_text}")

        # 6) TTS with Deepgram
        audio_out = self.tts.synthesize(response_text, language=language)

        return {"text": response_text, "audio_bytes": audio_out, "language": language}

# --- Example main showing wiring; implement provider methods before running ---
async def main():
    stt = DeepgramSTT(model="nova-3", language="multi")
    tts = DeepgramTTS(model="aura-asteria-en", voice=None)
    llm = NonRealtimeLLM(model="gpt-4o-mini")
    turn_detector = MultilingualTurnDetector()

    agent = MultilingualAgent(stt=stt, llm=llm, tts=tts, turn_detector=turn_detector)

    # Example: load some audio file chunk (PCM/ogg/etc) to simulate incoming audio.
    # Replace with actual streaming input in production.
    example_audio_path = "user_turn.wav"
    if os.path.exists(example_audio_path):
        with open(example_audio_path, "rb") as f:
            audio_bytes = f.read()
        result = await agent.handle_audio_chunk(audio_bytes)
        if result:
            print("Detected language:", result["language"])
            print("Assistant reply:", result["text"])
            # Save TTS to file for playback
            with open("reply.wav", "wb") as out:
                out.write(result["audio_bytes"])
            print("Wrote reply.wav")
    else:
        print("Place a test WAV at", example_audio_path)

if __name__ == "__main__":
    asyncio.run(main())
If you want, I can now: • Provide concrete implementations calling Deepgram STT/TTS SDKs and a specific LLM (e.g., OpenAI) with real request examples. • Add code for segment-level language detection / code‑switching handling using Deepgram segment metadata. Which concrete LLM and how would you like Deepgram voices chosen for different languages? Sources: Deepgram STT | LiveKit docs | Deepgram TTS | LiveKit docs | Deepgram TTS plugin guide | LiveKit Docs | Deepgram STT plugin guide | LiveKit docs
n
how do i run it for spanish?
t
To run the example for Spanish, set Deepgram STT to auto-detect (or explicitly Spanish) and choose a Spanish TTS voice, pass Spanish language metadata to the LLM prompt, then run the script. Concretely: 1. STT: instantiate with
language="es"
or keep
language="multi"
(auto-detect). Using
"es"
forces Spanish;
"multi"
lets Deepgram auto-detect. ◦ Example:
stt = DeepgramSTT(model="nova-3", language="es")
1. Prompt / LLM: include the detected language tag so the LLM replies in Spanish. ◦ The example already builds a prompt with
"[User language: {language}]"
and
Assistant (reply in {language}):"
. Ensure
language == "es"
(or set when detected). 1. TTS: pick a Deepgram voice/model for Spanish (use a Spanish voice model such as
aura-asteria-es
or the appropriate Deepgram Spanish voice). Example: ◦
tts = DeepgramTTS(model="aura-asteria-es", voice="athena-es")
◦ If you only have
aura-asteria-en
, switch to the Spanish model/voice to avoid English output. 1. Run the script: ◦ Put a Spanish audio file (user_turn.wav) with Spanish speech in the project root. ◦ Ensure DEEPGRAM_API_KEY and any LLM keys are set in env. ◦ Run:
python multilingual_agent_deepgram.py
1. Verify: ◦ The STT result should show
"language": "es"
and a Spanish transcript. ◦ The LLM response should be Spanish. ◦ The saved
reply.wav
should contain Spanish TTS audio. If you want, I can: • Provide the exact Deepgram API calls for STT/TTS in the placeholder methods, • Or update the example to force
language="es"
and use a confirmed Spanish Deepgram voice. Which would you prefer?