anderson-ufrj commited on
Commit
0564dce
·
1 Parent(s): 0f09977

docs(examples): add interactive demo for chat with dados.gov.br

Browse files

- Create demo script showing chat integration in action
- Demonstrate automatic dados.gov.br enrichment
- Show different investigation scenarios
- Include API health check and instructions

Files changed (1) hide show
  1. examples/chat_dados_gov_demo.py +196 -0
examples/chat_dados_gov_demo.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Demo: Chat with dados.gov.br integration
4
+
5
+ This script demonstrates how users can chat with Cidadão.AI
6
+ and automatically get enriched results from dados.gov.br.
7
+ """
8
+
9
+ import asyncio
10
+ import json
11
+ from datetime import datetime
12
+ import aiohttp
13
+
14
+ # API configuration
15
+ API_BASE_URL = "http://localhost:8000" # Adjust if needed
16
+ API_KEY = "demo-key" # Replace with actual API key if required
17
+
18
+
19
+ async def send_chat_message(session, message: str, session_id: str = None):
20
+ """Send a message to the chat API"""
21
+ url = f"{API_BASE_URL}/api/v1/chat/message"
22
+
23
+ headers = {
24
+ "Content-Type": "application/json",
25
+ "X-API-Key": API_KEY
26
+ }
27
+
28
+ data = {
29
+ "message": message,
30
+ "session_id": session_id
31
+ }
32
+
33
+ async with session.post(url, json=data, headers=headers) as response:
34
+ return await response.json()
35
+
36
+
37
+ async def demo_investigation_with_open_data():
38
+ """Demonstrate an investigation that includes dados.gov.br data"""
39
+ print("=" * 70)
40
+ print("🇧🇷 CIDADÃO.AI - Demonstração de Integração com dados.gov.br")
41
+ print("=" * 70)
42
+ print()
43
+
44
+ async with aiohttp.ClientSession() as session:
45
+ # Create a session ID
46
+ session_id = f"demo_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
47
+
48
+ # Example 1: Simple investigation
49
+ print("📋 Exemplo 1: Investigação Simples")
50
+ print("-" * 40)
51
+
52
+ message = "Quero investigar contratos do Ministério da Saúde"
53
+ print(f"👤 Usuário: {message}")
54
+ print()
55
+
56
+ try:
57
+ response = await send_chat_message(session, message, session_id)
58
+
59
+ print(f"🤖 Cidadão.AI:")
60
+ print(response.get("message", "Sem resposta"))
61
+ print()
62
+
63
+ # Check if open data was found
64
+ metadata = response.get("metadata", {})
65
+ if metadata.get("dados_gov_enabled"):
66
+ print("✅ Integração com dados.gov.br ativada!")
67
+
68
+ # Show suggested actions if available
69
+ actions = response.get("suggested_actions", [])
70
+ if actions:
71
+ print("\n💡 Ações sugeridas:")
72
+ for action in actions:
73
+ print(f" • {action}")
74
+ print()
75
+
76
+ except Exception as e:
77
+ print(f"❌ Erro: {e}")
78
+ return
79
+
80
+ # Example 2: Investigation with specific focus
81
+ print("\n" + "=" * 70)
82
+ print("📋 Exemplo 2: Investigação com Foco Específico")
83
+ print("-" * 40)
84
+
85
+ message = "Investigar anomalias em contratos de medicamentos e vacinas"
86
+ print(f"👤 Usuário: {message}")
87
+ print()
88
+
89
+ try:
90
+ response = await send_chat_message(session, message, session_id)
91
+
92
+ print(f"🤖 Cidadão.AI:")
93
+ print(response.get("message", "Sem resposta"))
94
+
95
+ except Exception as e:
96
+ print(f"❌ Erro: {e}")
97
+
98
+
99
+ async def demo_chat_flow():
100
+ """Demonstrate a complete chat flow"""
101
+ print("\n" + "=" * 70)
102
+ print("💬 Demonstração de Conversa Completa")
103
+ print("=" * 70)
104
+ print()
105
+
106
+ async with aiohttp.ClientSession() as session:
107
+ session_id = f"chat_demo_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
108
+
109
+ conversations = [
110
+ "Olá, o que você pode fazer?",
111
+ "Quero investigar contratos suspeitos",
112
+ "Analise contratos de TI do governo federal em 2024",
113
+ "Existem dados abertos sobre esses contratos?"
114
+ ]
115
+
116
+ for i, msg in enumerate(conversations, 1):
117
+ print(f"\n🔹 Mensagem {i}:")
118
+ print(f"👤 Usuário: {msg}")
119
+
120
+ try:
121
+ response = await send_chat_message(session, msg, session_id)
122
+
123
+ print(f"\n🤖 Cidadão.AI:")
124
+ print(response.get("message", "Sem resposta"))
125
+
126
+ # Show metadata if interesting
127
+ metadata = response.get("metadata", {})
128
+ if metadata.get("intent_type"):
129
+ print(f"\n[Intent detectado: {metadata['intent_type']}]")
130
+
131
+ await asyncio.sleep(1) # Small delay between messages
132
+
133
+ except Exception as e:
134
+ print(f"❌ Erro: {e}")
135
+ break
136
+
137
+
138
+ def print_instructions():
139
+ """Print instructions for running the demo"""
140
+ print("\n" + "=" * 70)
141
+ print("📖 INSTRUÇÕES")
142
+ print("=" * 70)
143
+ print()
144
+ print("1. Certifique-se de que o backend está rodando:")
145
+ print(" $ make run-dev")
146
+ print()
147
+ print("2. Se necessário, ajuste API_BASE_URL e API_KEY no script")
148
+ print()
149
+ print("3. Execute o script:")
150
+ print(" $ python examples/chat_dados_gov_demo.py")
151
+ print()
152
+ print("4. Observe como o sistema:")
153
+ print(" • Detecta automaticamente pedidos de investigação")
154
+ print(" • Busca dados no Portal da Transparência")
155
+ print(" • Enriquece com informações do dados.gov.br")
156
+ print(" • Sugere explorar datasets relacionados")
157
+ print()
158
+
159
+
160
+ async def check_api_health():
161
+ """Check if API is available"""
162
+ try:
163
+ async with aiohttp.ClientSession() as session:
164
+ async with session.get(f"{API_BASE_URL}/health") as response:
165
+ if response.status == 200:
166
+ return True
167
+ except:
168
+ pass
169
+ return False
170
+
171
+
172
+ async def main():
173
+ """Main demo function"""
174
+ print_instructions()
175
+
176
+ # Check API health
177
+ print("🔍 Verificando conexão com a API...")
178
+ if not await check_api_health():
179
+ print("❌ API não está disponível em", API_BASE_URL)
180
+ print(" Execute 'make run-dev' primeiro")
181
+ return
182
+
183
+ print("✅ API disponível!")
184
+ print()
185
+
186
+ # Run demos
187
+ await demo_investigation_with_open_data()
188
+ await demo_chat_flow()
189
+
190
+ print("\n" + "=" * 70)
191
+ print("✅ Demonstração concluída!")
192
+ print("=" * 70)
193
+
194
+
195
+ if __name__ == "__main__":
196
+ asyncio.run(main())