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
相关产品推荐
相关产品推荐

