Build an AI Voice Assistant for E-commerce

Step-by-step guide to building an AI voice assistant for e-commerce using VideoSDK.

Introduction to AI Voice Agents in E-commerce

AI Voice Agents are transforming the way businesses interact with customers, especially in the e-commerce industry. These agents leverage advanced technologies to understand and respond to human speech, providing a seamless and interactive user experience.

What is an AI

Voice Agent

?

An AI

Voice Agent

is a software application that uses speech recognition, natural language processing, and speech synthesis to interact with users via voice. It listens to user queries, processes them using AI models, and responds in a natural, human-like manner.

Why are they important for the E-commerce Industry?

In the e-commerce industry, AI Voice Agents can assist customers by providing information about products, tracking orders, offering personalized shopping recommendations, and handling customer service inquiries. They enhance user engagement and improve customer satisfaction by providing quick and accurate responses.

Core Components of a

Voice Agent

  • Speech-to-Text (STT): Converts spoken language into text.
  • Large Language Model (LLM): Processes the text to understand the user's intent and generate a response.
  • Text-to-Speech (TTS): Converts the generated text response back into speech.

What You'll Build in This Tutorial

In this tutorial, you will build an AI Voice Assistant tailored for the e-commerce industry using the VideoSDK framework. This agent will handle customer queries, provide product information, and offer personalized recommendations.

Architecture and Core Concepts

High-Level Architecture Overview

The architecture of an AI

Voice Agent

involves several components working together to process user input and generate responses. The data flow begins with capturing user speech, converting it to text, processing it with an AI model, and finally converting the response back to speech.
Diagram

Understanding Key Concepts in the VideoSDK Framework

  • Agent: The core class representing your bot, responsible for managing interactions.
  • Cascading Pipeline in AI voice Agents

    :
    Manages the flow of audio processing from STT to LLM to TTS.
  • VAD & TurnDetector: These components help the agent determine when to listen and when to speak, ensuring smooth interactions.

Setting Up the Development Environment

Prerequisites

To get started, ensure you have Python 3.11+ installed and a VideoSDK account. Sign up at the VideoSDK website to access the necessary tools and API keys.

Step 1: Create a Virtual Environment

Create a virtual environment to manage your project dependencies:
1python -m venv venv
2source venv/bin/activate  # On Windows use `venv\Scripts\activate`
3

Step 2: Install Required Packages

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

Step 3: Configure API Keys in a .env File

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

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

Here is the complete code for building your AI Voice Agent:
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 Assistant specialized in the e-commerce industry. Your primary role is to assist customers with their online shopping experience. You can provide information about products, help with order tracking, and offer personalized shopping recommendations based on user preferences and browsing history. You can also assist with common customer service inquiries such as return policies and payment options. However, you are not authorized to process payments or handle sensitive customer information such as credit card details. Always remind users to visit the official website for secure transactions and further assistance. You must maintain a friendly and professional tone, ensuring a seamless and helpful interaction for the user."
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=[Silero Voice Activity Detection](https://docs.videosdk.live/ai_agents/plugins/silero-vad)(threshold=0.35),
32        turn_detector=[Turn detector for AI voice Agents](https://docs.videosdk.live/ai_agents/plugins/turn-detector)(threshold=0.8)
33    )
34
35    session = [AI voice Agent Sessions](https://docs.videosdk.live/ai_agents/core-components/agent-session)(
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 agent, you'll need a meeting ID. Use the following curl command to generate one:
1curl -X POST "https://api.videosdk.live/v1/meetings" \
2-H "Authorization: Bearer YOUR_API_KEY" \
3-H "Content-Type: application/json"
4

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class is where you define the behavior of your voice assistant. It inherits from the Agent class and uses the instructions provided to guide 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 central to processing audio data. It uses plugins for STT, LLM, TTS, VAD, and turn detection to handle the entire conversation 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 initializes the agent session, connecting the pipeline and conversation flow. The make_context function sets up the room options for testing.
1def make_context() -> JobContext:
2    room_options = RoomOptions(
3        name="VideoSDK Cascaded Agent",
4        playground=True
5    )
6    return JobContext(room_options=room_options)
7
8async def start_session(context: JobContext):
9    agent = MyVoiceAgent()
10    conversation_flow = ConversationFlow(agent)
11    pipeline = CascadingPipeline(
12        stt=DeepgramSTT(model="nova-2", language="en"),
13        llm=OpenAILLM(model="gpt-4o"),
14        tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
15        vad=SileroVAD(threshold=0.35),
16        turn_detector=TurnDetector(threshold=0.8)
17    )
18    session = AgentSession(
19        agent=agent,
20        pipeline=pipeline,
21        conversation_flow=conversation_flow
22    )
23    try:
24        await context.connect()
25        await session.start()
26        await asyncio.Event().wait()
27    finally:
28        await session.close()
29        await context.shutdown()
30

Running and Testing the Agent

Step 5.1: Running the Python Script

Run your Python script to start the agent:
1python main.py
2

Step 5.2: Interacting with the Agent in the Playground

Once the script is running, check the console for a playground link. Use this link to join the session and interact with your AI Voice Agent.

Advanced Features and Customizations

Extending Functionality with Custom Tools

You can extend your agent's capabilities by integrating custom tools using the function_tool concept, allowing for more specialized interactions.

Exploring Other Plugins

The VideoSDK framework supports various plugins for STT, LLM, and TTS. Explore options like Cartesia for STT or Google Gemini for LLM to enhance your agent.

Troubleshooting Common Issues

API Key and Authentication Errors

Ensure your API key is correctly configured in the .env file and that your VideoSDK account is active.

Audio Input/Output Problems

Check your microphone and speaker settings to ensure they are correctly configured and functioning.

Dependency and Version Conflicts

Ensure all dependencies are installed with compatible versions as specified in the documentation.

Conclusion

Summary of What You've Built

In this tutorial, you've built a functional AI Voice Assistant for the e-commerce industry using VideoSDK. This agent can handle customer queries and provide product information.

Next Steps and Further Learning

Explore additional plugins and features in the VideoSDK framework to enhance your agent's capabilities. Consider integrating more complex AI models for improved interactions.

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