Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 5x 5x 5x 2x 2x 5x 9x 9x 5x 5x 1x 2x 2x 2x 2x 2x 2x 2x 2x | /**
* AgentKits — TTS (Text-to-Speech) Module
*
* Multi-provider text-to-speech with unified interface.
* Supports: OpenAI, Minimax, DashScope, Edge TTS (free), custom.
*
* Usage:
* import { createTTS } from 'agentkits/tts';
* const tts = createTTS({ provider: 'openai', apiKey: '...' });
* const audio = await tts.speak('Hello, world!');
* writeFileSync('output.mp3', audio);
*/
// ── Types ──────────────────────────────────────────────────────────
export type TTSProvider = 'openai' | 'minimax' | 'dashscope' | 'edge' | 'custom';
export interface TTSConfig {
provider?: TTSProvider;
model?: string;
voice?: string;
apiKey?: string;
baseUrl?: string;
speed?: number; // 0.25-4.0 (default 1.0)
format?: 'mp3' | 'wav' | 'opus' | 'flac';
}
export interface TTSClient {
/** Convert text to speech, returns audio buffer */
speak(text: string, options?: { voice?: string; speed?: number; format?: string }): Promise<Buffer>;
/** List available voices */
voices(): string[];
/** Current resolved config */
readonly config: Readonly<ResolvedTTSConfig>;
}
interface ResolvedTTSConfig {
provider: TTSProvider;
model: string;
voice: string;
baseUrl: string;
speed: number;
format: string;
}
// ── Provider Defaults ──────────────────────────────────────────────
interface ProviderDefaults {
model: string;
voice: string;
baseUrl: string;
voices: string[];
}
const PROVIDERS: Record<TTSProvider, ProviderDefaults> = {
openai: {
model: 'tts-1',
voice: 'nova',
baseUrl: 'https://api.openai.com/v1',
voices: ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'],
},
minimax: {
model: 'speech-02-hd',
voice: 'female-tianmei',
baseUrl: 'https://api.minimax.chat/v1',
voices: ['female-tianmei', 'male-qn-qingse', 'female-shaonv', 'male-qn-jingying'],
},
dashscope: {
model: 'cosyvoice-v1',
voice: 'longxiaochun',
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
voices: ['longxiaochun', 'longxiaoxia', 'longlaotie', 'longshu'],
},
edge: {
model: 'edge-tts',
voice: 'zh-CN-XiaoxiaoNeural',
baseUrl: '',
voices: ['zh-CN-XiaoxiaoNeural', 'zh-CN-YunxiNeural', 'en-US-JennyNeural', 'en-US-GuyNeural', 'ja-JP-NanamiNeural'],
},
custom: {
model: 'tts',
voice: 'default',
baseUrl: 'http://localhost:8080',
voices: [],
},
};
const ENV_MAP: Record<TTSProvider, { keyEnv: string[] }> = {
openai: { keyEnv: ['OPENAI_API_KEY'] },
minimax: { keyEnv: ['MINIMAX_API_KEY'] },
dashscope: { keyEnv: ['DASHSCOPE_API_KEY'] },
edge: { keyEnv: [] },
custom: { keyEnv: ['AGENTKIT_TTS_KEY'] },
};
// ── Factory ────────────────────────────────────────────────────────
export function createTTS(userConfig: TTSConfig = {}): TTSClient {
const provider = userConfig.provider ?? 'openai';
const defaults = PROVIDERS[provider] ?? PROVIDERS.openai;
const resolved: ResolvedTTSConfig = {
provider,
model: userConfig.model ?? defaults.model,
voice: userConfig.voice ?? defaults.voice,
baseUrl: userConfig.baseUrl ?? defaults.baseUrl,
speed: userConfig.speed ?? 1.0,
format: userConfig.format ?? 'mp3',
};
const apiKey = userConfig.apiKey
?? ENV_MAP[provider].keyEnv.map(k => process.env[k]).find(Boolean);
return {
async speak(text, options = {}) {
const voice = options.voice ?? resolved.voice;
const speed = options.speed ?? resolved.speed;
const format = options.format ?? resolved.format;
if (provider === 'openai' || provider === 'dashscope' || provider === 'custom') {
return speakOpenAICompatible(resolved, apiKey!, text, voice, speed, format);
} else if (provider === 'minimax') {
return speakMinimax(resolved, apiKey!, text, voice, speed);
} else if (provider === 'edge') {
// Edge TTS uses a different approach — simplified here
throw new Error('Edge TTS requires edge-tts npm package. Install: npm i edge-tts');
}
throw new Error(`Unknown TTS provider: ${provider}`);
},
voices() {
return defaults.voices;
},
get config() {
return resolved;
},
};
}
// ── Provider Implementations ───────────────────────────────────────
async function speakOpenAICompatible(
config: ResolvedTTSConfig,
apiKey: string,
text: string,
voice: string,
speed: number,
format: string,
): Promise<Buffer> {
const response = await fetch(`${config.baseUrl}/audio/speech`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: config.model,
input: text,
voice,
speed,
response_format: format,
}),
});
if (!response.ok) {
const err = await response.text();
throw new Error(`TTS failed (${response.status}): ${err}`);
}
const arrayBuffer = await response.arrayBuffer();
return Buffer.from(arrayBuffer);
}
async function speakMinimax(
config: ResolvedTTSConfig,
apiKey: string,
text: string,
voice: string,
speed: number,
): Promise<Buffer> {
const response = await fetch(`${config.baseUrl}/t2a_v2`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: config.model,
text,
timber_weights: [{ voice_id: voice, weight: 1 }],
audio_setting: { speed: speed * 100 },
}),
});
if (!response.ok) {
const err = await response.text();
throw new Error(`Minimax TTS failed (${response.status}): ${err}`);
}
const data = await response.json() as any;
if (data.data?.audio) {
return Buffer.from(data.data.audio, 'hex');
}
throw new Error('Minimax TTS: no audio in response');
}
// ── Convenience ────────────────────────────────────────────────────
export function listTTSProviders(): Array<{ id: TTSProvider; model: string; region: string; free: boolean }> {
return [
{ id: 'openai', model: 'tts-1', region: 'Global', free: false },
{ id: 'minimax', model: 'speech-02-hd', region: 'Global', free: false },
{ id: 'dashscope', model: 'cosyvoice-v1', region: 'China', free: true },
{ id: 'edge', model: 'edge-tts', region: 'Global', free: true },
{ id: 'custom', model: 'configurable', region: 'Any', free: false },
];
}
|