Build a Conversational AI E-commerce Agent

Learn to build a conversational AI voice agent for e-commerce with our detailed tutorial using VideoSDK.

Introduction to AI Voice Agents in Conversational AI E-commerce

In today's digital age, AI voice agents are revolutionizing the e-commerce industry by providing seamless and interactive customer experiences. These agents leverage advanced technologies to understand and respond to customer queries, making online shopping more intuitive and efficient.

What is an AI

Voice Agent

?

An AI

voice agent

is a sophisticated software application designed to interact with users through voice commands. It processes spoken language, interprets the intent, and delivers appropriate responses, often using natural language processing (NLP) and machine learning techniques.

Why are they important for the Conversational AI E-commerce Industry?

In the e-commerce domain, AI voice agents play a crucial role in enhancing customer interaction. They can provide product recommendations, answer queries about products, guide users through the purchasing process, and even assist with order tracking. This not only improves customer satisfaction but also increases sales and reduces operational costs.

Core Components of a

Voice Agent

A typical AI

voice agent

consists of several core components:
  • Speech-to-Text (STT): Converts spoken language into text.
  • Large Language Model (LLM): Understands and processes the text to generate responses.
  • Text-to-Speech (TTS): Converts the generated text back into speech.
For a comprehensive understanding, refer to the

AI voice Agent core components overview

.

What You'll Build in This Tutorial

In this tutorial, you'll learn how to build a conversational AI

voice agent

tailored for the e-commerce industry using the VideoSDK framework. This agent will assist customers with their shopping needs, enhancing their overall experience.

Architecture and Core Concepts

High-Level Architecture Overview

The architecture of an AI voice agent involves a seamless flow of data from user speech to agent response. Here's how it works:
  1. User Speech: The user speaks into a microphone.
  2. Speech-to-Text (STT): The spoken words are converted into text.
  3. Large Language Model (LLM): The text is processed to understand the user's intent.
  4. Text-to-Speech (TTS): The response is generated and converted back into speech.
  5. Agent Response: The agent speaks the response to the user.
Diagram

Understanding Key Concepts in the VideoSDK Framework

Agent

The Agent class is the core component representing your AI bot. It handles interactions and manages the conversation flow.

CascadingPipeline

The

Cascading pipeline in AI voice Agents

orchestrates the flow of audio processing, moving seamlessly from STT to LLM to TTS, ensuring smooth communication.

VAD & TurnDetector

Voice

Activity Detection

(VAD) and

Turn detector for AI voice Agents

are critical for determining when the agent should listen and when it should speak, creating a natural conversational experience.

Setting Up the Development Environment

Prerequisites

Before you begin, ensure you have the following:
  • Python 3.11+
  • VideoSDK Account: Sign up at app.videosdk.live to obtain API credentials.

Step 1: Create a Virtual Environment

To maintain a clean working environment, create a virtual environment:
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
2pip install python-dotenv
3

Step 3: Configure API Keys in a .env File

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

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

Below is the complete, runnable code for your AI voice agent. We'll break it down step-by-step to understand each component.
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 Conversational AI E-commerce Assistant designed to enhance the online shopping experience. Your primary role is to assist customers by providing product recommendations, answering queries about product details, and guiding them through the purchasing process. You can also help with order tracking and provide information about shipping and return policies. However, you are not authorized to process payments or handle sensitive customer information. Always remind users to review their cart and ensure all details are correct before proceeding to checkout. You must include a disclaimer that users should contact customer support for any issues related to payment or sensitive account information. Your goal is to make the shopping experience seamless and enjoyable while ensuring customer satisfaction 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 = [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-d "{\"region\":\"sg001\"}"
5

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class extends the Agent class, providing custom behavior for entering and exiting sessions. It uses predefined instructions to guide its interactions.
1class MyVoiceAgent(Agent):
2    def __init__(self):
3        super().__init__(instructions=agent_instructions)
4    async def on_enter(self):
5        await self.session.say("Hello! How can I help?")
6    async def on_exit(self):
7        await self.session.say("Goodbye!")
8

Step 4.3: Defining the Core Pipeline

The CascadingPipeline is crucial for processing audio data. It integrates STT, LLM, TTS, VAD, and Turn Detection 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 initializes the agent session and manages the lifecycle of the conversation. The make_context function sets up the room options for the agent.
1async def start_session(context: JobContext):
2    agent = MyVoiceAgent()
3    conversation_flow = ConversationFlow(agent)
4    pipeline = CascadingPipeline(
5        stt=DeepgramSTT(model="nova-2", language="en"),
6        llm=OpenAILLM(model="gpt-4o"),
7        tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
8        vad=SileroVAD(threshold=0.35),
9        turn_detector=TurnDetector(threshold=0.8)
10    )
11    session = AgentSession(
12        agent=agent,
13        pipeline=pipeline,
14        conversation_flow=conversation_flow
15    )
16    try:
17        await context.connect()
18        await session.start()
19        await asyncio.Event().wait()
20    finally:
21        await session.close()
22        await context.shutdown()
23
24def make_context() -> JobContext:
25    room_options = RoomOptions(
26        name="VideoSDK Cascaded Agent",
27        playground=True
28    )
29    return JobContext(room_options=room_options)
30
31if __name__ == "__main__":
32    job = WorkerJob(entrypoint=start_session, jobctx=make_context)
33    job.start()
34

Running and Testing the Agent

Step 5.1: Running the Python Script

To run your agent, execute the following command in your terminal:
1python main.py
2

Step 5.2: Interacting with the Agent in the Playground

After starting the agent, you'll receive a playground URL in the console. Open this URL in your browser to interact with your AI voice agent.

Advanced Features and Customizations

Extending Functionality with Custom Tools

The VideoSDK framework allows you to extend your agent's functionality by integrating custom tools, enhancing its capabilities beyond the standard plugins.

Exploring Other Plugins

While this tutorial uses specific plugins, VideoSDK supports a variety of STT, LLM, and TTS options. Explore these to tailor your agent to specific needs.

Troubleshooting Common Issues

API Key and Authentication Errors

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

Audio Input/Output Problems

Check your microphone and speaker settings if you encounter audio issues. Ensure your device permissions are correctly set.

Dependency and Version Conflicts

Verify that all dependencies are installed with compatible versions. Use a virtual environment to manage package versions effectively.

Conclusion

Summary of What You've Built

You've successfully built a conversational AI voice agent for e-commerce using the VideoSDK framework, capable of assisting customers with their shopping needs.

Next Steps and Further Learning

Explore additional plugins and customize your agent further. Consider integrating more advanced AI models and tools to enhance its capabilities.

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