Conversational AI in Retail: Build a Voice Agent

Step-by-step guide to building a conversational AI voice agent for retail using VideoSDK.

Introduction to AI Voice Agents in Conversational AI in Retail

In the rapidly evolving landscape of retail, AI Voice Agents are becoming indispensable tools. These agents are designed to interact with customers through natural language, providing assistance, information, and a seamless shopping experience. But what exactly is an AI

Voice Agent

, and why is it crucial for the retail industry?

What is an AI

Voice Agent

?

An AI

Voice Agent

is a software application that uses artificial intelligence to interact with users through voice commands. It processes spoken language, understands the intent, and responds in a conversational manner. These agents leverage technologies like Speech-to-Text (STT), Language Learning Models (LLM), and Text-to-Speech (TTS) to facilitate smooth communication.

Why are they important for the Conversational AI in Retail Industry?

In retail, AI Voice Agents enhance customer service by providing instant responses to queries about products, availability, and promotions. They offer personalized recommendations and can handle multiple customer interactions simultaneously, improving efficiency and customer satisfaction. By integrating AI Voice Agents, retailers can offer a more interactive and engaging shopping experience.

Core Components of a

Voice Agent

  • Speech-to-Text (STT): Converts spoken language into text.
  • Language Learning Models (LLM): Understands and processes the text to determine the appropriate response.
  • Text-to-Speech (TTS): Converts the response text back into speech.
For a comprehensive understanding of these elements, refer to the

AI voice Agent core components overview

.

What You'll Build in This Tutorial

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

voice agent

tailored for the retail environment using the VideoSDK framework. You'll learn how to set up the development environment, create a custom agent, define the core processing pipeline, and test your agent in a real-world scenario.

Architecture and Core Concepts

High-Level Architecture Overview

The architecture of an AI

Voice Agent

involves a seamless flow of data from the user's speech to the agent's response. Here's a high-level overview of how this process works:
  1. User Speech: The user speaks into the system.
  2. Voice

    Activity Detection

    (VAD):
    Detects when the user is speaking.
  3. Speech-to-Text (STT): Converts the speech into text.
  4. Language Learning Model (LLM): Processes the text to understand the user's intent.
  5. Text-to-Speech (TTS): Converts the response text into speech.
  6. Agent Response: The agent responds to the user.
Diagram

Understanding Key Concepts in the VideoSDK Framework

  • Agent: The core class representing your bot, responsible for handling 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: Tools that help the agent know when to listen and when to speak.

Setting Up the Development Environment

Prerequisites

To get started, you'll need Python 3.11+ and a VideoSDK account, which you can create at app.videosdk.live. Ensure you have access to the VideoSDK dashboard to generate necessary credentials.

Step 1: Create a Virtual Environment

Create a virtual environment to manage dependencies:
1python3 -m venv retail-agent-env
2source retail-agent-env/bin/activate  # On Windows use `retail-agent-env\\Scripts\\activate`
3

Step 2: Install Required Packages

Install the necessary Python packages using pip:
1pip install videosdk
2pip install asyncio
3

Step 3: Configure API Keys in a .env file

Create a .env file in your project directory to securely store your API keys:
1VIDEOSDK_API_KEY=your_api_key_here
2

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

First, let's look at the complete code that we'll be building and understanding step-by-step:
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 a friendly and knowledgeable retail assistant AI designed to enhance customer experience in retail environments. Your primary role is to assist customers by providing information about products, helping them find items, and offering personalized recommendations based on their preferences and purchase history. You can also assist with checking product availability, store hours, and ongoing promotions. However, you are not authorized to process payments or handle sensitive customer information such as credit card details. Always remind customers to consult a human staff member for any financial transactions or if they require further assistance beyond your capabilities. Your goal is to make shopping more convenient and enjoyable for customers while respecting their privacy and security."
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 your AI Voice Agent, you'll need a meeting ID. You can generate one using the VideoSDK API. Here's an example using curl:
1curl -X POST https://api.videosdk.live/v1/meetings \
2-H "Authorization: Bearer YOUR_API_KEY" \
3-H "Content-Type: application/json" \
4-d '{}'
5

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class is where you define the behavior of your AI Voice Agent. It inherits from the Agent class and uses the agent_instructions to guide its interactions.
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 the heart of the agent's processing capabilities. It connects the STT, LLM, TTS, VAD, and TurnDetector plugins to create a seamless conversational flow.
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

The start_session function manages the lifecycle of the agent session, including starting, running, and shutting down the session. For detailed insights, 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
The make_context function creates the job context with room options, enabling the agent to join a meeting room.
1def make_context() -> JobContext:
2    room_options = RoomOptions(
3    #  room_id="YOUR_MEETING_ID",  # Set to join a pre-created room; omit to auto-create
4        name="VideoSDK Cascaded Agent",
5        playground=True
6    )
7
8    return JobContext(room_options=room_options)
9
Finally, the main block starts the worker job, initializing the agent session.
1if __name__ == "__main__":
2    job = WorkerJob(entrypoint=start_session, jobctx=make_context)
3    job.start()
4

Running and Testing the Agent

Step 5.1: Running the Python Script

To run your AI Voice Agent, execute the Python script:
1python main.py
2

Step 5.2: Interacting with the Agent in the Playground

Once the script is running, you'll see a playground link in the console. Open this link in your browser to interact with your AI Voice Agent. You can speak to the agent and receive responses in real-time.

Advanced Features and Customizations

Extending Functionality with Custom Tools

The VideoSDK framework allows you to extend your agent's functionality by integrating custom tools. This enables you to add specific capabilities tailored to your retail environment.

Exploring Other Plugins

While this tutorial uses specific plugins, VideoSDK supports various STT, LLM, and TTS options. Explore these plugins to find the best fit for your needs.

Troubleshooting Common Issues

API Key and Authentication Errors

Ensure your API keys are correctly configured in the .env file and that you have the necessary permissions on the VideoSDK dashboard.

Audio Input/Output Problems

Check your microphone and speaker settings to ensure they're properly configured and functioning.

Dependency and Version Conflicts

Make sure all dependencies are installed and compatible with your Python version. Use a virtual environment to manage packages.

Conclusion

Summary of What You've Built

In this tutorial, you've built a fully functional AI Voice Agent tailored for the retail industry using the VideoSDK framework. You've learned about the core components, set up your development environment, and explored advanced features.

Next Steps and Further Learning

Continue exploring the VideoSDK framework and experiment with different plugins to enhance your agent's capabilities. Consider integrating additional features like sentiment analysis or multi-language support to further improve customer interactions.

Get 10,000 Free Minutes Every Months

No credit card required to start.

Want to level-up your learning? Subscribe now

Subscribe to our newsletter for more tech based insights

FAQ