@HamzaM to AI & LLMEnglish • 4 days ago

How do you use Groq or Cerebras inference APIs for sub-200ms voice assistant response latency?

message-square
0
1
How do you use Groq or Cerebras inference APIs for sub-200ms voice assistant response latency?
@HamzaM to AI & LLMEnglish • 4 days ago

Overview

Hitting sub-200ms end-to-end voice turn latency (from user speech end / turn detection to first audible TTS audio) requires treating ultra-fast LLM inference on Groq or Cerebras as only one slice of a pipelined real-time audio loop. Even when Groq or Cerebras generates tokens at hundreds to thousands of tokens per second with low time-to-first-token (TTFT), network round-trips, oversized prompts, reasoning overhead, or waiting for a full LLM reply before synthesizing speech will easily push voice latency past 200ms–1000ms+.

  • Pipeline LLM token streaming directly into sentence/clause-chunked TTS: Do not wait for completion.choices[0].message.content to finish. Stream token deltas from Groq (https://api.groq.com/openai/v1 or Groq SDK) or Cerebras (https://api.cerebras.ai/v1 or Cerebras SDK), flush short spoken clauses/sentences as soon as a natural boundary arrives, and start text-to-speech synthesis immediately on the first clause.
  • Keep prompts lean, disable unnecessary reasoning, and reuse warm connections: Sub-200ms voice turns depend on small context windows (trimmed history + concise voice system prompt), setting reasoning_effort: "none" on supported Cerebras models when reasoning is not needed for spoken replies, keeping HTTP keep-alive connections warm, and bounding max_tokens so replies stay concise and conversational.
  • Budget the full voice turn around LLM TTFT + TTS first-byte + network: If network RTT + VAD/endpointing + TTS time-to-first-audio takes ~100–150ms, the LLM must deliver its first usable token/clause very quickly—so choose fast models, avoid heavy multi-tool chains on every turn, and race/fail over between Groq and Cerebras when one experiences queue spikes.

Steps

  1. Keep the voice prompt, history, and output budget minimal: Use a short voice-first system prompt (no Markdown tables, code blocks, or long lists), keep only recent conversational turns, and set a tight max_tokens (e.g., 120–200) so the model responds concisely.
  2. Stream chat completions with low-latency settings: Call Groq (https://api.groq.com/openai/v1/chat/completions) or Cerebras (https://api.cerebras.ai/v1/chat/completions) with stream: true, reasoning_effort: "none" where supported, and a small max_tokens cap.
  3. Chunk streamed deltas on phrase/sentence boundaries for TTS: Accumulate incoming deltas and emit speech chunks as soon as a clause/sentence delimiter (., !, ?, :, ;, \n) is reached or once a small minimum character threshold is met after punctuation, sending each chunk to your streaming TTS engine immediately.
  4. Hedge or fail over across Groq and Cerebras for tail latency: Measure per-provider TTFT and error/429 rates continuously; if the primary provider exceeds a strict TTFT budget or returns 429/5xx, fall back to (or race) the secondary provider without dropping the voice turn.

Example

import OpenAI from "openai";

export interface VoiceStreamProviderConfig {
  name: "groq" | "cerebras";
  apiKey: string;
  baseURL: string;
  model: string;
  disableReasoning?: boolean;
}

/**
 * Splits streaming LLM text into short speakable phrases so TTS can begin
 * synthesizing before the full response finishes generating.
 */
export class PhraseBoundaryChunker {
  private buffer = "";

  constructor(private readonly minCharsBeforeSplit = 24) {}

  push(delta: string): string[] {
    if (!delta) return [];
    this.buffer += delta;

    const readyChunks: string[] = [];
    // Split at sentence/clause punctuation followed by whitespace or end-of-buffer
    const boundaryRegex = /([.!?…:;]+(?:\s+|\$)|\n+)/;

    while (true) {
      const match = boundaryRegex.exec(this.buffer);
      if (!match || match.index === undefined) break;

      const cutEnd = match.index + match[0].length;
      const candidate = this.buffer.slice(0, cutEnd).trim();

      if (candidate.length >= this.minCharsBeforeSplit) {
        readyChunks.push(candidate);
        this.buffer = this.buffer.slice(cutEnd);
      } else {
        // Avoid splitting tiny fragments like "Dr." or "Hi." too early unless long enough
        break;
      }
    }

    return readyChunks;
  }

  flush(): string | null {
    const remaining = this.buffer.trim();
    this.buffer = "";
    return remaining.length > 0 ? remaining : null;
  }
}

export function createLowLatencyVoiceClients(params: {
  groqApiKey: string;
  cerebrasApiKey: string;
  groqModel?: string;
  cerebrasModel?: string;
}): VoiceStreamProviderConfig[] {
  return [
    {
      name: "cerebras",
      apiKey: params.cerebrasApiKey,
      baseURL: "[https://api.cerebras.ai/v1](https://api.cerebras.ai/v1)",
      model: params.cerebrasModel ?? "qwen-3.8-27b",
      disableReasoning: true,
    },
    {
      name: "groq",
      apiKey: params.groqApiKey,
      baseURL: "[https://api.groq.com/openai/v1](https://api.groq.com/openai/v1)",
      model: params.groqModel ?? "llama-3.1-8b-instant",
      disableReasoning: false,
    },
  ];
}

/**
 * Streams a low-latency voice reply and invokes `onSpeakableChunk` as soon as
 * phrases are ready for TTS, falling back to the next provider on failure.
 */
export async function streamVoiceReplyWithFailover(params: {
  providers: VoiceStreamProviderConfig[];
  systemPrompt: string;
  recentMessages: Array<{ role: "user" | "assistant"; content: string }>;
  onFirstTokenMs?: (ms: number, providerName: string) => void;
  onSpeakableChunk: (phrase: string, meta: { provider: string; isFinal: boolean }) => Promise<void> | void;
  maxTokens?: number;
}): Promise<{ providerUsed: string; ttftMs: number; fullText: string }> {
  const maxTokens = params.maxTokens ?? 160;
  let lastError: unknown;

  for (const provider of params.providers) {
    const startMs = performance.now();
    let firstTokenRecorded = false;
    let ttftMs = 0;
    let fullText = "";

    const client = new OpenAI({
      apiKey: provider.apiKey,
      baseURL: provider.baseURL,
      maxRetries: 0, // Let voice orchestrator fail over immediately to backup provider
    });

    const chunker = new PhraseBoundaryChunker(20);

    try {
      const requestBody: Record<string, unknown> = {
        model: provider.model,
        stream: true,
        max_tokens: maxTokens,
        temperature: 0.3,
        messages: [
          { role: "system", content: params.systemPrompt },
          ...params.recentMessages,
        ],
      };

      if (provider.name === "cerebras" && provider.disableReasoning) {
        requestBody.reasoning_effort = "none";
      }

      const stream = await client.chat.completions.create(
        requestBody as unknown as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming
      );

      for await (const part of stream) {
        const delta = part.choices[0]?.delta?.content ?? "";
        if (!delta) continue;

        if (!firstTokenRecorded) {
          firstTokenRecorded = true;
          ttftMs = Math.round(performance.now() - startMs);
          params.onFirstTokenMs?.(ttftMs, provider.name);
        }

        fullText += delta;
        const readyPhrases = chunker.push(delta);
        for (const phrase of readyPhrases) {
          await params.onSpeakableChunk(phrase, { provider: provider.name, isFinal: false });
        }
      }

      const tail = chunker.flush();
      if (tail) {
        await params.onSpeakableChunk(tail, { provider: provider.name, isFinal: true });
      }

      return { providerUsed: provider.name, ttftMs, fullText: fullText.trim() };
    } catch (err) {
      lastError = err;
    }
  }

  throw lastError ?? new Error("All low-latency voice inference providers failed.");
}

Tips

  • Measure per-stage timestamps (VAD end -> LLM TTFT -> TTS first audio byte -> client playback): Without stage-level telemetry, you cannot tell whether latency is coming from endpointing/turn detection, prompt prefill time, network RTT, or TTS synthesis.
  • Watch out for reasoning tokens and tool-calling loops eating your sub-200ms budget: Reasoning/thinking output and multi-step tool calls add extra tokens and round-trips before speech starts—disable reasoning when not needed and keep synchronous voice tools minimal or asynchronous.
  • Reuse clients and match region/network proximity: Keep long-lived clients/connections rather than recreating clients per utterance, and test from the region where your voice media/WebRTC/WebSocket server runs to minimize WAN round-trip time.