```load_dotenv(".env") class Assistant(Agent): ...
# ask-ai
r
Copy code
load_dotenv(".env")

class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""You are a helpful voice assistant who can understand and respond in multiple languages.
            You should respond in the same language the user speaks.
            Your responses should be concise and clear."""
        )

async def entrypoint(ctx: agents.JobContext):

    session = AgentSession(
        turn_detection=MultilingualModel(),
        vad=silero.VAD.load(),
        stt=cartesia.STT(
            model="ink-whisper",
            language="bn",  # Bengali language code
        ),
        llm=google.LLM(
            model="gemini-2.5-flash-preview-09-2025",
            # gemini_tools=[types.GoogleSearch(), ...], # Uncomment and add tools if needed
        ),
        tts=google.beta.GeminiTTS(
            model="gemini-2.5-flash-preview-tts",
            voice_name="Sulafat",  # Test out voice in Google AI Studio (https://aistudio.google.com/live)
        )
    )

    # Define your agent and start the session.
    await session.start(
        agent=Assistant(),  # Use the Assistant class
        room=ctx.room,
        room_input_options=RoomInputOptions(
            # For telephony applications, use `BVCTelephony` instead for best results
            noise_cancellation=noise_cancellation.BVC(), 
        ),
    )

    # You can send an initial greeting
    await session.generate_reply(
        instructions="Greet the user in Bengali and ask how you can help."
    )
    
if __name__ == "__main__":
    # The cli.run_app function starts the worker and waits for jobs.
    agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))
Is the code correct?
t
Thanks for reaching out, Ayman. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
The code you shared looks great and fits well with LiveKit's features for creating a multilingual voice assistant. It nicely brings together components like
AgentSession
, Google LLM, and multilingual STT/TTS, all of which are fully supported. Just make sure you have all the necessary dependencies installed and your API keys set up correctly in your
.env
file. If you'd like, I'd be happy to share some additional resources or examples to help you get this up and running smoothly on LiveKit Cloud. Just let me know! Sources: LiveKit Docs | Building voice agents | LiveKit Docs | avatars/hedra/dynamically_created_avatar/agent.py | agent.py | examples/voice_agents/zapier_mcp_integration.py
r
I have installed all dependencies and set up API keys, but I get this error:
Copy code
Traceback (most recent call last):
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\livekit\plugins\google\beta\gemini_tts.py", line 203, in _run
    response = await self._tts._client.aio.models.generate_content(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\google\genai\models.py", line 6709, in generate_content
    response = await self._generate_content(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\google\genai\models.py", line 5544, in _generate_content
    response = await self._api_client.async_request(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\google\genai\_api_client.py", line 1326, in async_request
    result = await self._async_request(
             ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\google\genai\_api_client.py", line 1271, in _async_request
    return await self._async_retry(  # type: ignore[no-any-return]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\tenacity\asyncio\__init__.py", line 111, in __call__
    do = await self.iter(retry_state=retry_state)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\tenacity\asyncio\__init__.py", line 153, in iter
    result = await action(retry_state)
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\tenacity\_utils.py", line 99, in inner
    return call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\tenacity\__init__.py", line 420, in exc_check
    raise retry_exc.reraise()
          ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\tenacity\__init__.py", line 187, in reraise
    raise self.last_attempt.result()
          ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ayman\AppData\Roaming\uv\python\cpython-3.12.9-windows-x86_64-none\Lib\concurrent\futures\_base.py", line 449, in result
    return self.__get_result()
           ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ayman\AppData\Roaming\uv\python\cpython-3.12.9-windows-x86_64-none\Lib\concurrent\futures\_base.py", line 401, in __get_result
    raise self._exception
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\tenacity\asyncio\__init__.py", line 114, in __call__
    result = await fn(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\google\genai\_api_client.py", line 1216, in _async_request_once
    await errors.APIError.raise_for_async_response(response)
  File "C:\Users\Ayman\OneDrive\Desktop\voice_agent\.venv\Lib\site-packages\google\genai\errors.py", line 166, in raise_for_async_response
    raise ClientError(status_code, response_json, response)
google.genai.errors.ClientError: 429 RESOURCE_EXHAUSTED. {'error': {'code': 429, 'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, head to: https://ai.google.dev/gemini-api/docs/rate-limits.\n* Quota exceeded for metric: generativelanguage.googleapis.com/generate_content_free_tier_requests, limit: 3\nPlease retry in 30.374451188s.', 'status': 'RESOURCE_EXHAUSTED', 'details': [{'@type': 'type.googleapis.com/google.rpc.QuotaFailure', 'violations': [{'quotaMetric': 'generativelanguage.googleapis.com/generate_content_free_tier_requests', 'quotaId': 'GenerateRequestsPerMinutePerProjectPerModel-FreeTier', 'quotaDimensions': {'location': 'global', 'model': 'gemini-2.5-flash-tts'}, 'quotaValue': '3'}]}, {'@type': 'type.googleapis.com/google.rpc.Help', 'links': [{'description': 'Learn more about Gemini API quotas', 'url': 'https://ai.google.dev/gemini-api/docs/rate-limits'}]}, {'@type': 'type.googleapis.com/google.rpc.RetryInfo', 'retryDelay': '30s'}]}}
t
The error you're seeing suggests that your Google Gemini API quota has been exceeded. No worries—let's work through this together! Here are some friendly steps that can help: • Try adding retry logic with exponential backoff to smoothly handle those rate limits. • Take a moment to check your quota usage in the Google Cloud Console, and if it looks tight, you might want to request a quota increase. • Double-check that your API key and authentication are set up correctly to avoid any hiccups. • Keep an eye on your usage patterns so you can stay within your quotas going forward. • If you find yourself hitting limits often, upgrading to a paid plan could give you the extra room you need. If you'd like, I’m here to help guide you through any of these steps—just let me know! Sources: plugins/google/src/llm.ts | livekit-plugins/livekit-plugins-google/livekit/plugins/google/llm.py | Quotas and limits | LiveKit Docs | errors.go
r
Add them up for me
t
To help you resolve the quota exceeded error, here’s a friendly summary of the steps you can take: 1. Try adding retry logic with exponential backoff to gracefully handle those rate limits. 2. Take a moment to check your quota usage in the Google Cloud Console, and if needed, you can request an increase. 3. Double-check that your API key and authentication are set up correctly—sometimes a small tweak can make a big difference. 4. Keep an eye on your usage patterns so you can avoid hitting those limits in the future. 5. If you find yourself regularly reaching your quota, upgrading to a paid plan might be a great option to explore. Please feel free to reach out if you’d like a hand with any of these steps—I’m here to help!
r
retry logic add this to the code
t
Here’s a friendly way to add retry logic with exponential backoff to your code to gracefully handle those Google Gemini API rate limit errors:
Copy code
import asyncio
import logging
from google.genai.errors import ClientError

class RetryHandler:
    def __init__(self, max_retries=3, base_delay=1.0):
        self.max_retries = max_retries
        self.base_delay = base_delay

    async def execute_with_retry(self, operation):
        for attempt in range(self.max_retries):
            try:
                return await operation()
            except ClientError as e:
                if e.code == 429 and attempt < self.max_retries - 1:
                    retry_delay = self.base_delay * (2 ** attempt)
                    logging.warning(f"Rate limit hit. Retrying in {retry_delay}s...")
                    await asyncio.sleep(retry_delay)
                else:
                    raise

# Example usage
async def make_request():
    retry_handler = RetryHandler(max_retries=3, base_delay=2.0)

    async def api_call():
        # Replace with your actual API call
        response = await client.aio.models.generate_content(
            model="gemini-2.5-flash-preview-tts",
            contents="Your prompt here"
        )
        return response

    return await retry_handler.execute_with_retry(api_call)
This approach will patiently retry your API call up to 3 times with exponential backoff whenever a 429 error pops up. If you'd like, I’m here to help you weave this smoothly into your existing code—just let me know! Sources: livekit-plugins/livekit-plugins-google/livekit/plugins/google/llm.py | Webhook & Event Notification System | livekit/livekit_composite | DeepWiki