skip to Main Content

Working with OpenAI API and below is my simple code, but getting deprecation warning for ‘steam_to_file’ method.

Code –

from openai import OpenAI
from pathlib import Path

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

speech_file_path = Path(__file__).parent / "speech.mp3"
response = client.audio.speech.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
         '''
)
response.stream_to_file(speech_file_path)

IDE – Visual Studio code

Warning as below –

** DeprecationWarning: Due to a bug, this method doesn’t actually stream the response content, .with_streaming_response.method() should be used instead
response.stream_to_file("song.mp3")**

Can anyone please help?

I tried to check through different forums but could not find error related to stream_to_file.

I am using Python 3.12

2

Answers


  1. I had the same issue but this fixed it. Delete line
    speech_file_path = Path(__file__).parent / "speech.mp3" and write file_name = "speech.mp3".

    response = openai.audio.speech.create(
      model="tts-1",
      voice=shimmer,
      input="The quick brown fox jumped over the lazy dog."
    )
    
    file_name = "speech.mp3"
    response.stream_to_file(file_name)
    
    Login or Signup to reply.
  2. This seems to be the recommended approach, at least it uses the methods that the error message suggests:

    from openai import OpenAI
    
    client = OpenAI()
    
    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.mp3")
    

    However, it seems like this still doesn’t actually stream the response. If I repeatedly check the "last changed" time on the speech.mp3 file, I can see that it is created immediately, but it isn’t changed again until the entire generation completes.

    I’m still trying to figure out how to do proper streaming of TTS, but at least this is a way to use the API without a DeprecationError.

    Using openai 1.12.0

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search