The TTS API not working I need to fix my code, please help!?

I am trying to run the Text To Speech api, using the following code:

from openai import OpenAI
import api

Initialize your OpenAI API key

openai.api_key = api.API_KEY

client = OpenAI()

response = client.audio.speech.create(
model=“tts-1”,
voice=“alloy”,
input=“Hello world! This is a streaming test.”,
)

response.stream_to_file(“output.mp3”)

But I am getting the following error code :

Traceback (most recent call last):
File “/Users/stephenhill/Coding/last_practice/tts.py”, line 1, in
from openai import OpenAI
ImportError: cannot import name ‘OpenAI’ from ‘openai’ (/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/openai/init.py)

You’ll have to update to the latest version of the OpenAI python package in order for this code to run.

2 Likes

I have ran the “pip3 install openai” but it says it is up to date

Found the mistake @shuffls2010 :

Here’s how you initialize API key in the latest version:

from openai import OpenAI

client = OpenAI(
    # defaults to os.environ.get("OPENAI_API_KEY")
    api_key="My API Key",
)

However it still might not solve your issue because your python dev environment might be misconfigured e.g there could be two versions of python on your machine or both pip and pip3 installed, which could cause issues like this:

1 Like

Thank you. It was some kind of a compatibility issue. I just created a virtual environment and it resolved it.

1 Like