-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
232 lines (181 loc) · 7.09 KB
/
main.py
File metadata and controls
232 lines (181 loc) · 7.09 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
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#!/usr/bin/env python3
"""
Transaction Anomaly Analysis Agent
Architecture with specialized sub-agents + LangChain + Redis + Qdrant
Hackathon - November 2025
"""
import sys
import os
# Add directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from config import settings, LLMProvider
from orchestrator import Orchestrator, EXAMPLE_ALERTS
from services.vector_db_service import vector_db_service
from services.cache_service import cache_service
def show_banner():
"""Shows project banner."""
print("""
╔═══════════════════════════════════════════════════════════════╗
║ 🔍 TRANSACTION ANOMALY ANALYSIS AGENT ║
║ ║
║ Architecture with Specialized Sub-Agents ║
║ LangChain • Redis • Qdrant • Multi-LLM ║
╚═══════════════════════════════════════════════════════════════╝
""")
def show_help():
"""Shows usage instructions."""
print("""
Usage:
python main.py [option]
Options:
--demo Run demonstration with mock data
--seed Populate vector database with sample incidents
--stats Show services statistics
--provider <name> Set LLM provider (anthropic, openai, ollama)
transaction_drop Example alert: 40% drop in transactions
high_latency Example alert: P99 latency above threshold
partner_error Example alert: high error rate with partner
--help, -h Show this help
Environment variables:
ANTHROPIC_API_KEY Anthropic API key (Claude)
OPENAI_API_KEY OpenAI API key
LLM_PROVIDER Default provider (anthropic, openai, ollama)
REDIS_URL Redis URL (default: redis://localhost:6379)
QDRANT_URL Qdrant URL (default: http://localhost:6333)
Docker:
docker-compose up -d # Start Redis + Qdrant
docker-compose run app python main.py --demo
Examples:
python main.py --demo # Demo with mocks
python main.py --seed # Populate vector database
python main.py transaction_drop # Analyze alert
python main.py --provider openai partner_error
""")
def show_stats():
"""Shows services statistics."""
print("\n📊 Services Statistics\n")
# Redis
print("Redis:")
if cache_service.connect():
stats = cache_service.get_stats()
print(f" Status: ✓ Connected")
print(f" Keys: {stats.get('total_keys', 0)}")
print(f" Hits: {stats.get('hits', 0)}")
print(f" Misses: {stats.get('misses', 0)}")
else:
print(" Status: ✗ Disconnected")
print()
# Qdrant
print("Qdrant:")
if vector_db_service.connect():
stats = vector_db_service.get_stats()
print(f" Status: ✓ Connected")
print(f" Collection: {stats.get('collection', 'N/A')}")
print(f" Incidents: {stats.get('total_incidents', 0)}")
else:
print(" Status: ✗ Disconnected")
print()
# Config
print("Configuration:")
print(f" LLM Provider: {settings.llm_provider.value}")
print(f" Demo Mode: {settings.demo_mode}")
print(f" Reports Dir: {settings.reports_dir}")
def seed_database():
"""Populates vector database with sample data."""
print("\n🌱 Populating vector database with sample incidents...\n")
if not vector_db_service.connect():
print("✗ Error: Could not connect to Qdrant")
print(" Make sure the service is running:")
print(" docker-compose up -d qdrant")
return False
added = vector_db_service.seed_mock_incidents()
print(f"✓ {added} incidents added to vector database")
# Show stats
stats = vector_db_service.get_stats()
print(f" Total incidents: {stats.get('total_incidents', 0)}")
return True
def run_demo():
"""Runs demonstration with mock data."""
# Force demo mode
settings.demo_mode = True
# Connect services to show interaction
print("\n🔌 Connecting services...")
redis_ok = cache_service.connect()
qdrant_ok = vector_db_service.connect()
if redis_ok:
print(" ✓ Redis connected")
else:
print(" ⚠️ Redis unavailable (cache disabled)")
if qdrant_ok:
print(" ✓ Qdrant connected")
stats = vector_db_service.get_stats()
if stats.get("total_incidents", 0) == 0:
print(" 📝 Populating vector database with sample data...")
vector_db_service.seed_mock_incidents()
else:
print(" ⚠️ Qdrant unavailable (pre-analysis disabled)")
# Run analysis
alert = EXAMPLE_ALERTS["transaction_drop"]
orchestrator = Orchestrator(verbose=True, parallel=True)
report = orchestrator.investigate(alert)
print(report)
def main():
"""Main function."""
args = sys.argv[1:]
# Help
if "--help" in args or "-h" in args:
show_banner()
show_help()
return
# Stats
if "--stats" in args:
show_stats()
return
# Seed
if "--seed" in args:
seed_database()
return
# Provider
if "--provider" in args:
idx = args.index("--provider")
if idx + 1 < len(args):
provider_name = args[idx + 1].lower()
try:
settings.llm_provider = LLMProvider(provider_name)
print(f"✓ LLM Provider: {settings.llm_provider.value}")
except ValueError:
print(f"✗ Invalid provider: {provider_name}")
print(f" Options: anthropic, openai, ollama")
return
args.remove("--provider")
args.remove(provider_name)
# Demo
if "--demo" in args or not args:
show_banner()
run_demo()
return
# Check API key
has_api_key = (
(settings.llm_provider == LLMProvider.ANTHROPIC and settings.anthropic_api_key) or
(settings.llm_provider == LLMProvider.OPENAI and settings.openai_api_key) or
(settings.llm_provider == LLMProvider.OLLAMA)
)
if not has_api_key:
print(f"⚠️ API key not configured for {settings.llm_provider.value}")
print(" Running in demonstration mode...\n")
show_banner()
run_demo()
return
# Example alert
alert_name = args[0] if args else "transaction_drop"
if alert_name in EXAMPLE_ALERTS:
show_banner()
orchestrator = Orchestrator(verbose=True, parallel=True)
report = orchestrator.investigate(EXAMPLE_ALERTS[alert_name])
print(report)
else:
print(f"✗ Alert '{alert_name}' not found")
print(f" Options: {list(EXAMPLE_ALERTS.keys())}")
sys.exit(1)
if __name__ == "__main__":
main()