Danielfonseca1212 commited on
Commit
89b9bf6
·
verified ·
1 Parent(s): 7309146

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +350 -0
app.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 🧠 Agent Pruning Lab
3
+ Demonstração visual de Context Pruning com Provence e Semantic Highlighting
4
+ para sistemas de Agentes LLM - Hugging Face Space
5
+ """
6
+
7
+ import streamlit as st
8
+ import json
9
+ import random
10
+ from components.visualizer import SemanticHighlighter
11
+ from components.provence_wrapper import ProvencePruner
12
+ from components.agent_simulator import AgentSimulator
13
+
14
+ # Configuração da página
15
+ st.set_page_config(
16
+ page_title="🧠 Agent Pruning Lab",
17
+ page_icon="✂️",
18
+ layout="wide",
19
+ initial_sidebar_state="expanded"
20
+ )
21
+
22
+ # CSS Customizado
23
+ st.markdown("""
24
+ <style>
25
+ .main-header {
26
+ font-size: 3rem;
27
+ font-weight: 800;
28
+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
29
+ -webkit-background-clip: text;
30
+ -webkit-text-fill-color: transparent;
31
+ margin-bottom: 0.5rem;
32
+ }
33
+ .sub-header {
34
+ font-size: 1.2rem;
35
+ color: #666;
36
+ margin-bottom: 2rem;
37
+ }
38
+ .metric-card {
39
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
40
+ padding: 1.5rem;
41
+ border-radius: 15px;
42
+ color: white;
43
+ text-align: center;
44
+ box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
45
+ }
46
+ .metric-value {
47
+ font-size: 2.5rem;
48
+ font-weight: 700;
49
+ }
50
+ .metric-label {
51
+ font-size: 0.9rem;
52
+ opacity: 0.9;
53
+ }
54
+ .pruned-text {
55
+ background-color: #ff6b6b20;
56
+ text-decoration: line-through;
57
+ color: #999;
58
+ padding: 2px 4px;
59
+ border-radius: 3px;
60
+ }
61
+ .kept-text {
62
+ background-color: #51cf6620;
63
+ color: #2b8a3e;
64
+ padding: 2px 4px;
65
+ border-radius: 3px;
66
+ font-weight: 500;
67
+ }
68
+ .highlight-low { background-color: #fff3bf; }
69
+ .highlight-med { background-color: #ffd8a8; }
70
+ .highlight-high { background-color: #ff8787; }
71
+ .agent-thought {
72
+ background: #f8f9fa;
73
+ border-left: 4px solid #667eea;
74
+ padding: 1rem;
75
+ margin: 0.5rem 0;
76
+ border-radius: 0 8px 8px 0;
77
+ font-family: 'Courier New', monospace;
78
+ }
79
+ .stTabs [data-baseweb="tab-list"] {
80
+ gap: 8px;
81
+ }
82
+ .stTabs [data-baseweb="tab"] {
83
+ background-color: #f0f2f6;
84
+ border-radius: 8px 8px 0 0;
85
+ padding: 10px 20px;
86
+ }
87
+ </style>
88
+ """, unsafe_allow_html=True)
89
+
90
+ # Inicialização dos componentes
91
+ @st.cache_resource
92
+ def load_models():
93
+ return ProvencePruner(), SemanticHighlighter(), AgentSimulator()
94
+
95
+ pruner, highlighter, agent = load_models()
96
+
97
+ # Header
98
+ st.markdown('<h1 class="main-header">🧠 Agent Pruning Lab</h1>', unsafe_allow_html=True)
99
+ st.markdown('<p class="sub-header">Context Pruning com Provence + Semantic Highlighting para Agentes LLM</p>', unsafe_allow_html=True)
100
+
101
+ # Sidebar
102
+ with st.sidebar:
103
+ st.markdown("### ⚙️ Configurações do Agente")
104
+
105
+ model_choice = st.selectbox(
106
+ "Modelo de Pruning",
107
+ ["OpenProvence-XSmall (30M)", "OpenProvence-Small (110M)", "Simulação (Demo)"],
108
+ index=2
109
+ )
110
+
111
+ pruning_threshold = st.slider(
112
+ "Threshold de Pruning",
113
+ 0.0, 1.0, 0.5, 0.05,
114
+ help="Sentenças com score abaixo são removidas"
115
+ )
116
+
117
+ highlight_mode = st.radio(
118
+ "Modo de Visualização",
119
+ ["Semantic Highlighting", "Binary Keep/Remove", "Heatmap de Relevância"],
120
+ index=0
121
+ )
122
+
123
+ st.markdown("---")
124
+ st.markdown("### 📚 Sobre")
125
+ st.info("""
126
+ **Provence** é um método de pruning de contexto desenvolvido pela Naver Labs Europe [^7^].
127
+
128
+ **Semantic Highlighting** visualiza a relevância token-a-token do contexto [^11^].
129
+
130
+ Combinação ideal para agentes que precisam processar documentos longos de forma eficiente.
131
+ """)
132
+
133
+ st.markdown("---")
134
+ st.markdown("🔗 [Paper Provence](https://arxiv.org/abs/2501.16214)")
135
+ st.markdown("🔗 [OpenProvence GitHub](https://github.com/hotchpotch/open_provence)")
136
+
137
+ # Tabs principais
138
+ tab1, tab2, tab3, tab4 = st.tabs([
139
+ "🎮 Demo Interativo",
140
+ "📊 Benchmarks",
141
+ "🔬 Análise Técnica",
142
+ "📖 Documentação"
143
+ ])
144
+
145
+ with tab1:
146
+ st.markdown("### 🎯 Simule um Agente de Pesquisa")
147
+
148
+ col1, col2 = st.columns([1, 1])
149
+
150
+ with col1:
151
+ st.markdown("#### ❓ Query do Agente")
152
+ query = st.text_area(
153
+ "O que o agente precisa encontrar?",
154
+ value="Quais são os principais benefícios do context pruning em sistemas RAG?",
155
+ height=80
156
+ )
157
+
158
+ st.markdown("#### 📄 Documento de Entrada")
159
+ document = st.text_area(
160
+ "Cole um documento longo ou use o exemplo:",
161
+ value="""A inteligência artificial tem revolucionado diversos setores da economia global.
162
+ No campo da medicina, algoritmos de deep learning são utilizados para diagnóstico precoce de câncer.
163
+ Em finanças, modelos preditivos analisam padrões de mercado.
164
+ No entanto, um dos maiores desafios em sistemas de Retrieval-Augmented Generation (RAG) é o gerenciamento eficiente de contexto longo.
165
+ Quando documentos irrelevantes são incluídos no prompt, o modelo desperdiça tokens e pode gerar respostas imprecisas.
166
+ Técnicas como context pruning, especialmente métodos como Provence, permitem remover sentenças irrelevantes mantendo apenas o conteúdo necessário.
167
+ Isso resulta em redução de latência e melhoria na qualidade das respostas.
168
+ Estudos mostram que Provence consegue taxas de compressão de até 95% sem perda de performance [^1^].
169
+ Além disso, o Semantic Highlighting permite visualizar quais partes do texto são mais relevantes para uma query específica.
170
+ Em sistemas multi-agente, onde múltiplos agentes trocam contexto, o pruning se torna ainda mais crítico para evitar propagação de ruído.
171
+ A Naver Labs Europe desenvolveu o Provence como um modelo leve baseado em DeBERTa que realiza pruning e reranking em um único forward pass [^4^].
172
+ O modelo é treinado com labels de prata geradas por LLMs, identificando quais sentenças foram de fato utilizadas para gerar respostas.
173
+ Resultados em benchmarks como Natural Questions e HotpotQA demonstram melhorias consistentes.""",
174
+ height=300
175
+ )
176
+
177
+ run_button = st.button("🚀 Executar Pipeline do Agente", type="primary", use_container_width=True)
178
+
179
+ with col2:
180
+ st.markdown("#### 🧠 Simulação do Agente")
181
+
182
+ if run_button:
183
+ with st.spinner("🔍 Agente processando..."):
184
+ # Simula o pipeline completo
185
+ results = agent.run_pipeline(query, document, pruning_threshold)
186
+
187
+ # Métricas
188
+ col_m1, col_m2, col_m3 = st.columns(3)
189
+ with col_m1:
190
+ st.markdown(f"""
191
+ <div class="metric-card">
192
+ <div class="metric-value">{results['compression_rate']}%</div>
193
+ <div class="metric-label">Compressão</div>
194
+ </div>
195
+ """, unsafe_allow_html=True)
196
+ with col_m2:
197
+ st.markdown(f"""
198
+ <div class="metric-card">
199
+ <div class="metric-value">{results['tokens_saved']}</div>
200
+ <div class="metric-label">Tokens Economizados</div>
201
+ </div>
202
+ """, unsafe_allow_html=True)
203
+ with col_m3:
204
+ st.markdown(f"""
205
+ <div class="metric-card">
206
+ <div class="metric-value">{results['relevance_score']:.2f}</div>
207
+ <div class="metric-label">Score de Relevância</div>
208
+ </div>
209
+ """, unsafe_allow_html=True)
210
+
211
+ st.markdown("---")
212
+
213
+ # Visualização do resultado
214
+ st.markdown("#### ✂️ Resultado do Pruning")
215
+
216
+ if highlight_mode == "Semantic Highlighting":
217
+ html_output = highlighter.render_semantic_highlighting(
218
+ results['sentences'],
219
+ results['scores']
220
+ )
221
+ st.markdown(html_output, unsafe_allow_html=True)
222
+
223
+ elif highlight_mode == "Binary Keep/Remove":
224
+ for sent, score, kept in zip(results['sentences'], results['scores'], results['kept']):
225
+ css_class = "kept-text" if kept else "pruned-text"
226
+ st.markdown(f'<span class="{css_class}">{sent}</span> ', unsafe_allow_html=True)
227
+
228
+ else: # Heatmap
229
+ fig = highlighter.render_heatmap(results['sentences'], results['scores'])
230
+ st.plotly_chart(fig, use_container_width=True)
231
+
232
+ # Pensamento do agente
233
+ st.markdown("---")
234
+ st.markdown("#### 💭 Raciocínio do Agente")
235
+ for thought in results['agent_thoughts']:
236
+ st.markdown(f'<div class="agent-thought">{thought}</div>', unsafe_allow_html=True)
237
+ else:
238
+ st.info("👈 Configure a query e clique em 'Executar Pipeline do Agente'")
239
+
240
+ with tab2:
241
+ st.markdown("### 📊 Benchmarks de Performance")
242
+
243
+ data = {
244
+ "Método": ["Sem Pruning", "Truncation Simples", "Provence", "XProvence", "Semantic Highlighter"],
245
+ "F1 Score": ["—", "42.3%", "66.76%", "58.97%", "46.37%"],
246
+ "Compressão": ["0%", "60%", "80-95%", "75-85%", "70-80%"],
247
+ "Latência Extra": ["0ms", "0ms", "~0ms*", "~0ms*", "5-10ms"],
248
+ "Multilíngue": ["—", "Sim", "Inglês", "Sim", "Sim"]
249
+ }
250
+
251
+ import pandas as pd
252
+ df = pd.DataFrame(data)
253
+ st.dataframe(df, use_container_width=True, hide_index=True)
254
+
255
+ st.caption("*Provence integra pruning com reranking, adicionando latência quase zero [^4^]")
256
+
257
+ st.markdown("---")
258
+ st.markdown("#### 🏆 Resultados em Datasets")
259
+
260
+ col_b1, col_b2 = st.columns(2)
261
+ with col_b1:
262
+ st.markdown("**Natural Questions**")
263
+ st.progress(0.89, text="Provence: 89% retenção de acurácia")
264
+ st.progress(0.72, text="Baseline: 72% retenção de acurácia")
265
+ with col_b2:
266
+ st.markdown("**HotpotQA (Multi-hop)**")
267
+ st.progress(0.85, text="Provence: 85% retenção de acurácia")
268
+ st.progress(0.68, text="Baseline: 68% retenção de acurácia")
269
+
270
+ with tab3:
271
+ st.markdown("### 🔬 Análise Técnica Detalhada")
272
+
273
+ st.markdown("""
274
+ #### Arquitetura Provence
275
+
276
+ Provence utiliza uma arquitetura **dual-head** baseada em DeBERTa-V3 [^5^]:
277
+
278
+ 1. **Reranking Head**: Prediz score de relevância do documento inteiro
279
+ 2. **Pruning Head**: Gera máscara binária token-a-token indicando relevância
280
+
281
+ Durante o treinamento, o modelo otimiza simultaneamente:
282
+ - Binary Cross-Entropy para pruning
283
+ - MSE para distilação do reranker original
284
+
285
+ #### Semantic Highlighting vs Traditional Highlighting
286
+
287
+ | Aspecto | Traditional (Keyword) | Semantic Highlighting |
288
+ |---------|----------------------|----------------------|
289
+ | Base | Matching literal | Similaridade semântica |
290
+ | Sinônimos | ❌ Não detecta | ✅ Detecta |
291
+ | Paráfrases | ❌ Não detecta | ✅ Detecta |
292
+ | Custo | Baixo | Moderado |
293
+ | Precisão | Baixa para RAG | Alta para RAG |
294
+
295
+ #### Integração em Agentes
296
+
297
+ Em workflows agentic, o pruning é aplicado em múltiplos pontos [^12^]:
298
+ - **Pré-LLM**: Filtra documentos recuperados
299
+ - **Inter-agente**: Resume contexto entre agentes
300
+ - **Pós-tool**: Compacta outputs de ferramentas token-heavy
301
+ """)
302
+
303
+ with tab4:
304
+ st.markdown("### 📖 Como Usar Este Projeto")
305
+
306
+ st.markdown("""
307
+ #### 🚀 Deploy no Hugging Face Spaces
308
+
309
+ 1. Crie um novo Space em [huggingface.co/spaces](https://huggingface.co/spaces)
310
+ 2. Escolha **Streamlit** como SDK
311
+ 3. Faça push deste código:
312
+
313
+ ```bash
314
+ git clone https://huggingface.co/spaces/seu-username/agent-pruning-lab
315
+ cd agent-pruning-lab
316
+ # Copie os arquivos deste projeto
317
+ git add .
318
+ git commit -m "Initial commit"
319
+ git push
320
+ ```
321
+
322
+ #### 🔧 Integração com Seu Agente
323
+
324
+ ```python
325
+ from components.provence_wrapper import ProvencePruner
326
+
327
+ pruner = ProvencePruner(model_name="hotchpotch/open_provence_xsmall")
328
+
329
+ # No seu pipeline RAG
330
+ retrieved_docs = retriever.search(query)
331
+ pruned_docs = pruner.prune(query, retrieved_docs, threshold=0.5)
332
+ response = llm.generate(query, context=pruned_docs)
333
+ ```
334
+
335
+ #### 📚 Referências
336
+
337
+ - [Provence Paper - ICLR 2025](https://arxiv.org/abs/2501.16214) [^7^]
338
+ - [OpenProvence Implementation](https://github.com/hotchpotch/open_provence) [^8^]
339
+ - [Semantic Highlighting Blog - Milvus](https://milvus.io/blog/semantic-highlighting-model-for-rag-context-pruning-and-token-saving.md) [^11^]
340
+ - [Context Engineering - LangChain](https://www.langchain.com/blog/context-engineering-for-agents) [^12^]
341
+ """)
342
+
343
+ # Footer
344
+ st.markdown("---")
345
+ st.markdown("""
346
+ <div style="text-align: center; color: #666; padding: 1rem;">
347
+ <p>🧠 Agent Pruning Lab | Built with ❤️ for Hugging Face Spaces</p>
348
+ <p>Demonstrando Provence + Semantic Highlighting para Agentes LLM Modernos</p>
349
+ </div>
350
+ """, unsafe_allow_html=True)