Build an AI Voice Agent for Supply Chain

Step-by-step guide to building an AI Voice Agent for the supply chain industry using VideoSDK, complete with code examples.

Introduction to AI Voice Agents in the Supply Chain Industry

AI Voice Agents are sophisticated software systems that can interpret human speech, process the information, and respond in a conversational manner. These agents are powered by advanced technologies such as Speech-to-Text (STT), Language Learning Models (LLM), and Text-to-Speech (TTS) systems. In the context of the supply chain industry, AI Voice Agents can streamline operations by providing real-time insights, answering queries related to logistics, inventory management, and procurement processes.
In this tutorial, we will build an AI

Voice Agent

designed specifically for the supply chain industry. This agent will leverage the VideoSDK framework, which provides a robust platform for developing voice-enabled applications.

Architecture and Core Concepts

High-Level Architecture Overview

The AI

Voice Agent

operates by capturing user speech, converting it to text, processing the text to generate a response, and finally converting the response back to speech. This process involves several key components:
Diagram

Understanding Key Concepts in the VideoSDK Framework

Setting Up the Development Environment

Prerequisites

Before we begin, ensure you have Python 3.11+ installed and a VideoSDK account set up at app.videosdk.live.

Step 1: Create a Virtual Environment

Create a virtual environment to manage 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-agents videosdk-plugins
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 the 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 a knowledgeable AI Voice Agent specialized in the supply chain industry. Your primary role is to assist users by providing insights and answering questions related to supply chain management, logistics, inventory control, and procurement processes. You can offer guidance on optimizing supply chain operations, suggest best practices, and provide updates on industry trends. However, you are not a certified supply chain consultant, and users should verify critical decisions with a professional. You must include a disclaimer advising users to consult with a qualified expert for complex supply chain issues. Your responses should be concise, informative, and tailored to the supply chain context."
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

Before running the agent, you need a meeting ID. You can generate this using the VideoSDK API:
1curl -X POST \\
2  https://api.videosdk.live/v1/meetings \\
3  -H "Authorization: Bearer YOUR_API_KEY" \\
4  -H "Content-Type: application/json" \\
5  -d '{"region":"sg001"}'
6

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class is where we define the agent's behavior. It inherits from the Agent class and implements the on_enter and on_exit methods to handle session start and end events.
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 crucial as it defines the flow of data through the system. It connects the STT, LLM, and TTS plugins, allowing seamless interaction.
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, as outlined in the

AI voice Agent Sessions

.
1async def start_session(context: JobContext):
2    agent = MyVoiceAgent()
3    conversation_flow = ConversationFlow(agent)
4
5    pipeline = CascadingPipeline(
6        stt=DeepgramSTT(model="nova-2", language="en"),
7        llm=OpenAILLM(model="gpt-4o"),
8        tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
9        vad=SileroVAD(threshold=0.35),
10        turn_detector=TurnDetector(threshold=0.8)
11    )
12
13    session = AgentSession(
14        agent=agent,
15        pipeline=pipeline,
16        conversation_flow=conversation_flow
17    )
18
19    try:
20        await context.connect()
21        await session.start()
22        await asyncio.Event().wait()
23    finally:
24        await session.close()
25        await context.shutdown()
26

Running and Testing the Agent

Step 5.1: Running the Python Script

To start the agent, run the Python script:
1python main.py
2

Step 5.2: Interacting with the Agent in the Playground

Once the agent is running, you can interact with it using the

AI Agent playground

. The console will provide a link to join the session.

Advanced Features and Customizations

Extending Functionality with Custom Tools

The VideoSDK framework allows you to extend the agent's functionality by integrating custom tools and plugins to suit specific needs.

Exploring Other Plugins

While this tutorial uses specific plugins, you can explore other STT, LLM, and TTS options available in the VideoSDK ecosystem.

Troubleshooting Common Issues

API Key and Authentication Errors

Ensure your API key is correctly configured in the .env file and that you have the necessary permissions.

Audio Input/Output Problems

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

Dependency and Version Conflicts

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

Conclusion

In this tutorial, we built a fully functional AI Voice Agent tailored for the supply chain industry using the VideoSDK framework. This agent can assist with logistics, inventory management, and more. As next steps, consider exploring additional plugins and customizations to further enhance the agent's 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