-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
61 lines (40 loc) · 1.48 KB
/
main.py
File metadata and controls
61 lines (40 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import streamlit as st
from openai import OpenAI
from dotenv import load_dotenv
import os
# carregar .env
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
if api_key:
modelo = OpenAI(api_key=api_key)
st.write("### ChatBot com IA")
# memória do chat
if "lista_mensagens" not in st.session_state:
st.session_state["lista_mensagens"] = []
# mostrar histórico
for mensagem in st.session_state["lista_mensagens"]:
st.chat_message(mensagem["role"]).write(mensagem["content"])
mensagem_usuario = st.chat_input("Escreva sua mensagem aqui")
if mensagem_usuario:
st.chat_message("user").write(mensagem_usuario)
mensagem = {"role": "user", "content": mensagem_usuario}
st.session_state["lista_mensagens"].append(mensagem)
try:
if api_key:
resposta_modelo = modelo.chat.completions.create(
messages=st.session_state["lista_mensagens"],
model="gpt-4o-mini"
)
resposta_ia = resposta_modelo.choices[0].message.content
else:
raise Exception("Sem API")
except Exception:
st.warning("Modo demonstração ativado (API sem créditos ou não configurada)")
resposta_ia = f"""
Resposta simulada.
Pergunta: {mensagem_usuario}
Este chatbot demonstra integração de IA usando Streamlit.
"""
st.chat_message("assistant").write(resposta_ia)
mensagem_ia = {"role": "assistant", "content": resposta_ia}
st.session_state["lista_mensagens"].append(mensagem_ia)