(params: {
model: string;
contents: any[];
voiceName?: string;
})
| 706 | } |
| 707 | |
| 708 | async generateTTS(params: { |
| 709 | model: string; |
| 710 | contents: any[]; |
| 711 | voiceName?: string; |
| 712 | }): Promise<{ audioData?: Buffer[]; audioMimeType?: string }> { |
| 713 | |
| 714 | const url = `${this.baseUrl}/v1beta/models/${params.model}:generateContent`; |
| 715 | |
| 716 | const headers: Record<string, string> = { |
| 717 | 'x-goog-api-key': this.apiKey, |
| 718 | 'Content-Type': 'application/json' |
| 719 | }; |
| 720 | |
| 721 | const voiceName = params.voiceName || DEFAULT_CONFIG[CONFIG_KEYS.GEMINI_TTS_VOICE]; |
| 722 | |
| 723 | const textContent = params.contents[0]?.parts?.[0]?.text || ''; |
| 724 | if (!textContent.trim()) { |
| 725 | throw new Error('TTS 需要有效的文本内容'); |
| 726 | } |
| 727 | |
| 728 | const requestData = { |
| 729 | contents: [{ |
| 730 | role: 'user', |
| 731 | parts: [{ text: textContent }] |
| 732 | }], |
| 733 | generationConfig: { |
| 734 | responseModalities: ['AUDIO'], |
| 735 | speechConfig: { |
| 736 | voiceConfig: { |
| 737 | prebuiltVoiceConfig: { |
| 738 | voiceName: voiceName |
| 739 | } |
| 740 | } |
| 741 | } |
| 742 | } |
| 743 | }; |
| 744 | |
| 745 | const response = await HttpClient.makeRequest(url, { |
| 746 | method: 'POST', |
| 747 | headers, |
| 748 | data: requestData, |
| 749 | timeout: 60000 |
| 750 | }); |
| 751 | |
| 752 | if (response.status !== 200) { |
| 753 | const errorMsg = response.data?.error?.message || 'Unknown error'; |
| 754 | if (response.status === 429) { |
| 755 | throw new Error('API配额已用完,请检查您的计费详情'); |
| 756 | } |
| 757 | const sanitizedMsg = errorMsg.replace(/api_key:[A-Za-z0-9_-]+/g, 'api_key:***'); |
| 758 | throw new Error(`HTTP错误 ${response.status}: ${sanitizedMsg}`); |
| 759 | } |
| 760 | |
| 761 | if (response.data?.error) { |
| 762 | const errorMsg = response.data.error.message || JSON.stringify(response.data.error); |
| 763 | const sanitizedMsg = errorMsg.replace(/api_key:[A-Za-z0-9_-]+/g, 'api_key:***'); |
| 764 | throw new Error(`API错误: ${sanitizedMsg}`); |
| 765 | } |
no test coverage detected