text_to_speech_agent.py
Run the Example
1
Set up your virtual environment
2
Install dependencies
3
Export your API keys
4
Run the example
Save the code above as
text_to_speech_agent.py, then run:Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Generate speech with the OpenAITools speech toolkit and save the returned audio to tmp/speech_output.mp3.
"""Example: Using the OpenAITools Toolkit for Text-to-Speech
This script demonstrates how to use an agent to generate speech from a given text input and optionally save it to a specified audio file.
Run `uv pip install openai agno` to install the necessary dependencies.
"""
import base64
from pathlib import Path
from agno.agent import Agent
from agno.models.google import Gemini
from agno.tools.openai import OpenAITools
from agno.utils.media import save_base64_data
# ---------------------------------------------------------------------------
# Create Agent
# ---------------------------------------------------------------------------
output_file: str = str(Path("tmp/speech_output.mp3"))
agent: Agent = Agent(
model=Gemini(id="gemini-2.5-pro"),
tools=[OpenAITools(enable_speech_generation=True)],
markdown=True,
)
# Ask the agent to generate speech, but not save it
response = agent.run(
'Please generate speech for the following text: "Hello from Agno! This is a demonstration of the text-to-speech capability using OpenAI"'
)
print(f"Agent response: {response.get_content_as_string()}")
if response.audio:
base64_audio = base64.b64encode(response.audio[0].content).decode("utf-8")
save_base64_data(base64_audio, output_file)
print(f"Successfully saved generated speech to{output_file}")
# ---------------------------------------------------------------------------
# Run Agent
# ---------------------------------------------------------------------------
if __name__ == "__main__":
pass
Set up your virtual environment
uv venv --python 3.12
source .venv/bin/activate
uv venv --python 3.12
.venv\Scripts\activate
Install dependencies
uv pip install -U agno google-genai openai
Export your API keys
export GOOGLE_API_KEY="your_google_api_key_here"
export OPENAI_API_KEY="your_openai_api_key_here"
$Env:GOOGLE_API_KEY="your_google_api_key_here"
$Env:OPENAI_API_KEY="your_openai_api_key_here"
Run the example
text_to_speech_agent.py, then run:python text_to_speech_agent.py
Was this page helpful?