Meu código está igual ao do instrutor, porém quando eu faço uma pergunta, o chat da esse erro:
href="?debugger=yes&cmd=resource&f=console.png">
AttributeError
AttributeError: 'str' object has no attribute 'choices'
Traceback (most recent call last)
return self.wsgi_app(environ, start_response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
response = self.handle_exception(e) ^^^^^^^^^^^^^^^^^^^^^^^^
response = self.full_dispatch_request() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
rv = self.handle_user_exception(e) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
rv = self.dispatch_request() ^^^^^^^^^^^^^^^^^^^^^^^ return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
texto_resposta = resposta.choices[0].message.content ^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'choices'
código:
from flask import Flask,render_template, request, Response
from openai import OpenAI
from dotenv import load_dotenv
import os
from time import sleep
load_dotenv()
cliente = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
modelo = "gpt-4"
app = Flask(__name__)
app.secret_key = 'alura'
def bot (prompt):
maximo_tentativas = 1
repeticao = 0
while True:
try:
prompt_do_sistema = f"""
Você é um chatbot de atendimento a clientes de um e-commerce.
Você não deve responder perguntas que não sejam dados do e-commerce informado!
"""
response = cliente.chat.completions.create(
messages=[
{
"role": "system",
"content": prompt_do_sistema
},
{
"role": "user",
"content": prompt
}
],
temperature=1,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
model = modelo)
return response
except Exception as erro:
repeticao += 1
if repeticao >= maximo_tentativas:
return "Erro no GPT: %s" % erro
print('Erro de comunicação com OpenAI:', erro)
sleep(1)
@app.route("/chat", methods = ["POST"])
def chat():
prompt = request.json["msg"]
resposta = bot(prompt)
texto_resposta = resposta.choices[0].message.content
return texto_resposta
@app.route("/")
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug = True)