[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6FA4E5M2DVGCTAEHGN4Q6MZ":3,"skill-same:01M6FA4E5M2DVGCTAEHGN4Q6MZ":76},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":53,"commitSha":54,"skillDirectory":55,"forksCount":56,"repositoryHtmlUrl":57,"repositoryHomepageUrl":58,"ownerHtmlUrl":59,"ownerBlogUrl":6,"ownerDescription":60,"updatedAt":61,"install":62,"resources":75},"01M6FA4E5M2DVGCTAEHGN4Q6MZ","elevenlabs-reference-architecture",null,"Implement ElevenLabs reference architecture for production TTS\u002Fvoice applications.\nUse when designing new ElevenLabs integrations, reviewing project structure,\nor building a scalable audio generation service.\nTrigger: \"elevenlabs architecture\", \"elevenlabs project structure\",\n\"how to organize elevenlabs\", \"TTS service architecture\",\n\"elevenlabs design patterns\", \"voice API architecture\".","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fjeremylongshore\u002Fclaude-code-plugins-plus-skills\u002Felevenlabs-reference-architecture\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"elevenlabs","elevenlabs reference architecture","reference","architecture","patterns","project structure","Scalable","Audio Generation","how to","io","project","structure","organize","code","design","design patterns","read","how","Audio","api","2026-11-10 10:12:30",false,"---\nname: elevenlabs-reference-architecture\ndescription: |\n  Implement ElevenLabs reference architecture for production TTS\u002Fvoice applications.\n  Use when designing new ElevenLabs integrations, reviewing project structure,\n  or building a scalable audio generation service.\n  Trigger: \"elevenlabs architecture\", \"elevenlabs project structure\",\n  \"how to organize elevenlabs\", \"TTS service architecture\",\n  \"elevenlabs design patterns\", \"voice API architecture\".\nallowed-tools: Read, Grep\nversion: 1.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ntags: [saas, voice, ai, elevenlabs, architecture, patterns]\ncompatible-with: claude-code\n---\n\n# ElevenLabs Reference Architecture\n\n## Overview\n\nProduction-ready architecture for ElevenLabs TTS\u002Fvoice applications. Covers project layout, service layers, caching, streaming, and multi-model orchestration.\n\n## Prerequisites\n\n- Understanding of layered architecture patterns\n- ElevenLabs SDK knowledge (see `elevenlabs-sdk-patterns`)\n- TypeScript project with async patterns\n- Redis (optional, for distributed caching)\n\n## Instructions\n\n### Step 1: Project Structure\n\n```\nmy-elevenlabs-service\u002F\n├── src\u002F\n│   ├── elevenlabs\u002F\n│   │   ├── client.ts            # Singleton client with retry config\n│   │   ├── config.ts            # Environment-aware configuration\n│   │   ├── models.ts            # Model selection logic\n│   │   ├── errors.ts            # Error classification (see sdk-patterns)\n│   │   └── types.ts             # TypeScript interfaces\n│   ├── services\u002F\n│   │   ├── tts-service.ts       # Text-to-Speech orchestration\n│   │   ├── voice-service.ts     # Voice management (clone, list, settings)\n│   │   ├── audio-service.ts     # SFX, isolation, transcription\n│   │   └── cache-service.ts     # Audio caching layer\n│   ├── api\u002F\n│   │   ├── routes\u002F\n│   │   │   ├── tts.ts           # POST \u002Fapi\u002Ftts\n│   │   │   ├── voices.ts        # GET\u002FPOST \u002Fapi\u002Fvoices\n│   │   │   ├── webhooks.ts      # POST \u002Fwebhooks\u002Felevenlabs\n│   │   │   └── health.ts        # GET \u002Fhealth\n│   │   └── middleware\u002F\n│   │       ├── rate-limit.ts    # Request throttling\n│   │       └── auth.ts          # Your app's auth (not ElevenLabs auth)\n│   ├── queue\u002F\n│   │   ├── tts-queue.ts         # Async TTS job processing\n│   │   └── workers.ts           # Queue workers\n│   └── monitoring\u002F\n│       ├── metrics.ts           # Latency, error rate, quota tracking\n│       └── alerts.ts            # Budget and health alerts\n├── tests\u002F\n│   ├── unit\u002F\n│   │   ├── tts-service.test.ts\n│   │   └── cache-service.test.ts\n│   └── integration\u002F\n│       └── tts-smoke.test.ts\n├── config\u002F\n│   ├── development.json\n│   ├── staging.json\n│   └── production.json\n└── .env.example\n```\n\n### Step 2: Configuration Layer\n\n```typescript\n\u002F\u002F src\u002Felevenlabs\u002Fconfig.ts\nexport interface ElevenLabsConfig {\n  apiKey: string;\n  environment: \"development\" | \"staging\" | \"production\";\n  defaults: {\n    modelId: string;\n    voiceId: string;\n    outputFormat: string;\n    voiceSettings: {\n      stability: number;\n      similarity_boost: number;\n      style: number;\n      speed: number;\n    };\n  };\n  performance: {\n    maxConcurrency: number;\n    timeoutMs: number;\n    maxRetries: number;\n  };\n  cache: {\n    enabled: boolean;\n    maxSizeMB: number;\n    ttlSeconds: number;\n  };\n}\n\nconst ENV_CONFIGS: Record\u003Cstring, Partial\u003CElevenLabsConfig>> = {\n  development: {\n    defaults: {\n      modelId: \"eleven_flash_v2_5\",    \u002F\u002F Cheap + fast for dev\n      voiceId: \"21m00Tcm4TlvDq8ikWAM\", \u002F\u002F Rachel\n      outputFormat: \"mp3_22050_32\",     \u002F\u002F Small files\n      voiceSettings: { stability: 0.5, similarity_boost: 0.75, style: 0, speed: 1 },\n    },\n    performance: { maxConcurrency: 2, timeoutMs: 30_000, maxRetries: 1 },\n    cache: { enabled: true, maxSizeMB: 50, ttlSeconds: 3600 },\n  },\n  production: {\n    defaults: {\n      modelId: \"eleven_multilingual_v2\", \u002F\u002F High quality for prod\n      voiceId: \"21m00Tcm4TlvDq8ikWAM\",\n      outputFormat: \"mp3_44100_128\",     \u002F\u002F High quality\n      voiceSettings: { stability: 0.5, similarity_boost: 0.75, style: 0, speed: 1 },\n    },\n    performance: { maxConcurrency: 10, timeoutMs: 60_000, maxRetries: 3 },\n    cache: { enabled: true, maxSizeMB: 500, ttlSeconds: 86_400 },\n  },\n};\n\nexport function loadConfig(): ElevenLabsConfig {\n  const env = process.env.NODE_ENV || \"development\";\n  const envConfig = ENV_CONFIGS[env] || ENV_CONFIGS.development;\n\n  return {\n    apiKey: process.env.ELEVENLABS_API_KEY!,\n    environment: env as any,\n    ...envConfig,\n  } as ElevenLabsConfig;\n}\n```\n\n### Step 3: TTS Service Layer\n\n```typescript\n\u002F\u002F src\u002Fservices\u002Ftts-service.ts\nimport { ElevenLabsClient } from \"@elevenlabs\u002Felevenlabs-js\";\nimport PQueue from \"p-queue\";\nimport { loadConfig } from \"..\u002Felevenlabs\u002Fconfig\";\nimport { classifyError } from \"..\u002Felevenlabs\u002Ferrors\";\n\nexport class TTSService {\n  private client: ElevenLabsClient;\n  private queue: PQueue;\n  private config: ReturnType\u003Ctypeof loadConfig>;\n\n  constructor() {\n    this.config = loadConfig();\n    this.client = new ElevenLabsClient({\n      apiKey: this.config.apiKey,\n      maxRetries: this.config.performance.maxRetries,\n      timeoutInSeconds: this.config.performance.timeoutMs \u002F 1000,\n    });\n    this.queue = new PQueue({\n      concurrency: this.config.performance.maxConcurrency,\n    });\n  }\n\n  async generate(text: string, options?: {\n    voiceId?: string;\n    modelId?: string;\n    outputFormat?: string;\n    streaming?: boolean;\n  }): Promise\u003CReadableStream | Buffer> {\n    const voiceId = options?.voiceId || this.config.defaults.voiceId;\n    const modelId = options?.modelId || this.config.defaults.modelId;\n    const format = options?.outputFormat || this.config.defaults.outputFormat;\n\n    return this.queue.add(async () => {\n      const start = performance.now();\n\n      try {\n        if (options?.streaming) {\n          return await this.client.textToSpeech.stream(voiceId, {\n            text,\n            model_id: modelId,\n            output_format: format,\n            voice_settings: this.config.defaults.voiceSettings,\n          });\n        }\n\n        const audio = await this.client.textToSpeech.convert(voiceId, {\n          text,\n          model_id: modelId,\n          output_format: format,\n          voice_settings: this.config.defaults.voiceSettings,\n        });\n\n        const latency = performance.now() - start;\n        console.log(`[TTS] ${text.length} chars, ${modelId}, ${latency.toFixed(0)}ms`);\n        return audio;\n      } catch (error) {\n        throw classifyError(error);\n      }\n    }) as Promise\u003CReadableStream | Buffer>;\n  }\n\n  \u002F\u002F Split long text into chunks with prosody context\n  async generateLongText(text: string, voiceId?: string): Promise\u003CBuffer[]> {\n    const chunks = this.splitText(text, 4500); \u002F\u002F Stay under 5000 limit\n    const results: Buffer[] = [];\n\n    for (let i = 0; i \u003C chunks.length; i++) {\n      const audio = await this.generate(chunks[i], {\n        voiceId,\n        \u002F\u002F Pass context for natural prosody across chunks\n      });\n      results.push(audio as Buffer);\n    }\n\n    return results;\n  }\n\n  private splitText(text: string, maxChars: number): string[] {\n    const chunks: string[] = [];\n    const sentences = text.match(\u002F[^.!?]+[.!?]+\u002Fg) || [text];\n    let current = \"\";\n\n    for (const sentence of sentences) {\n      if ((current + sentence).length > maxChars) {\n        if (current) chunks.push(current.trim());\n        current = sentence;\n      } else {\n        current += sentence;\n      }\n    }\n    if (current) chunks.push(current.trim());\n    return chunks;\n  }\n}\n```\n\n### Step 4: Voice Management Service\n\n```typescript\n\u002F\u002F src\u002Fservices\u002Fvoice-service.ts\nexport class VoiceService {\n  private client: ElevenLabsClient;\n\n  constructor(client: ElevenLabsClient) {\n    this.client = client;\n  }\n\n  async listVoices(filter?: { category?: \"premade\" | \"cloned\" | \"generated\" }) {\n    const { voices } = await this.client.voices.getAll();\n    if (filter?.category) {\n      return voices.filter(v => v.category === filter.category);\n    }\n    return voices;\n  }\n\n  async cloneVoice(name: string, description: string, audioFiles: NodeJS.ReadableStream[]) {\n    return this.client.voices.add({\n      name,\n      description,\n      files: audioFiles,\n    });\n  }\n\n  async getVoiceSettings(voiceId: string) {\n    return this.client.voices.getSettings(voiceId);\n  }\n\n  async updateVoiceSettings(voiceId: string, settings: {\n    stability: number;\n    similarity_boost: number;\n  }) {\n    return this.client.voices.editSettings(voiceId, settings);\n  }\n\n  async deleteVoice(voiceId: string) {\n    return this.client.voices.delete(voiceId);\n  }\n}\n```\n\n### Step 5: Data Flow Diagram\n\n```\n                         ┌──────────────┐\n                         │   Client     │\n                         │  (Browser\u002F   │\n                         │   Mobile)    │\n                         └──────┬───────┘\n                                │\n                         ┌──────▼───────┐\n                         │   API Layer  │\n                         │   \u002Fapi\u002Ftts   │\n                         │   \u002Fapi\u002Fvoice │\n                         └──────┬───────┘\n                                │\n                    ┌───────────┼───────────┐\n                    │           │           │\n             ┌──────▼──┐ ┌─────▼─────┐ ┌──▼──────┐\n             │  Cache   │ │   TTS     │ │  Voice  │\n             │ Service  │ │  Service  │ │ Service │\n             └──────┬───┘ └─────┬─────┘ └────────┘\n                    │           │\n              ┌─────▼─┐  ┌─────▼──────────┐\n              │ Redis\u002F │  │ Concurrency    │\n              │ LRU    │  │ Queue (p-queue)│\n              └────────┘  └─────┬──────────┘\n                                │\n                         ┌──────▼───────┐\n                         │  ElevenLabs  │\n                         │  Client SDK  │\n                         │  (singleton) │\n                         └──────┬───────┘\n                                │\n                    ┌───────────┼───────────┐\n                    │           │           │\n             ┌──────▼──┐ ┌─────▼─────┐ ┌──▼──────┐\n             │ \u002Fv1\u002Ftts  │ │ \u002Fv1\u002Fvoices│ │ \u002Fv1\u002Fsfx │\n             │ REST\u002FWS  │ │  REST     │ │  REST   │\n             └──────────┘ └───────────┘ └─────────┘\n                    ElevenLabs API (api.elevenlabs.io)\n```\n\n### Step 6: Health Check Composition\n\n```typescript\n\u002F\u002F src\u002Fapi\u002Froutes\u002Fhealth.ts\nexport async function healthCheck() {\n  const checks = await Promise.allSettled([\n    checkElevenLabsConnectivity(),\n    checkQuotaStatus(),\n    checkCacheHealth(),\n  ]);\n\n  const elevenlabs = checks[0].status === \"fulfilled\" ? checks[0].value : null;\n  const quota = checks[1].status === \"fulfilled\" ? checks[1].value : null;\n  const cache = checks[2].status === \"fulfilled\" ? checks[2].value : null;\n\n  const degraded = !elevenlabs || (quota && quota.pctUsed > 90);\n\n  return {\n    status: !elevenlabs ? \"unhealthy\" : degraded ? \"degraded\" : \"healthy\",\n    services: { elevenlabs, quota, cache },\n    timestamp: new Date().toISOString(),\n  };\n}\n```\n\n## Architecture Decisions\n\n| Decision | Choice | Rationale |\n|----------|--------|-----------|\n| Client pattern | Singleton | One connection pool, shared retry config |\n| Concurrency | p-queue | Respects plan limits, prevents 429 |\n| Caching | LRU (local) or Redis (distributed) | Repeated content is common in TTS |\n| Long text | Sentence-boundary splitting | Preserves natural speech prosody |\n| Error handling | Classification + retry | Different strategies for 429 vs 401 vs 500 |\n| Model selection | Environment-based | Flash in dev (cheap), Multilingual in prod (quality) |\n| Streaming | HTTP streaming + WebSocket | HTTP for simple, WS for LLM integration |\n\n## Error Handling\n\n| Issue | Cause | Solution |\n|-------|-------|----------|\n| Circular dependencies | Wrong layering | Services depend on client, never reverse |\n| Cold start latency | Client initialization | Pre-warm in server startup |\n| Memory pressure | Unbounded audio cache | Set `maxSizeMB` on cache |\n| Type errors | SDK version mismatch | Pin SDK version in package.json |\n\n## Resources\n\n- [ElevenLabs API Reference](https:\u002F\u002Felevenlabs.io\u002Fdocs\u002Fapi-reference\u002Fintroduction)\n- [ElevenLabs SDK Source](https:\u002F\u002Fgithub.com\u002Felevenlabs\u002Felevenlabs-js)\n- [p-queue](https:\u002F\u002Fgithub.com\u002Fsindresorhus\u002Fp-queue)\n- [LRU Cache](https:\u002F\u002Fgithub.com\u002Fisaacs\u002Fnode-lru-cache)\n\n## Next Steps\n\nStart with `elevenlabs-install-auth` for setup, then apply this architecture. Use `elevenlabs-core-workflow-a` and `elevenlabs-core-workflow-b` for feature implementation.\n\n","# ElevenLabs Reference Architecture\n\n## Overview\n\nProduction-ready architecture for ElevenLabs TTS\u002Fvoice applications. Covers project layout, service layers, caching, streaming, and multi-model orchestration.\n\n## Prerequisites\n\n- Understanding of layered architecture patterns\n- ElevenLabs SDK knowledge (see `elevenlabs-sdk-patterns`)\n- TypeScript project with async patterns\n- Redis (optional, for distributed caching)\n\n## Instructions\n\n### Step 1: Project Structure\n\n```\nmy-elevenlabs-service\u002F\n├── src\u002F\n│   ├── elevenlabs\u002F\n│   │   ├── client.ts            # Singleton client with retry config\n│   │   ├── config.ts            # Environment-aware configuration\n│   │   ├── models.ts            # Model selection logic\n│   │   ├── errors.ts            # Error classification (see sdk-patterns)\n│   │   └── types.ts             # TypeScript interfaces\n│   ├── services\u002F\n│   │   ├── tts-service.ts       # Text-to-Speech orchestration\n│   │   ├── voice-service.ts     # Voice management (clone, list, settings)\n│   │   ├── audio-service.ts     # SFX, isolation, transcription\n│   │   └── cache-service.ts     # Audio caching layer\n│   ├── api\u002F\n│   │   ├── routes\u002F\n│   │   │   ├── tts.ts           # POST \u002Fapi\u002Ftts\n│   │   │   ├── voices.ts        # GET\u002FPOST \u002Fapi\u002Fvoices\n│   │   │   ├── webhooks.ts      # POST \u002Fwebhooks\u002Felevenlabs\n│   │   │   └── health.ts        # GET \u002Fhealth\n│   │   └── middleware\u002F\n│   │       ├── rate-limit.ts    # Request throttling\n│   │       └── auth.ts          # Your app's auth (not ElevenLabs auth)\n│   ├── queue\u002F\n│   │   ├── tts-queue.ts         # Async TTS job processing\n│   │   └── workers.ts           # Queue workers\n│   └── monitoring\u002F\n│       ├── metrics.ts           # Latency, error rate, quota tracking\n│       └── alerts.ts            # Budget and health alerts\n├── tests\u002F\n│   ├── unit\u002F\n│   │   ├── tts-service.test.ts\n│   │   └── cache-service.test.ts\n│   └── integration\u002F\n│       └── tts-smoke.test.ts\n├── config\u002F\n│   ├── development.json\n│   ├── staging.json\n│   └── production.json\n└── .env.example\n```\n\n### Step 2: Configuration Layer\n\n```typescript\n\u002F\u002F src\u002Felevenlabs\u002Fconfig.ts\nexport interface ElevenLabsConfig {\n  apiKey: string;\n  environment: \"development\" | \"staging\" | \"production\";\n  defaults: {\n    modelId: string;\n    voiceId: string;\n    outputFormat: string;\n    voiceSettings: {\n      stability: number;\n      similarity_boost: number;\n      style: number;\n      speed: number;\n    };\n  };\n  performance: {\n    maxConcurrency: number;\n    timeoutMs: number;\n    maxRetries: number;\n  };\n  cache: {\n    enabled: boolean;\n    maxSizeMB: number;\n    ttlSeconds: number;\n  };\n}\n\nconst ENV_CONFIGS: Record\u003Cstring, Partial\u003CElevenLabsConfig>> = {\n  development: {\n    defaults: {\n      modelId: \"eleven_flash_v2_5\",    \u002F\u002F Cheap + fast for dev\n      voiceId: \"21m00Tcm4TlvDq8ikWAM\", \u002F\u002F Rachel\n      outputFormat: \"mp3_22050_32\",     \u002F\u002F Small files\n      voiceSettings: { stability: 0.5, similarity_boost: 0.75, style: 0, speed: 1 },\n    },\n    performance: { maxConcurrency: 2, timeoutMs: 30_000, maxRetries: 1 },\n    cache: { enabled: true, maxSizeMB: 50, ttlSeconds: 3600 },\n  },\n  production: {\n    defaults: {\n      modelId: \"eleven_multilingual_v2\", \u002F\u002F High quality for prod\n      voiceId: \"21m00Tcm4TlvDq8ikWAM\",\n      outputFormat: \"mp3_44100_128\",     \u002F\u002F High quality\n      voiceSettings: { stability: 0.5, similarity_boost: 0.75, style: 0, speed: 1 },\n    },\n    performance: { maxConcurrency: 10, timeoutMs: 60_000, maxRetries: 3 },\n    cache: { enabled: true, maxSizeMB: 500, ttlSeconds: 86_400 },\n  },\n};\n\nexport function loadConfig(): ElevenLabsConfig {\n  const env = process.env.NODE_ENV || \"development\";\n  const envConfig = ENV_CONFIGS[env] || ENV_CONFIGS.development;\n\n  return {\n    apiKey: process.env.ELEVENLABS_API_KEY!,\n    environment: env as any,\n    ...envConfig,\n  } as ElevenLabsConfig;\n}\n```\n\n### Step 3: TTS Service Layer\n\n```typescript\n\u002F\u002F src\u002Fservices\u002Ftts-service.ts\nimport { ElevenLabsClient } from \"@elevenlabs\u002Felevenlabs-js\";\nimport PQueue from \"p-queue\";\nimport { loadConfig } from \"..\u002Felevenlabs\u002Fconfig\";\nimport { classifyError } from \"..\u002Felevenlabs\u002Ferrors\";\n\nexport class TTSService {\n  private client: ElevenLabsClient;\n  private queue: PQueue;\n  private config: ReturnType\u003Ctypeof loadConfig>;\n\n  constructor() {\n    this.config = loadConfig();\n    this.client = new ElevenLabsClient({\n      apiKey: this.config.apiKey,\n      maxRetries: this.config.performance.maxRetries,\n      timeoutInSeconds: this.config.performance.timeoutMs \u002F 1000,\n    });\n    this.queue = new PQueue({\n      concurrency: this.config.performance.maxConcurrency,\n    });\n  }\n\n  async generate(text: string, options?: {\n    voiceId?: string;\n    modelId?: string;\n    outputFormat?: string;\n    streaming?: boolean;\n  }): Promise\u003CReadableStream | Buffer> {\n    const voiceId = options?.voiceId || this.config.defaults.voiceId;\n    const modelId = options?.modelId || this.config.defaults.modelId;\n    const format = options?.outputFormat || this.config.defaults.outputFormat;\n\n    return this.queue.add(async () => {\n      const start = performance.now();\n\n      try {\n        if (options?.streaming) {\n          return await this.client.textToSpeech.stream(voiceId, {\n            text,\n            model_id: modelId,\n            output_format: format,\n            voice_settings: this.config.defaults.voiceSettings,\n          });\n        }\n\n        const audio = await this.client.textToSpeech.convert(voiceId, {\n          text,\n          model_id: modelId,\n          output_format: format,\n          voice_settings: this.config.defaults.voiceSettings,\n        });\n\n        const latency = performance.now() - start;\n        console.log(`[TTS] ${text.length} chars, ${modelId}, ${latency.toFixed(0)}ms`);\n        return audio;\n      } catch (error) {\n        throw classifyError(error);\n      }\n    }) as Promise\u003CReadableStream | Buffer>;\n  }\n\n  \u002F\u002F Split long text into chunks with prosody context\n  async generateLongText(text: string, voiceId?: string): Promise\u003CBuffer[]> {\n    const chunks = this.splitText(text, 4500); \u002F\u002F Stay under 5000 limit\n    const results: Buffer[] = [];\n\n    for (let i = 0; i \u003C chunks.length; i++) {\n      const audio = await this.generate(chunks[i], {\n        voiceId,\n        \u002F\u002F Pass context for natural prosody across chunks\n      });\n      results.push(audio as Buffer);\n    }\n\n    return results;\n  }\n\n  private splitText(text: string, maxChars: number): string[] {\n    const chunks: string[] = [];\n    const sentences = text.match(\u002F[^.!?]+[.!?]+\u002Fg) || [text];\n    let current = \"\";\n\n    for (const sentence of sentences) {\n      if ((current + sentence).length > maxChars) {\n        if (current) chunks.push(current.trim());\n        current = sentence;\n      } else {\n        current += sentence;\n      }\n    }\n    if (current) chunks.push(current.trim());\n    return chunks;\n  }\n}\n```\n\n### Step 4: Voice Management Service\n\n```typescript\n\u002F\u002F src\u002Fservices\u002Fvoice-service.ts\nexport class VoiceService {\n  private client: ElevenLabsClient;\n\n  constructor(client: ElevenLabsClient) {\n    this.client = client;\n  }\n\n  async listVoices(filter?: { category?: \"premade\" | \"cloned\" | \"generated\" }) {\n    const { voices } = await this.client.voices.getAll();\n    if (filter?.category) {\n      return voices.filter(v => v.category === filter.category);\n    }\n    return voices;\n  }\n\n  async cloneVoice(name: string, description: string, audioFiles: NodeJS.ReadableStream[]) {\n    return this.client.voices.add({\n      name,\n      description,\n      files: audioFiles,\n    });\n  }\n\n  async getVoiceSettings(voiceId: string) {\n    return this.client.voices.getSettings(voiceId);\n  }\n\n  async updateVoiceSettings(voiceId: string, settings: {\n    stability: number;\n    similarity_boost: number;\n  }) {\n    return this.client.voices.editSettings(voiceId, settings);\n  }\n\n  async deleteVoice(voiceId: string) {\n    return this.client.voices.delete(voiceId);\n  }\n}\n```\n\n### Step 5: Data Flow Diagram\n\n```\n                         ┌──────────────┐\n                         │   Client     │\n                         │  (Browser\u002F   │\n                         │   Mobile)    │\n                         └──────┬───────┘\n                                │\n                         ┌──────▼───────┐\n                         │   API Layer  │\n                         │   \u002Fapi\u002Ftts   │\n                         │   \u002Fapi\u002Fvoice │\n                         └──────┬───────┘\n                                │\n                    ┌───────────┼───────────┐\n                    │           │           │\n             ┌──────▼──┐ ┌─────▼─────┐ ┌──▼──────┐\n             │  Cache   │ │   TTS     │ │  Voice  │\n             │ Service  │ │  Service  │ │ Service │\n             └──────┬───┘ └─────┬─────┘ └────────┘\n                    │           │\n              ┌─────▼─┐  ┌─────▼──────────┐\n              │ Redis\u002F │  │ Concurrency    │\n              │ LRU    │  │ Queue (p-queue)│\n              └────────┘  └─────┬──────────┘\n                                │\n                         ┌──────▼───────┐\n                         │  ElevenLabs  │\n                         │  Client SDK  │\n                         │  (singleton) │\n                         └──────┬───────┘\n                                │\n                    ┌───────────┼───────────┐\n                    │           │           │\n             ┌──────▼──┐ ┌─────▼─────┐ ┌──▼──────┐\n             │ \u002Fv1\u002Ftts  │ │ \u002Fv1\u002Fvoices│ │ \u002Fv1\u002Fsfx │\n             │ REST\u002FWS  │ │  REST     │ │  REST   │\n             └──────────┘ └───────────┘ └─────────┘\n                    ElevenLabs API (api.elevenlabs.io)\n```\n\n### Step 6: Health Check Composition\n\n```typescript\n\u002F\u002F src\u002Fapi\u002Froutes\u002Fhealth.ts\nexport async function healthCheck() {\n  const checks = await Promise.allSettled([\n    checkElevenLabsConnectivity(),\n    checkQuotaStatus(),\n    checkCacheHealth(),\n  ]);\n\n  const elevenlabs = checks[0].status === \"fulfilled\" ? checks[0].value : null;\n  const quota = checks[1].status === \"fulfilled\" ? checks[1].value : null;\n  const cache = checks[2].status === \"fulfilled\" ? checks[2].value : null;\n\n  const degraded = !elevenlabs || (quota && quota.pctUsed > 90);\n\n  return {\n    status: !elevenlabs ? \"unhealthy\" : degraded ? \"degraded\" : \"healthy\",\n    services: { elevenlabs, quota, cache },\n    timestamp: new Date().toISOString(),\n  };\n}\n```\n\n## Architecture Decisions\n\n| Decision | Choice | Rationale |\n|----------|--------|-----------|\n| Client pattern | Singleton | One connection pool, shared retry config |\n| Concurrency | p-queue | Respects plan limits, prevents 429 |\n| Caching | LRU (local) or Redis (distributed) | Repeated content is common in TTS |\n| Long text | Sentence-boundary splitting | Preserves natural speech prosody |\n| Error handling | Classification + retry | Different strategies for 429 vs 401 vs 500 |\n| Model selection | Environment-based | Flash in dev (cheap), Multilingual in prod (quality) |\n| Streaming | HTTP streaming + WebSocket | HTTP for simple, WS for LLM integration |\n\n## Error Handling\n\n| Issue | Cause | Solution |\n|-------|-------|----------|\n| Circular dependencies | Wrong layering | Services depend on client, never reverse |\n| Cold start latency | Client initialization | Pre-warm in server startup |\n| Memory pressure | Unbounded audio cache | Set `maxSizeMB` on cache |\n| Type errors | SDK version mismatch | Pin SDK version in package.json |\n\n## Resources\n\n- [ElevenLabs API Reference](https:\u002F\u002Felevenlabs.io\u002Fdocs\u002Fapi-reference\u002Fintroduction)\n- [ElevenLabs SDK Source](https:\u002F\u002Fgithub.com\u002Felevenlabs\u002Felevenlabs-js)\n- [p-queue](https:\u002F\u002Fgithub.com\u002Fsindresorhus\u002Fp-queue)\n- [LRU Cache](https:\u002F\u002Fgithub.com\u002Fisaacs\u002Fnode-lru-cache)\n\n## Next Steps\n\nStart with `elevenlabs-install-auth` for setup, then apply this architecture. Use `elevenlabs-core-workflow-a` and `elevenlabs-core-workflow-b` for feature implementation.\n\n",{"name":5,"tags":44,"author":48,"license":15,"version":49,"description":50,"allowed-tools":51,"compatible-with":52},[45,46,47,19,22,23],"saas","voice","ai","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","1.0.0","Implement ElevenLabs reference architecture for production TTS\u002Fvoice applications.\nUse when designing new ElevenLabs integrations, reviewing project structure,\nor building a scalable audio generation service.\nTrigger: \"elevenlabs architecture\", \"elevenlabs project structure\",\n\"how to organize elevenlabs\", \"TTS service architecture\",\n\"elevenlabs design patterns\", \"voice API architecture\".\n","Read, Grep","claude-code","main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002Fjeremylongshore\u002Fclaude-code-plugins-plus-skills\u002Felevenlabs-reference-architecture",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":63,"prompt":73,"zipAvailable":74},[64,67,70],{"tool":65,"command":66},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill elevenlabs-reference-architecture",{"tool":68,"command":69},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill elevenlabs-reference-architecture",{"tool":71,"command":72},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill elevenlabs-reference-architecture","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fjeremylongshore\u002Fclaude-code-plugins-plus-skills\u002Felevenlabs-reference-architecture\u002FSKILL.md",true,[],[77,86,95,104,110,116],{"skillNo":78,"name":79,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":39},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[83,84,85],"model","model hierarchy","model hierarchy skill",{"skillNo":87,"name":88,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":39},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[92,93,94],"MCP","zoom","zoom mcp",{"skillNo":96,"name":97,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":39},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[101,102,103,93],"sdk","zoom apps sdk","apps",{"skillNo":105,"name":106,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":39},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[106],{"skillNo":111,"name":112,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":39},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[112],{"skillNo":117,"name":118,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":119,"categories":120,"keywords":121,"publishedAt":39},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[118]]