-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
64 lines (51 loc) · 2.29 KB
/
main.py
File metadata and controls
64 lines (51 loc) · 2.29 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
62
63
64
# titulo
# input do chat
# a cada mensagem enviada:
# mostrar a mensagem que o usuario enviou no chat
# enviar essa mensagem para a IA responder
# aparece na tela a resposta da IA
# streamlit - frontend e backend
# python3 -m pip install openai streamlit
# python -m pip install openai streamlit
# Roda o projeto: streamlit run main.py
import streamlit as st
from openai import OpenAI
from dotenv import load_dotenv
import os
# 🔑 Carrega variáveis do .env
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
# Validação de segurança
if not api_key or not api_key.startswith("sk-"):
st.error("🔑 API Key inválida ou não configurada!")
st.info("Crie o arquivo `.env` com: `OPENAI_API_KEY=sk-proj-...`")
st.stop()
modelo = OpenAI(api_key=api_key)
st.write("### ChatBot com IA")
if "lista_mensagens" not in st.session_state:
# st.session_state["lista_mensagens"] = [{"role": "system", "content": "Adicionar as instruções iniciais no do seu sistema para a ia se basear"}]
st.session_state["lista_mensagens"] = []
# session_state = memoria do streamlit
for msg in st.session_state["lista_mensagens"]:
st.chat_message(msg["role"]).write(msg["content"])
if mensagem_usuario := st.chat_input("Escreva sua mensagem aqui"):
# user -> ser humano
# assistant -> inteligencia artificial
st.chat_message("user").write(mensagem_usuario)
st.session_state["lista_mensagens"].append({"role": "user", "content": mensagem_usuario})
try:
with st.spinner("🤔 Pensando..."):
# Para criar um agente com base os dados na minha empresa precisa
# resposta da IA
resposta = modelo.chat.completions.create(
messages=st.session_state["lista_mensagens"],
model="gpt-4o"
)
resposta_ia = resposta.choices[0].message.content
# exibir a resposta da IA na tela
st.chat_message("assistant").write(resposta_ia)
st.session_state["lista_mensagens"].append({"role": "assistant", "content": resposta_ia})
except Exception as e:
st.error(f"❌ Erro: {str(e)}")
if "401" in str(e):
st.warning("💡 Chave inválida! Revogue e gere uma nova em: https://platform.openai.com/api-keys")