Skip to content
speak-performance-tuning logo

Speak Performance Tuning

speak-performance-tuning

Optimize Speak API performance with caching, audio preprocessing, and connection pooling. Use when experiencing slow API responses, implementing caching strategies, or optimizing request throughput for language learning applications. Trigger with phrases like "speak performance", "optimize speak"...

SKILL.md

Full skill instructions

Speak Performance Tuning

Overview

Optimize Speak API performance with caching, audio preprocessing, and connection pooling for language learning applications.

Prerequisites

  • Speak SDK installed
  • Understanding of async patterns
  • Redis or in-memory cache available (optional)
  • Performance monitoring in place

Latency Benchmarks

OperationP50P95P99
Session Start200ms500ms1000ms
Tutor Prompt150ms300ms600ms
Text Response Submit100ms250ms500ms
Audio Recognition500ms1500ms3000ms
Pronunciation Scoring800ms2000ms4000ms

Audio Optimization

Pre-processing Audio Before Upload

class AudioOptimizer {
  // Optimize audio for Speak's speech recognition
  async optimizeForRecognition(audioData: ArrayBuffer): Promise<ArrayBuffer> {
    // Convert to optimal format: 16kHz mono PCM WAV
    const audioContext = new AudioContext({ sampleRate: 16000 });
    const audioBuffer = await audioContext.decodeAudioData(audioData);

    // Convert to mono if stereo
    const monoBuffer = this.toMono(audioBuffer);

    // Normalize audio levels
    const normalizedBuffer = this.normalize(monoBuffer);

    // Remove silence at start/​end
    const trimmedBuffer = this.trimSilence(normalizedBuffer);

    // Encode as WAV
    return this.encodeWav(trimmedBuffer);
  }

  private toMono(buffer: AudioBuffer): AudioBuffer {
    if (buffer.numberOfChannels === 1) return buffer;

    const monoData = new Float32Array(buffer.length);
    const left = buffer.getChannelData(0);
    const right = buffer.getChannelData(1);

    for (let i = 0; i < buffer.length; i++) {
      monoData[i] = (left[i] + right[i]) / 2;
    }

    const ctx = new OfflineAudioContext(1, buffer.length, buffer.sampleRate);
    const newBuffer = ctx.createBuffer(1, buffer.length, buffer.sampleRate);
    newBuffer.copyToChannel(monoData, 0);
    return newBuffer;
  }

  private normalize(buffer: AudioBuffer): AudioBuffer {
    const data = buffer.getChannelData(0);
    let max = 0;

    for (let i = 0; i < data.length; i++) {
      max = Math.max(max, Math.abs(data[i]));
    }

    if (max > 0 && max < 0.9) {
      const factor = 0.9 / max;
      for (let i = 0; i < data.length; i++) {
        data[i] *= factor;
      }
    }

    return buffer;
  }

  private trimSilence(buffer: AudioBuffer, threshold = 0.01): AudioBuffer {
    const data = buffer.getChannelData(0);
    let start = 0;
    let end = data.length;

    // Find start
    for (let i = 0; i < data.length; i++) {
      if (Math.abs(data[i]) > threshold) {
        start = Math.max(0, i - 1000); // Keep small buffer
        break;
      }
    }

    // Find end
    for (let i = data.length - 1; i >= 0; i--) {
      if (Math.abs(data[i]) > threshold) {
        end = Math.min(data.length, i + 1000);
        break;
      }
    }

    const trimmedLength = end - start;
    const ctx = new OfflineAudioContext(1, trimmedLength, buffer.sampleRate);
    const newBuffer = ctx.createBuffer(1, trimmedLength, buffer.sampleRate);
    newBuffer.copyToChannel(data.slice(start, end), 0);
    return newBuffer;
  }
}

Streaming Audio for Real-time Recognition

class StreamingRecognizer {
  private chunks: ArrayBuffer[] = [];
  private processingPromise: Promise<void> | null = null;

  async streamAudioChunk(chunk: ArrayBuffer): Promise<PartialResult | null> {
    this.chunks.push(chunk);

    // Process in batches to reduce API calls
    if (this.chunks.length >= 5 || this.shouldProcess()) {
      return this.processAccumulated();
    }

    return null;
  }

  private async processAccumulated(): Promise<PartialResult> {
    const combinedSize = this.chunks.reduce((sum, c) => sum + c.byteLength, 0);
    const combined = new ArrayBuffer(combinedSize);
    const view = new Uint8Array(combined);

    let offset = 0;
    for (const chunk of this.chunks) {
      view.set(new Uint8Array(chunk), offset);
      offset += chunk.byteLength;
    }

    this.chunks = [];

    const result = await speakClient.speech.recognizeStream(combined);
    return result;
  }
}

Caching Strategy

Response Caching for Static Content

import { LRUCache } from 'lru-cache';

// Cache tutor prompts and audio URLs
const promptCache = new LRUCache<string, TutorPrompt>({
  max: 500,
  ttl: 60 * 60 * 1000, // 1 hour
  updateAgeOnGet: true,
});

// Cache vocabulary lookups
const vocabularyCache = new LRUCache<string, VocabularyEntry>({
  max: 10000,
  ttl: 24 * 60 * 60 * 1000, // 24 hours
});

async function getCachedVocabulary(
  word: string,
  language: string
): Promise<VocabularyEntry> {
  const key = `${language}:${word}`;
  const cached = vocabularyCache.get(key);
  if (cached) return cached;

  const entry = await speakClient.vocabulary.lookup(word, language);
  vocabularyCache.set(key, entry);
  return entry;
}

Redis Caching for Distributed Systems

import Redis from 'ioredis';

const redis = new Redis(process.env.REDIS_URL);

async function cachedWithRedis<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttlSeconds = 3600
): Promise<T> {
  const cached = await redis.get(key);
  if (cached) {
    return JSON.parse(cached);
  }

  const result = await fetcher();
  await redis.setex(key, ttlSeconds, JSON.stringify(result));
  return result;
}

// Cache user progress
async function getUserProgress(userId: string): Promise<UserProgress> {
  return cachedWithRedis(
    `speak:progress:${userId}`,
    () => speakClient.users.getProgress(userId),
    300 // 5 minutes
  );
}

Audio Asset Caching

// Pre-fetch and cache audio assets
class AudioAssetCache {
  private cache: Map<string, ArrayBuffer> = new Map();
  private preloadQueue: Set<string> = new Set();

  async preloadLessonAudio(lessonId: string): Promise<void> {
    const lesson = await speakClient.lessons.get(lessonId);

    // Pre-fetch all audio for the lesson
    const audioUrls = lesson.items.map(item => item.audioUrl);

    await Promise.all(
      audioUrls.map(async (url) => {
        if (!this.cache.has(url) && !this.preloadQueue.has(url)) {
          this.preloadQueue.add(url);
          const response = await fetch(url);
          const buffer = await response.arrayBuffer();
          this.cache.set(url, buffer);
          this.preloadQueue.delete(url);
        }
      })
    );
  }

  async getAudio(url: string): Promise<ArrayBuffer> {
    const cached = this.cache.get(url);
    if (cached) return cached;

    const response = await fetch(url);
    const buffer = await response.arrayBuffer();
    this.cache.set(url, buffer);
    return buffer;
  }
}

Connection Optimization

import { Agent } from 'https';

// Keep-alive connection pooling
const agent = new Agent({
  keepAlive: true,
  maxSockets: 10,
  maxFreeSockets: 5,
  timeout: 60000,
});

const client = new SpeakClient({
  apiKey: process.env.SPEAK_API_KEY!,
  appId: process.env.SPEAK_APP_ID!,
  httpAgent: agent,
  timeout: 30000,
});

Request Batching

import DataLoader from 'dataloader';

// Batch vocabulary lookups
const vocabularyLoader = new DataLoader<string, VocabularyEntry>(
  async (words) => {
    // Batch API call
    const results = await speakClient.vocabulary.batchLookup(words);
    return words.map(word => results.find(r => r.word === word) || null);
  },
  {
    maxBatchSize: 50,
    batchScheduleFn: callback => setTimeout(callback, 50),
  }
);

// Usage - automatically batched
const [word1, word2, word3] = await Promise.all([
  vocabularyLoader.load('hola'),
  vocabularyLoader.load('buenos'),
  vocabularyLoader.load('días'),
]);

Performance Monitoring

interface SpeakMetrics {
  operation: string;
  duration: number;
  success: boolean;
  audioSize?: number;
}

async function measuredSpeakCall<T>(
  operation: string,
  fn: () => Promise<T>,
  metadata?: Record<string, any>
): Promise<T> {
  const start = performance.now();
  try {
    const result = await fn();
    const duration = performance.now() - start;

    // Log metrics
    console.log({
      operation,
      duration,
      success: true,
      ...metadata,
    });

    // Track in metrics system
    metrics.histogram('speak_api_duration', duration, { operation });
    metrics.increment('speak_api_success', { operation });

    return result;
  } catch (error) {
    const duration = performance.now() - start;

    console.error({
      operation,
      duration,
      success: false,
      error,
      ...metadata,
    });

    metrics.histogram('speak_api_duration', duration, { operation });
    metrics.increment('speak_api_error', { operation });

    throw error;
  }
}

// Usage
const result = await measuredSpeakCall(
  'speech.recognize',
  () => speakClient.speech.recognize(audioBuffer),
  { audioSize: audioBuffer.byteLength }
);

Output

  • Reduced API latency
  • Audio preprocessing pipeline
  • Caching layer implemented
  • Request batching enabled
  • Connection pooling configured

Error Handling

IssueCauseSolution
Cache miss stormTTL expiredUse stale-while-revalidate
Audio too largeNo compressionOptimize audio format
Connection exhaustedNo poolingConfigure max sockets
Memory pressureCache too largeSet max cache entries
Batch timeoutToo many itemsReduce batch size

Examples

Quick Performance Wrapper

const withPerformance = <T>(name: string, fn: () => Promise<T>) =>
  measuredSpeakCall(name, () =>
    cachedWithRedis(`cache:${name}`, fn, 300)
  );

Resources

Next Steps

For cost optimization, see speak-cost-tuning.

More skills from Dicklesworthstone

environment-setup-guide logo
Dicklesworthstone/pi_agent_rust

environment-setup-guide

Guide developers through setting up development environments with proper tools, dependencies, and configurations

1.8K 0
View
exa-policy-guardrails logo
Dicklesworthstone/pi_agent_rust

exa-policy-guardrails

Implement Exa lint rules, policy enforcement, and automated guardrails. Use when setting up code quality rules for Exa integrations, implementing pre-commit hooks, or configuring CI policy checks for Exa best practices. Trigger with phrases like "exa policy", "exa lint", "exa guardrails", "exa be...

1.8K 0
View
documenso-ci-integration logo
Dicklesworthstone/pi_agent_rust

documenso-ci-integration

Configure CI/CD pipelines for Documenso integrations. Use when setting up automated testing, deployment pipelines, or continuous integration for Documenso projects. Trigger with phrases like "documenso CI", "documenso GitHub Actions", "documenso pipeline", "documenso automated testing".

1.8K 0
View
openrouter-model-availability logo
Dicklesworthstone/pi_agent_rust

openrouter-model-availability

Build check model availability and implement fallback chains. Use when building resilient systems or handling model outages. Trigger with phrases like 'openrouter availability', 'openrouter fallback', 'openrouter model down', 'openrouter health check'.

1.8K 0
View
langfuse-enterprise-rbac logo
Dicklesworthstone/pi_agent_rust

langfuse-enterprise-rbac

Configure Langfuse enterprise organization management and access control. Use when implementing team access controls, configuring organization settings, or setting up role-based permissions for Langfuse projects. Trigger with phrases like "langfuse RBAC", "langfuse teams", "langfuse organization"...

1.8K 0
View
cursor-compliance-audit logo
Dicklesworthstone/pi_agent_rust

cursor-compliance-audit

Execute compliance and security auditing for Cursor usage. Triggers on "cursor compliance", "cursor audit", "cursor security review", "cursor soc2", "cursor gdpr". Use when analyzing or auditing cursor compliance audit. Trigger with phrases like "cursor compliance audit", "cursor audit", "cursor".

1.8K 0
View
apollo-ci-integration logo
Dicklesworthstone/pi_agent_rust

apollo-ci-integration

Configure Apollo.io CI/CD integration. Use when setting up automated testing, continuous integration, or deployment pipelines for Apollo integrations. Trigger with phrases like "apollo ci", "apollo github actions", "apollo pipeline", "apollo ci/cd", "apollo automated tests".

1.8K 0
View
python-script logo
Dicklesworthstone/pi_agent_rust

python-script

Create robust Python automation with full logging and safety checks. Use when tasks need complex data processing, authenticated API work, conditional file operations, or error handling beyond simple shell commands.

1.8K 0
View
posthog-multi-env-setup logo
Dicklesworthstone/pi_agent_rust

posthog-multi-env-setup

Configure PostHog across development, staging, and production environments. Use when setting up multi-environment deployments, configuring per-environment secrets, or implementing environment-specific PostHog configurations. Trigger with phrases like "posthog environments", "posthog staging", "po...

1.8K 0
View
ai-agents-architect logo
Dicklesworthstone/pi_agent_rust

ai-agents-architect

Expert in designing and building autonomous AI agents. Masters tool use, memory systems, planning strategies, and multi-agent orchestration. Use when: build agent, AI agent, autonomous agent, tool use, function calling.

1.8K 0
View
insecure-deserialization-checker logo
Dicklesworthstone/pi_agent_rust

insecure-deserialization-checker

Validate insecure deserialization checker operations. Auto-activating skill for Security Fundamentals. Triggers on: insecure deserialization checker, insecure deserialization checker Part of the Security Fundamentals skill category. Use when working with insecure deserialization checker functiona...

1.8K 0
View
path-traversal-finder logo
Dicklesworthstone/pi_agent_rust

path-traversal-finder

Manage path traversal finder operations. Auto-activating skill for Security Fundamentals. Triggers on: path traversal finder, path traversal finder Part of the Security Fundamentals skill category. Use when working with path traversal finder functionality. Trigger with phrases like "path traversa...

1.8K 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View