Build an AI Voice Agent for Astrology

Step-by-step guide to building an AI Voice Agent for astrology using VideoSDK, complete with code examples and testing instructions.

Introduction to AI Voice Agents in the Astrology Industry

In recent years, AI voice agents have become increasingly prevalent across various industries, offering automated and interactive solutions for businesses and consumers alike. But what exactly is an AI

voice agent

? Simply put, it is a software application that can understand and respond to human speech, often using natural language processing (NLP) technologies. These agents can perform a wide range of tasks, from answering questions to executing commands, making them invaluable in today's digital landscape.

Why are they important for the astrology industry?

The astrology industry, with its vast array of information and personalized advice, stands to benefit significantly from the integration of AI voice agents. These agents can provide users with instant access to daily horoscopes, explain astrological signs, and even offer insights into compatibility—all through simple voice interactions. This not only enhances user engagement but also provides a more personalized and interactive experience.

Core Components of a

Voice Agent

To build an effective AI

voice agent

, several core components are essential:
  • Speech-to-Text (STT): Converts spoken language into text.
  • Large Language Model (LLM): Processes the text to understand and generate responses.
  • Text-to-Speech (TTS): Converts the generated text back into spoken language.
For a comprehensive understanding, refer to the

AI voice Agent core components overview

which details these elements.

What You'll Build in This Tutorial

In this tutorial, we'll guide you through building a fully functional AI

voice agent

tailored for the astrology industry. Using the VideoSDK framework, we'll leverage state-of-the-art plugins for STT, TTS, and LLM to create an engaging and interactive agent.

Architecture and Core Concepts

To understand how our AI

voice agent

works, it's important to grasp its high-level architecture. The agent begins by listening to user input, which is processed through a series of steps to generate a response.

High-Level Architecture Overview

Diagram

Understanding Key Concepts in the VideoSDK Framework

  • Agent: The core class representing your bot, responsible for managing interactions.
  • CascadingPipeline: Manages the flow of audio processing from STT to LLM to TTS. For more details, explore the

    Cascading pipeline in AI voice Agents

    .
  • VAD & TurnDetector: Ensure the agent knows when to listen and respond, enhancing interaction fluidity. Learn more about the

    Turn detector for AI voice Agents

    .

Setting Up the Development Environment

Before diving into the code, let's set up our development environment.

Prerequisites

To follow this tutorial, you'll need:
  • Python 3.11+
  • A VideoSDK account (sign up at app.videosdk.live)

Step 1: Create a Virtual Environment

1python -m venv astrology-voice-agent
2source astrology-voice-agent/bin/activate  # On Windows use `astrology-voice-agent\\Scripts\\activate`
3

Step 2: Install Required Packages

Install the necessary packages using pip:
1pip install videosdk
2pip install python-dotenv
3

Step 3: Configure API Keys in a .env file

Create a .env file in your project's root directory and add your API keys:
1VIDEOSDK_API_KEY=your_api_key_here
2

Building the AI Voice Agent: A Step-by-Step Guide

Let's dive into building our AI voice agent. Below is the complete code block that we'll break down in this section.
1import asyncio, os
2from videosdk.agents import Agent, AgentSession, CascadingPipeline, JobContext, RoomOptions, WorkerJob, ConversationFlow
3from videosdk.plugins.silero import SileroVAD
4from videosdk.plugins.turn_detector import TurnDetector, pre_download_model
5from videosdk.plugins.deepgram import DeepgramSTT
6from videosdk.plugins.openai import OpenAILLM
7from videosdk.plugins.elevenlabs import ElevenLabsTTS
8from typing import AsyncIterator
9
10# Pre-downloading the Turn Detector model
11pre_download_model()
12
13agent_instructions = "You are an AI Voice Agent specialized in the astrology industry. Your persona is that of a knowledgeable and friendly astrology guide. Your primary capabilities include providing daily horoscopes, explaining astrological signs and their characteristics, and offering insights into astrological compatibility. You can also answer general questions about astrology and its history. However, you must clearly state that your insights are for entertainment purposes only and should not be considered as professional advice. You are not a certified astrologer, and users should consult a professional for personalized astrological readings. Always maintain a friendly and respectful tone, and ensure user privacy by not storing any personal data."
14
15class MyVoiceAgent(Agent):
16    def __init__(self):
17        super().__init__(instructions=agent_instructions)
18    async def on_enter(self): await self.session.say("Hello! How can I help?")
19    async def on_exit(self): await self.session.say("Goodbye!")
20
21async def start_session(context: JobContext):
22    # Create agent and conversation flow
23    agent = MyVoiceAgent()
24    conversation_flow = ConversationFlow(agent)
25
26    # Create pipeline
27    pipeline = CascadingPipeline(
28        stt=DeepgramSTT(model="nova-2", language="en"),
29        llm=OpenAILLM(model="gpt-4o"),
30        tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
31        vad=SileroVAD(threshold=0.35),
32        turn_detector=TurnDetector(threshold=0.8)
33    )
34
35    session = AgentSession(
36        agent=agent,
37        pipeline=pipeline,
38        conversation_flow=conversation_flow
39    )
40
41    try:
42        await context.connect()
43        await session.start()
44        # Keep the session running until manually terminated
45        await asyncio.Event().wait()
46    finally:
47        # Clean up resources when done
48        await session.close()
49        await context.shutdown()
50
51def make_context() -> JobContext:
52    room_options = RoomOptions(
53    #  room_id="YOUR_MEETING_ID",  # Set to join a pre-created room; omit to auto-create
54        name="VideoSDK Cascaded Agent",
55        playground=True
56    )
57
58    return JobContext(room_options=room_options)
59
60if __name__ == "__main__":
61    job = WorkerJob(entrypoint=start_session, jobctx=make_context)
62    job.start()
63

Step 4.1: Generating a VideoSDK Meeting ID

To interact with our agent, we need a meeting ID. This can be generated using the VideoSDK API. Here's an example using curl:
1curl -X POST \
2  https://api.videosdk.live/v1/meetings \
3  -H "Authorization: Bearer YOUR_API_KEY" \
4  -H "Content-Type: application/json"
5

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class is where we define the behavior of our agent. It inherits from the Agent class and is initialized with specific instructions tailored for astrology.
1class MyVoiceAgent(Agent):
2    def __init__(self):
3        super().__init__(instructions=agent_instructions)
4    async def on_enter(self): await self.session.say("Hello! How can I help?")
5    async def on_exit(self): await self.session.say("Goodbye!")
6

Step 4.3: Defining the Core Pipeline

The CascadingPipeline is a crucial part of our agent, orchestrating the flow of data through STT, LLM, and TTS plugins.
1pipeline = CascadingPipeline(
2    stt=DeepgramSTT(model="nova-2", language="en"),
3    llm=OpenAILLM(model="gpt-4o"),
4    tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
5    vad=SileroVAD(threshold=0.35),
6    turn_detector=TurnDetector(threshold=0.8)
7)
8

Step 4.4: Managing the Session and Startup Logic

We manage the session and startup logic using start_session, make_context, and the main block. For more insight into managing sessions, refer to

AI voice Agent Sessions

.
1async def start_session(context: JobContext):
2    # Create agent and conversation flow
3    agent = MyVoiceAgent()
4    conversation_flow = ConversationFlow(agent)
5
6    # Create pipeline
7    pipeline = CascadingPipeline(
8        stt=DeepgramSTT(model="nova-2", language="en"),
9        llm=OpenAILLM(model="gpt-4o"),
10        tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
11        vad=SileroVAD(threshold=0.35),
12        turn_detector=TurnDetector(threshold=0.8)
13    )
14
15    session = AgentSession(
16        agent=agent,
17        pipeline=pipeline,
18        conversation_flow=conversation_flow
19    )
20
21    try:
22        await context.connect()
23        await session.start()
24        # Keep the session running until manually terminated
25        await asyncio.Event().wait()
26    finally:
27        # Clean up resources when done
28        await session.close()
29        await context.shutdown()
30
31if __name__ == "__main__":
32    job = WorkerJob(entrypoint=start_session, jobctx=make_context)
33    job.start()
34

Running and Testing the Agent

Now that we've built our agent, it's time to test it.

Step 5.1: Running the Python Script

Run the script using:
1python main.py
2

Step 5.2: Interacting with the Agent in the Playground

Once the script is running, you'll receive a playground link in the console. Use this link to interact with your agent in a simulated environment.

Advanced Features and Customizations

Extending Functionality with Custom Tools

The VideoSDK framework allows you to extend your agent's functionality with custom tools, known as function_tool. This enables you to add specialized capabilities tailored to your needs.

Exploring Other Plugins

While we've used specific plugins in this tutorial, VideoSDK supports a variety of STT, LLM, and TTS options that you can explore to enhance your agent's capabilities.

Troubleshooting Common Issues

API Key and Authentication Errors

Ensure your API keys are correctly set in the .env file. Double-check for typos or missing entries.

Audio Input/Output Problems

Verify your microphone and speaker settings. Ensure they are properly configured and compatible with the agent.

Dependency and Version Conflicts

Make sure all dependencies are installed with compatible versions. Use a virtual environment to manage packages effectively.

Conclusion

Congratulations! You've successfully built an AI voice agent for the astrology industry using the VideoSDK framework. This agent can provide horoscopes, explain astrological signs, and engage users in meaningful conversations. As next steps, consider exploring additional plugins and customizing your agent further to suit your specific needs.

Start Building With Free $20 Balance

No credit card required to start.

Want to level-up your learning? Subscribe now

Subscribe to our newsletter for more tech based insights

FAQ