-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
411 lines (336 loc) Β· 14.3 KB
/
main.py
File metadata and controls
411 lines (336 loc) Β· 14.3 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import click
import time
import json
import logging
from typing import Dict, Any, Optional
from pathlib import Path
from data_processor import DataProcessor
from vector_store import VectorStore
from agent import query_hyperliquid_agent, PRODUCTION_CONFIG
# Configure CLI logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
@click.group()
@click.option('--debug', is_flag=True, help='Enable debug logging')
@click.option('--config-file', type=click.Path(exists=True), help='Path to configuration JSON file')
@click.pass_context
def cli(ctx, debug, config_file):
"""HyperLiquid Market Intelligence Agent CLI
Production-ready tool for analyzing HyperLiquid market sentiment,
trends, and mentions across various crypto data sources.
"""
# Ensure context object exists
ctx.ensure_object(dict)
# Set debug level
if debug:
logging.getLogger().setLevel(logging.DEBUG)
logger.debug("Debug mode enabled")
# Load configuration
config = PRODUCTION_CONFIG.copy()
if config_file:
try:
with open(config_file, 'r') as f:
custom_config = json.load(f)
config.update(custom_config)
logger.info(f"Configuration loaded from {config_file}")
except Exception as e:
logger.error(f"Failed to load config file: {e}")
click.echo(f"β Error loading config: {e}", err=True)
raise click.Abort()
ctx.obj['config'] = config
@cli.command()
@click.option('--jsonl-file',
default='data/hyperliquid_mentions.json',
type=click.Path(exists=True),
help='Path to JSONL data file')
@click.option('--batch-size',
default=100,
type=int,
help='Processing batch size')
@click.option('--force',
is_flag=True,
help='Force re-ingestion even if data exists')
@click.pass_context
def ingest(ctx, jsonl_file, batch_size, force):
"""Ingest JSONL data into vector store with production optimizations"""
start_time = time.time()
try:
click.echo("π Starting HyperLiquid data ingestion...")
click.echo(f"π Source file: {jsonl_file}")
click.echo(f"π¦ Batch size: {batch_size}")
# Initialize components
processor = DataProcessor()
vector_store = VectorStore()
# Check if data already exists
if not force:
try:
test_results = vector_store.search("HyperLiquid", top_k=1)
if test_results:
click.echo("β οΈ Data already exists in vector store.")
if not click.confirm("Continue with ingestion anyway?"):
click.echo("Ingestion cancelled.")
return
except Exception:
pass # Continue if check fails
# Process JSONL file
click.echo("\nπ Processing JSONL file...")
with click.progressbar(length=1, label='Loading data') as bar:
mentions = processor.process_jsonl_file(jsonl_file)
bar.update(1)
click.echo(f"β
Processed {len(mentions)} mentions")
# Create chunks with progress tracking
click.echo("\nπ¨ Creating text chunks...")
with click.progressbar(mentions, label='Creating chunks') as bar:
chunks = []
for mention in bar:
mention_chunks = processor.create_mention_chunks(mention)
chunks.extend(mention_chunks)
click.echo(f"β
Created {len(chunks)} chunks")
# Store in vector database with batching
click.echo(f"\nπΎ Storing in vector database (batch size: {batch_size})...")
total_batches = (len(chunks) + batch_size - 1) // batch_size
with click.progressbar(length=total_batches, label='Storing batches') as bar:
for i in range(0, len(chunks), batch_size):
batch = chunks[i:i + batch_size]
vector_store.store_chunks(batch)
bar.update(1)
time.sleep(0.1) # Prevent rate limiting
# Verify ingestion
click.echo("\nπ Verifying ingestion...")
test_results = vector_store.search("HyperLiquid", top_k=5)
execution_time = time.time() - start_time
if test_results:
click.echo(f"β
Ingestion successful!")
click.echo(f"π Verification: Found {len(test_results)} test results")
click.echo(f"β±οΈ Total time: {execution_time:.2f}s")
else:
click.echo("β Ingestion verification failed!")
raise click.Abort()
except Exception as e:
logger.error(f"Ingestion failed: {e}")
click.echo(f"β Ingestion failed: {e}", err=True)
raise click.Abort()
@cli.command()
@click.argument('query')
@click.option('--top-k',
default=15,
type=int,
help='Number of results to return')
@click.option('--output-format',
type=click.Choice(['detailed', 'summary', 'json']),
default='detailed',
help='Output format')
@click.option('--save-results',
type=click.Path(),
help='Save results to file')
@click.pass_context
def search(ctx, query, top_k, output_format, save_results):
"""Search HyperLiquid mentions using AI agent
Examples:
python main.py search "What are people saying about HyperLiquid vaults?"
python main.py search "HYPE token price sentiment" --top-k 20
python main.py search "influencer tweets" --output-format summary
"""
start_time = time.time()
try:
# Validate inputs
if not query.strip():
click.echo("β Error: Query cannot be empty", err=True)
raise click.Abort()
if top_k <= 0 or top_k > 50:
click.echo("β Error: top-k must be between 1 and 50", err=True)
raise click.Abort()
# Update config with CLI parameters
config = ctx.obj['config'].copy()
config['top_k'] = top_k
config['output_format'] = output_format
click.echo(f"π Searching: '{query}'")
click.echo(f"π Results: {top_k} | Format: {output_format}")
click.echo("=" * 80)
if output_format == 'json':
# JSON output for programmatic use
from agent import HyperLiquidAgent
agent = HyperLiquidAgent(config)
results = agent.search_mentions(query, top_k)
json_output = {
'query': query,
'timestamp': time.time(),
'execution_time': time.time() - start_time,
'results': results
}
output_text = json.dumps(json_output, indent=2)
click.echo(output_text)
elif output_format == 'summary':
# Brief summary output
config['reasoning'] = False
config['show_tool_calls'] = False
query_hyperliquid_agent(query, config)
else:
# Detailed output (default)
query_hyperliquid_agent(query, config)
# Save results if requested
if save_results:
execution_time = time.time() - start_time
save_path = Path(save_results)
with open(save_path, 'w') as f:
f.write(f"Query: {query}\n")
f.write(f"Timestamp: {time.ctime()}\n")
f.write(f"Execution Time: {execution_time:.2f}s\n")
f.write("=" * 80 + "\n\n")
# Results would be written here in a real implementation
click.echo(f"\nπΎ Results saved to: {save_path}")
except Exception as e:
logger.error(f"Search failed: {e}")
click.echo(f"β Search failed: {e}", err=True)
raise click.Abort()
@cli.command()
@click.option('--mode',
type=click.Choice(['quick', 'comprehensive']),
default='quick',
help='Demo mode')
@click.pass_context
def demo(ctx, mode):
"""Run demonstration queries
Quick mode: Essential queries for HyperLiquid analysis
Comprehensive mode: Extended set of market intelligence queries
"""
quick_queries = [
"What are people saying about HyperLiquid's vaults?",
"Any influencer tweets about HyperLiquid recently?",
"HYPE token price sentiment analysis"
]
comprehensive_queries = quick_queries + [
"HyperLiquid vs other DEX mentions",
"HyperLiquid security concerns or exploits",
"HyperLiquid TVL and trading volume discussions",
"James Wynn HyperLiquid trading performance",
"HyperLiquid yield farming opportunities",
"HYPE token staking and rewards"
]
queries = comprehensive_queries if mode == 'comprehensive' else quick_queries
config = ctx.obj['config'].copy()
click.echo(f"π¬ Running {mode} demo with {len(queries)} queries...")
click.echo("=" * 80)
for i, query in enumerate(queries, 1):
click.echo(f"\nπ Demo Query {i}/{len(queries)}: {query}")
click.echo("-" * 60)
try:
query_hyperliquid_agent(query, config)
except Exception as e:
click.echo(f"β Query failed: {e}")
if i < len(queries):
click.echo("\n" + "="*100 + "\n")
time.sleep(1) # Brief pause between queries
@cli.command()
@click.option('--export-format',
type=click.Choice(['json', 'csv']),
default='json',
help='Export format')
@click.option('--output-file',
type=click.Path(),
help='Output file path')
def status(export_format, output_file):
"""Show system status and performance metrics"""
try:
from agent import HyperLiquidAgent
click.echo("π HyperLiquid Agent System Status")
click.echo("=" * 50)
# Initialize agent to get metrics
agent = HyperLiquidAgent()
# Test vector store connectivity
click.echo("\nπ Connectivity Tests:")
try:
test_results = agent.vector_store.search("test", top_k=1)
click.echo(" β
Vector store: Connected")
click.echo(f" π Sample query returned {len(test_results)} results")
except Exception as e:
click.echo(f" β Vector store: {e}")
# Get performance metrics
click.echo("\nπ Performance Metrics:")
metrics = agent.get_performance_metrics()
for key, value in metrics.items():
if isinstance(value, float):
click.echo(f" ββ {key.replace('_', ' ').title()}: {value:.3f}")
elif isinstance(value, list):
click.echo(f" ββ {key.replace('_', ' ').title()}: {len(value)} items")
else:
click.echo(f" ββ {key.replace('_', ' ').title()}: {value}")
# Export if requested
if output_file:
export_data = {
'timestamp': time.time(),
'status': 'operational',
'metrics': metrics
}
if export_format == 'json':
with open(output_file, 'w') as f:
json.dump(export_data, f, indent=2)
else: # csv
# CSV export logic would go here
pass
click.echo(f"\nπΎ Status exported to: {output_file}")
except Exception as e:
logger.error(f"Status check failed: {e}")
click.echo(f"β Status check failed: {e}", err=True)
@cli.command()
@click.option('--days', default=30, type=int, help='Analysis period in days')
@click.option('--save-report', type=click.Path(), help='Save trend report to file')
def trends(days, save_report):
"""Generate comprehensive trends analysis"""
try:
click.echo(f"π Generating {days}-day trend analysis...")
from agent import HyperLiquidAgent
agent = HyperLiquidAgent()
# Generate trends report
trends_report = agent.analyze_trends(f"{days}d")
click.echo("=" * 80)
click.echo(trends_report)
# Save report if requested
if save_report:
with open(save_report, 'w') as f:
f.write(f"HyperLiquid Trends Analysis - {days} Days\n")
f.write(f"Generated: {time.ctime()}\n")
f.write("=" * 80 + "\n\n")
f.write(trends_report)
click.echo(f"\nπΎ Trend report saved to: {save_report}")
except Exception as e:
logger.error(f"Trends analysis failed: {e}")
click.echo(f"β Trends analysis failed: {e}", err=True)
@cli.command()
def config():
"""Show current configuration"""
click.echo("βοΈ Current Configuration:")
click.echo("=" * 40)
for key, value in PRODUCTION_CONFIG.items():
if isinstance(value, dict):
click.echo(f"{key}:")
for sub_key, sub_value in value.items():
click.echo(f" ββ {sub_key}: {sub_value}")
else:
click.echo(f"{key}: {value}")
@cli.command()
@click.argument('query')
@click.option('--continuous', is_flag=True, help='Run continuous monitoring')
@click.option('--interval', default=300, type=int, help='Check interval in seconds')
def monitor(query, continuous, interval):
"""Monitor specific query for changes over time"""
click.echo(f"ποΈ Monitoring: '{query}'")
if continuous:
click.echo(f"π Continuous mode: checking every {interval}s")
click.echo("Press Ctrl+C to stop")
try:
while True:
click.echo(f"\nβ° Check at {time.ctime()}")
query_hyperliquid_agent(query)
click.echo(f"\nπ΄ Sleeping for {interval}s...")
time.sleep(interval)
except KeyboardInterrupt:
click.echo("\nπ Monitoring stopped by user")
else:
# Single check
query_hyperliquid_agent(query)
if __name__ == "__main__":
cli()