File size: 5,632 Bytes
edf2dd9 c43bd73 954bd9f c43bd73 edf2dd9 37d3daa edf2dd9 c43bd73 80b13d7 edf2dd9 80b13d7 edf2dd9 80b13d7 c43bd73 edf2dd9 954bd9f edf2dd9 b304899 edf2dd9 b304899 edf2dd9 bb879f5 edf2dd9 bb879f5 954bd9f edf2dd9 d5fde2c 80b13d7 d5fde2c 80b13d7 d5fde2c 80b13d7 edf2dd9 d5fde2c edf2dd9 d5fde2c edf2dd9 d5fde2c c43bd73 954bd9f c43bd73 edf2dd9 4245712 edf2dd9 4245712 edf2dd9 4245712 edf2dd9 4245712 37d3daa 4bd9825 edf2dd9 4245712 954bd9f edf2dd9 | 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | import os
import unicodedata
import streamlit as st
from pergunte_2 import build_runner, debug_info # usamos só o runner e o painel de debug
def build_chat_ctx(history, max_chars=1200, max_turns=6):
"""Concatena os últimos turnos (user/assistant) e corta em ~max_chars."""
msgs = history[-max_turns:]
lines = []
for m in msgs:
role = "Usuário" if m["role"] == "user" else "Assistente"
lines.append(f"{role}: {m['content']}")
s = "\n".join(lines)
# corta para não estourar contexto
if len(s) > max_chars:
s = "… " + s[-max_chars:]
return s
# ===================== HELPERS =====================
def normalize_text(s: str) -> str:
"""Evita bugs de formatação no Markdown do Streamlit."""
if s is None:
return ""
# Normaliza primeiro
s = unicodedata.normalize("NFC", s)
# Escapes de Markdown/MathJax
s = s.replace("\\", "\\\\") # barra invertida primeiro
s = s.replace("_", "\\_")
s = s.replace("*", "\\*")
s = s.replace("$", "\\$") # <<<<<< ESCAPE DO CIFRÃO (resolve o seu bug)
s = s.replace("|", "\\|")
return s
# ===================== API KEY (fallback) =====================
if not os.getenv("OPENAI_API_KEY"):
with st.sidebar:
st.info("Defina sua chave da OpenAI (ou use o .env).")
api_key_input = st.text_input("OPENAI_API_KEY", type="password")
if api_key_input:
os.environ["OPENAI_API_KEY"] = api_key_input
# ===================== CONTROLES DA UI =====================
st.set_page_config(
page_title="TaxBot — O Agente do Imposto de Renda",
page_icon="💬",
layout="centered",
initial_sidebar_state="collapsed",
)
# Modo de resposta (resumido/detalhado)
modo = st.sidebar.selectbox("🧰 Nível de detalhe", ["resumido", "detalhado"], index=0)
# Opções avançadas (mantemos só tipo e k)
with st.sidebar.expander("⚙️ Opções avançadas", expanded=False):
tipo = st.selectbox("Tipo de conteúdo", ["any", "texto", "tabela", "imagem"], index=0)
k = st.slider("Top-k (trechos de contexto)", 3, 12, 6)
# Criar/atualizar runner quando o modo mudar
if "runner" not in st.session_state or st.session_state.get("modo") != modo or st.session_state.get("k") != k:
st.session_state.runner = build_runner(k=k, style_mode=modo)
st.session_state.modo = modo
st.session_state.k = k
# Painel de debug da memória
_dbg = debug_info()
with st.sidebar:
st.markdown("### 🔎 Memória (Chroma)")
st.write(f"**DIR**: `{_dbg['chroma_dir']}`")
st.write(f"**COL**: `{_dbg['collection']}`")
st.write(f"**COUNT**: `{_dbg['count']}`")
st.write("**Amostra de hits:**")
st.json(_dbg.get("sample_hits", []))
# ===================== ESTILO =====================
st.markdown(
"""
<style>
.main .block-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 85vh;
text-align: center;
}
[data-testid="stChatInput"] {
width: 72%;
margin: 0 auto;
}
.intro-text { font-size: 1.2rem; color: #ddd; margin-bottom: 2rem; line-height: 1.5; }
.title { font-size: 1.8rem; font-weight: 600; color: #fff; margin-bottom: 0.5rem; }
.disclaimer { opacity: .9; margin-top: 1.25rem; }
</style>
""",
unsafe_allow_html=True
)
# 🔽 Adicione este segundo bloco logo abaixo 🔽
st.markdown("""
<style>
/* chat sempre alinhado à esquerda */
.stChatMessage, .stChatMessage p, .stChatMessage li, .stChatMessage ul, .stChatMessage ol {
text-align: left !important;
}
</style>
""", unsafe_allow_html=True)
# ===================== HEADER =====================
st.markdown(
"""
<div class="title">💬 TaxBot — O Agente do Imposto de Renda</div>
<div class="intro-text">
Pergunte o que quiser sobre a Reforma do Imposto de Renda.
Eu explico as novas regras, simulo cálculos (quando você pedir) e comparo mudanças no IRPF.
</div>
""",
unsafe_allow_html=True,
)
st.caption("Respostas baseadas em documentos oficiais e científicos.")
# ===================== HISTÓRICO =====================
if "history" not in st.session_state:
st.session_state.history = []
for m in st.session_state.history:
with st.chat_message(m["role"]):
st.markdown(normalize_text(m["content"]), unsafe_allow_html=False)
# ===================== CHAT INPUT =====================
if prompt := st.chat_input("Escreva sua pergunta..."):
# Mostra a pergunta
st.session_state.history.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(normalize_text(prompt), unsafe_allow_html=False)
# Responde usando o runner (fonte fixa 'all')
with st.chat_message("assistant"):
with st.spinner("🔎 Consultando memória e calculando quando necessário..."):
try:
chat_ctx = build_chat_ctx(st.session_state.history)
result = st.session_state.runner(prompt, "all", tipo, chat_ctx)
answer = result["answer"]
except Exception as e:
answer = f"⚠️ Erro: `{e}`"
st.markdown(normalize_text(answer), unsafe_allow_html=False)
st.session_state.history.append({"role": "assistant", "content": answer})
# ===================== AVISO FIXO =====================
st.markdown(
"""
<div class="disclaimer">
⚠️ Isto é informação geral e <u>não</u> constitui aconselhamento tributário, contábil ou jurídico.
</div>
""",
unsafe_allow_html=True,
)
|