Home Projects Portfolio Dashboard Export PDF Log in

Building a Real-time AI Voice Assistant: The V5 Senior Upgrade

Introduction

Developing an AI voice assistant that feels truly conversational and intelligent requires overcoming significant technical hurdles. The goal is to minimize latency, accurately interpret user intent, and maintain context over extended interactions. In the cronix project, we recently rolled out a "V5 Senior" upgrade to our Luis-IA assistant, focusing on these very challenges by integrating real-time streaming, vector memory for Retrieval Augmented Generation (RAG), and a refined user experience.

The Problem

Previous iterations of our Luis-IA assistant, while functional, faced limitations common to many voice AI systems:

  1. Latency in Speech-to-Text (STT): Reliance on batch processing for audio transcription introduced noticeable delays, hindering the fluidity of conversations.
  2. Lack of Persistent Context: The assistant struggled with long-term memory, often requiring users to repeat information or context within a single session or across different sessions.
  3. Basic Voice Activity Detection (VAD): Simple VAD led to missed user input or premature responses, impacting conversational flow.
  4. Static Interaction Flow: The assistant's response mechanism was often monolithic, lacking the nuance to provide quick confirmations for complex requests before full execution.

The Solution: Real-time, Memory-Augmented AI

The V5 Senior upgrade addresses these problems through several key architectural and feature enhancements:

Real-time Speech-to-Text with WebSockets

We replaced our blob-based STT with Deepgram Nova-2, leveraging WebSockets for near-zero latency transcription. This allows for live streaming of audio, where text is transcribed as it's spoken, drastically improving the responsiveness of the assistant. A dedicated /api/assistant/token gateway was implemented to issue short-lived, authenticated Deepgram tokens, ensuring secure and controlled access to the STT service.

// Conceptual client-side WebSocket initiation for real-time STT
const startDeepgramStream = async () => {
  const response = await fetch('/api/assistant/token');
  const { token } = await response.json();

  const ws = new WebSocket(`wss://api.deepgram.com/v1/listen?encoding=linear16&sample_rate=16000`, ['token', token]);

  ws.onopen = () => console.log('Deepgram WebSocket connected');
  ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    if (data.channel && data.channel.alternatives && data.channel.alternatives.length > 0) {
      console.log('Transcript:', data.channel.alternatives[0].transcript);
      // Update UI with live transcription (Ghost Transcript)
    }
  };
  ws.onerror = (error) => console.error('Deepgram WebSocket error:', error);
  ws.onclose = () => console.log('Deepgram WebSocket closed');

  // Assume audioStream is a MediaRecorder output or similar
  // audioStream.ondataavailable = (event) => ws.send(event.data);
};

Advanced Voice Activity Detection (VAD)

To refine the conversational experience, a 2-phase VAD system was introduced with carefully calibrated silence thresholds. This ensures the assistant accurately detects when a user begins and stops speaking, preventing interruptions and enhancing the natural flow of dialogue.

Executive Confirmation Mode

For more complex requests that might involve heavy tool calls or lengthy processing, the assistant now utilizes an "Executive Confirmation Mode." This involves delivering a brief micro-response to acknowledge the request and confirm understanding before proceeding with the full action, managing user expectations and reducing perceived wait times.

Long-Term Memory with pgvector RAG

A critical addition for intelligence was implementing long-term memory. We integrated pgvector with PostgreSQL to store vector embeddings of past interactions and relevant knowledge. GTE-small embeddings, processed via an Edge Function, convert text into numerical vectors. A MemoryService exposes an RPC (Remote Procedure Call) match_memories that uses cosine similarity and an HNSW (Hierarchical Navigable Small World) index for efficient retrieval of relevant context. This enables a Retrieval Augmented Generation (RAG) approach, where the assistant can consult its memory before formulating a response.

// Conceptual MemoryService interaction for retrieving context
interface MemoryItem {
  id: string;
  content: string;
  embedding: number[];
}

interface MemoryService {
  match_memories(queryEmbedding: number[], limit: number): Promise<MemoryItem[]>;
}

// Example usage within the Assistant Core
async function getAugmentedContext(userInput: string, memoryService: MemoryService): Promise<string> {
  // Assume an embedding function exists to convert text to vector
  const queryEmbedding = await generateEmbedding(userInput);
  const relevantMemories = await memoryService.match_memories(queryEmbedding, 5);

  let context = relevantMemories.map(m => m.content).join('\n');
  if (context) {
    context = 'Previous context:\n' + context + '\n\n';
  }
  return context + userInput;
}

Polymorphic Voice Route & VoiceVisualizer

The voice route was made polymorphic, allowing it to handle both V5 JSON text paths and legacy FormData audio inputs. On the UI front, a Siri-style VoiceVisualizer was developed using React and Framer Motion, providing real-time visual feedback of the assistant's activity with dynamic, reactive bars and a vibrant gradient.

Results After Six Months

The V5 Senior upgrade has dramatically improved the user experience of the Luis-IA assistant. Qualitative feedback indicates a significantly more natural and responsive conversational flow. The near-zero latency STT has eliminated awkward pauses, making interactions feel immediate. The introduction of long-term memory has reduced repetition and allowed for more complex, multi-turn dialogues, boosting the assistant's perceived intelligence and utility. Executive Confirmation Mode has effectively managed user expectations during intensive processing. These enhancements have transformed Luis-IA into a truly 'senior' and capable assistant.

Getting Started

  1. Embrace WebSockets for Real-time: For any real-time interaction (STT, chat, notifications), move away from request-response models to persistent WebSocket connections.
  2. Implement RAG for Context: If your AI needs to remember or reference specific information, consider a vector database (like pgvector) paired with embeddings to enable efficient Retrieval Augmented Generation.
  3. Refine VAD: Invest in advanced Voice Activity Detection to improve the naturalness of voice interactions, tailoring it to your application's specific audio environment.
  4. Manage Expectations with Micro-responses: For long-running AI tasks, provide immediate, brief confirmations to keep users informed and engaged.

Key Insight

Building an intelligent AI assistant isn't just about the 'brain'; it's equally about the nervous system – the real-time communication, contextual memory, and subtle UI cues that make interactions feel intuitive and responsive. Optimize the entire pipeline for a truly 'senior' experience.


Generated with Gitvlg.com

Building a Real-time AI Voice Assistant: The V5 Senior Upgrade
Luis Romero

Luis Romero

Author

Share: