Hi I am trying to run my code that integrates with the chat completions API (OpenAI API) however when I try to submit a prompt to it it throws this error:
AttributeError: text
This error is specific to this part of the code :
Extract the generated response text from the API response
chat_response = response.choices[0].text.strip()
How do I fix this so that all of my code runs and I am able to generate chat responses?
Here is all of my code:
app = Flask(name)
Set your OpenAI API key here
openai.api_key = “sk-my-api-key”
Define the prompt and chat history
prompt = “prompt”
messages = [
{“role”: “system”, “content”: “What is the capital of France?”},
{“role”: “user”, “content”: “The capital of France is Paris.”},
{“role”: “assistant”, “content”: “The Los Angeles Dodgers won the World Series in 2020.”},
{“role”: “user”, “content”: “Where was it played?”}
]
Define a model and engine
model_engine = “gpt-3.5-turbo”
Generate the response using the OpenAI API
response = openai.ChatCompletion.create(
model=model_engine,
temperature=0.7,
max_tokens=1024,
n=1,
stop=None,
messages=messages,
)
Print the chatbot response
print(messages)
@app.route(“/”)
def index():
return render_template(“index.html”)
@app.route(“/chat”, methods=[“POST”])
def chat():
# Get the user’s prompt from the form data
prompt = request.form[“prompt”]
# Define the chat history
chat_history = [{'role': 'system', 'content': "What is the capital of France?"},
{'role': 'user', 'content': "The capital of France is Paris."},
{'role': 'assistant', 'content': "The Los Angeles Dodgers won the World Series in 2020."},
{'role': 'user', 'content': "Where was it played?"}]
# Generate the response using the OpenAI API
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
temperature=0.7,
max_tokens=1024,
n=1,
stop=None,
messages=messages,
)
# Extract the generated response text from the API response
chat_response = response.choices[0].text.strip()
# Render the chatbot response template with the response text
return render_template("chat.html", prompt=prompt, response=response)
if name == “main”:
app.run(debug=True)