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

OpenAI API中stream_to_file方法弃用警告问题求助

解决OpenAI API stream_to_file 弃用警告问题

你遇到的弃用警告是因为旧的stream_to_file方法存在bug,并未真正实现流式传输,官方推荐使用with_streaming_response上下文管理器来替代。以下是修改后的完整代码:

from openai import OpenAI
from pathlib import Path
import os

client = OpenAI(
    api_key=os.getenv("OPENAI_API_KEY"),
)

speech_file_path = Path(__file__).parent / "speech.mp3"

# 使用流式响应上下文管理器创建音频
with client.audio.speech.with_streaming_response.create(
    model="tts-1",
    voice="alloy",
    input='''I see skies of blue and clouds of white
            The bright blessed days, the dark sacred nights
            And I think to myself
            What a wonderful world
         '''
) as response:
    # 流式写入文件
    response.stream_to_file(speech_file_path)

关键修改说明:

  • 替换client.audio.speech.create()为client.audio.speech.with_streaming_response.create(),该方法会返回真正的流式响应对象
  • 通过with上下文管理器管理响应资源,确保连接正确关闭
  • 原代码遗漏了import os,补充后可正常读取环境变量中的API密钥

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 19:48:15