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( """ """, unsafe_allow_html=True ) # 🔽 Adicione este segundo bloco logo abaixo 🔽 st.markdown(""" """, unsafe_allow_html=True) # ===================== HEADER ===================== st.markdown( """