You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用elevenlabs.generate报Invalid header值错误,无法使用POST请求

解决ElevenLabs generate()函数触发的ValueError问题

问题根源

错误ValueError: Invalid header value b'328fff54abb8128f17ea704be7f24fe7\n'是因为ElevenLabs API密钥末尾带有换行符(\n),导致请求头参数格式非法。

修复方案

1. 清理API密钥

配置密钥时用strip()方法自动去除首尾的换行、空格等空白字符:

import elevenlabs
# 替换为你的实际密钥,或从环境变量读取后处理
elevenlabs.set_api_key("你的API密钥".strip())

2. 优化Flask路由代码

确保密钥在Flask应用初始化时就完成配置,避免在路由内重复处理:

import elevenlabs
import os
from flask import Flask, request, render_template

app = Flask(__name__)
# 从环境变量读取并清理密钥,更安全
elevenlabs.set_api_key(os.getenv("ELEVENLABS_API_KEY").strip())

@app.route('/voiceTest_and_download/<int:story_id>', methods=['GET', 'POST'])
def voiceTest_and_download(story_id):
    global is_speaking  
    is_speaking = False
    choice_voice = request.form.get('choice_voice')
    choice_model = request.form.get('choice_model')
    session = db.session
    story = session.get(Story, story_id)
    
    if story and 'listen_voice' in request.form:
        audio = elevenlabs.generate(
            text="something text for testing",
            voice=choice_voice,
            model="eleven_multilingual_v2"
        )
        elevenlabs.play(audio)
        return render_template('voiceTest_and_download.html', story=story)

3. 额外检查点

  • 检查存储密钥的文件/环境变量,确保没有意外添加换行符。
  • 复制密钥时避免连带末尾的换行,粘贴后手动确认格式。

内容的提问来源于stack exchange,提问作者Rokon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 05:32:45