-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.py
More file actions
executable file
·2304 lines (1899 loc) · 93.5 KB
/
run.py
File metadata and controls
executable file
·2304 lines (1899 loc) · 93.5 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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
AgentLead - Main Application Entry Point and CLI Interface
A comprehensive lead extraction and research platform that integrates
Kimi K2 extraction, AI-powered research, personalized outreach, and cost tracking.
Features:
- Command-line interface for all operations
- Web dashboard for monitoring (optional)
- Batch processing capabilities
- Configuration validation
- Health checks and status reporting
- Integration of all components
Usage:
python run.py extract --url https://company.com
python run.py outreach --leads-file leads.csv --output outreach_campaigns
python run.py monitor --dashboard
python run.py health --full
python run.py batch process --config batch_config.json
"""
import argparse
import asyncio
import csv
import json
import sys
import os
import logging
import signal
import time
import glob
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional, Any, Union
from dataclasses import dataclass, asdict
from decimal import Decimal
import threading
import multiprocessing
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
# Add project root to path
project_root = Path(__file__).parent
sys.path.append(str(project_root))
# Import core components with error handling
try:
import sys
sys.path.insert(0, str(project_root))
from src.core.kimi_extractor import KimiK2Extractor, IndustryType, LeadQuality
HAS_KIMI_EXTRACTOR = True
except ImportError as e:
print(f"Warning: Could not import Kimi extractor: {e}")
HAS_KIMI_EXTRACTOR = False
# Define dummy classes
class IndustryType:
TECHNOLOGY = "technology"
class LeadQuality:
HOT = "hot"
# Cost tracking removed - was causing complexity without proper integration
try:
from src.core.crawler_manager import CrawlerManager
HAS_CRAWLER_MANAGER = True
except ImportError as e:
print(f"Warning: Could not import crawler manager: {e}")
HAS_CRAWLER_MANAGER = False
# SmartLead client removed - not in use
# Clay enrichment functionality removed - not in use
# Import multi-agent components
try:
from src.agents import (
OutreachCrew, LeadProfile, CompanyResearcher,
set_progress_callback, print_progress_update
)
from src.core.research_exporter import ResearchExporter, quick_export_research
HAS_MULTI_AGENT = True
except ImportError as e:
print(f"Warning: Could not import multi-agent components: {e}")
HAS_MULTI_AGENT = False
try:
from config.kimi_config import get_config, validate_config, get_industry_config
HAS_KIMI_CONFIG = True
except ImportError as e:
print(f"Warning: Could not import Kimi config: {e}")
HAS_KIMI_CONFIG = False
# Import utilities with fallbacks
from dotenv import load_dotenv
try:
import structlog
HAS_STRUCTLOG = True
except ImportError:
import logging
structlog = logging
HAS_STRUCTLOG = False
try:
from rich.console import Console
from rich.table import Table
from rich.progress import Progress, TaskID
from rich.panel import Panel
from rich.text import Text
from rich import print as rprint
HAS_RICH = True
console = Console()
except ImportError:
HAS_RICH = False
console = None
def rprint(text):
print(text)
try:
import click
HAS_CLICK = True
except ImportError:
HAS_CLICK = False
print("Error: Click is required for CLI functionality. Please install with: pip install click")
# Load environment variables
load_dotenv()
# Configure structured logging
if HAS_STRUCTLOG:
structlog.configure(
processors=[
structlog.stdlib.filter_by_level,
structlog.stdlib.add_logger_name,
structlog.stdlib.add_log_level,
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
structlog.processors.UnicodeDecoder(),
structlog.processors.JSONRenderer()
],
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
wrapper_class=structlog.stdlib.BoundLogger,
cache_logger_on_first_use=True,
)
logger = structlog.get_logger(__name__)
else:
logger = logging.getLogger(__name__)
@dataclass
class AppConfig:
"""Main application configuration."""
debug: bool = False
log_level: str = "INFO"
max_workers: int = 4
batch_size: int = 10
enable_dashboard: bool = False
dashboard_port: int = 8080
health_check_interval: int = 300 # 5 minutes
# Cost tracking removed
auto_save_interval: int = 60 # seconds
# Clay enrichment configuration removed - not in use
def __post_init__(self):
"""Validate configuration."""
if self.max_workers <= 0:
self.max_workers = multiprocessing.cpu_count()
if self.batch_size <= 0:
self.batch_size = 10
# Clay configuration removed
class AgentLeadApp:
"""Main AgentLead application class."""
def __init__(self, config: Optional[AppConfig] = None):
"""Initialize the AgentLead application."""
self.config = config or AppConfig()
# Initialize config if available
if HAS_KIMI_CONFIG:
self.kimi_config = get_config()
else:
self.kimi_config = None
self.running = False
self.health_status = {}
# Initialize components
self.extractor = None
# Cost tracking removed
# SmartLead client removed
self.crawler_manager = None
# Clay client removed
# Background tasks
self.health_check_task = None
self.auto_save_task = None
# Setup logging
self._setup_logging()
# Signal handlers
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGTERM, self._signal_handler)
def _setup_logging(self):
"""Setup application logging."""
level = getattr(logging, self.config.log_level.upper(), logging.INFO)
logging.basicConfig(
level=level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
if self.config.debug:
logging.getLogger().setLevel(logging.DEBUG)
def _signal_handler(self, signum, frame):
"""Handle shutdown signals."""
if HAS_STRUCTLOG:
logger.info("Received shutdown signal", signal=signum)
else:
logger.info(f"Received shutdown signal: {signum}")
self.shutdown()
async def initialize(self) -> bool:
"""Initialize all application components."""
print("Initializing AgentLead application")
try:
# Validate configuration if available
if HAS_KIMI_CONFIG and self.kimi_config:
validate_config(self.kimi_config)
print("✓ Configuration validated")
# Cost tracking removed - was causing complexity without proper integration
# Initialize Kimi K2 extractor
if HAS_KIMI_EXTRACTOR:
# Get API key from environment
api_key = os.getenv('OPENROUTER_API_KEY') or os.getenv('KIMI_API_KEY')
if api_key:
self.extractor = KimiK2Extractor(
api_key=api_key,
base_url="https://openrouter.ai/api/v1" if os.getenv('OPENROUTER_API_KEY') else "https://api.moonshot.cn/v1"
)
print("✓ Kimi K2 extractor initialized")
else:
print("⚠️ No API key found for Kimi K2 extractor")
self.extractor = None
else:
print("⚠️ Kimi K2 extractor not available")
self.extractor = None
# SmartLead client initialization removed
# Initialize crawler manager
if HAS_CRAWLER_MANAGER:
self.crawler_manager = CrawlerManager()
print("✓ Crawler manager initialized")
else:
print("⚠️ Crawler manager not available")
# Clay integration removed - not in use
# Update health status
await self.check_health()
self.running = True
print("✅ AgentLead application initialized successfully")
return True
except Exception as e:
print(f"❌ Failed to initialize application: {e}")
return False
async def shutdown(self):
"""Shutdown the application gracefully."""
if HAS_STRUCTLOG:
logger.info("Shutting down AgentLead application")
else:
logger.info("Shutting down AgentLead application")
self.running = False
# Cancel background tasks
if self.health_check_task:
self.health_check_task.cancel()
if self.auto_save_task:
self.auto_save_task.cancel()
# Cleanup components
# Cost tracking removed
if self.extractor:
await self.extractor.close()
# Clay client shutdown removed
print("✅ Application shutdown complete")
async def check_health(self) -> Dict[str, Any]:
"""Perform comprehensive health checks."""
health_status = {
"timestamp": datetime.now().isoformat(),
"overall_status": "healthy",
"components": {}
}
# Check Kimi K2 extractor
try:
if self.extractor:
# Simple API connectivity test
test_result = await self.extractor.test_connection()
health_status["components"]["kimi_extractor"] = {
"status": "healthy" if test_result else "unhealthy",
"last_check": datetime.now().isoformat()
}
else:
health_status["components"]["kimi_extractor"] = {
"status": "not_initialized",
"last_check": datetime.now().isoformat()
}
except Exception as e:
health_status["components"]["kimi_extractor"] = {
"status": "error",
"error": str(e),
"last_check": datetime.now().isoformat()
}
# Cost tracking removed from health checks
# SmartLead client health check removed
# Clay client health check removed
# Check system resources
try:
import psutil
health_status["system"] = {
"cpu_percent": psutil.cpu_percent(),
"memory_percent": psutil.virtual_memory().percent,
"disk_usage": psutil.disk_usage('/').percent
}
except ImportError:
health_status["system"] = {"status": "monitoring_unavailable"}
# Determine overall status
component_statuses = [
comp["status"] for comp in health_status["components"].values()
]
if "error" in component_statuses or "unhealthy" in component_statuses:
health_status["overall_status"] = "degraded"
elif all(status in ["healthy", "disabled", "not_configured"] for status in component_statuses):
health_status["overall_status"] = "healthy"
else:
health_status["overall_status"] = "unknown"
self.health_status = health_status
return health_status
async def extract_leads(self,
content: str = None,
url: str = None,
file_path: str = None,
industry: str = "technology",
output_format: str = "json",
output_file: str = None) -> Dict[str, Any]:
"""Extract leads from various sources."""
if not self.extractor:
raise RuntimeError("Extractor not initialized")
# Extract lead using appropriate method
industry_type = IndustryType(industry.upper()) if hasattr(IndustryType, industry.upper()) else IndustryType.TECHNOLOGY
if url:
# Direct URL extraction using integrated Firecrawl crawler
result = await self.extractor.extract_lead_from_url(
url=url,
industry=industry_type
)
else:
# Content-based extraction
if file_path:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
elif not content:
raise ValueError("Must provide content, URL, or file path")
result = await self.extractor.extract_lead(
content=content,
industry=industry_type,
source_url=url
)
# Format output
if result.success:
output_data = {
"extraction_timestamp": datetime.now().isoformat(),
"source": url or file_path or "direct_input",
"industry": industry,
"lead_data": result.lead_data.model_dump() if result.lead_data else None,
"metadata": {
"extractor_version": "1.0.0",
"processing_time": result.processing_time,
"token_usage": result.token_usage,
"extraction_id": result.extraction_id,
"retry_count": result.retry_count
}
}
else:
raise RuntimeError(f"Lead extraction failed: {result.error_message}")
# Save output if requested
if output_file:
if output_format.lower() == "json":
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(output_data, f, indent=2, default=str)
elif output_format.lower() == "csv":
import pandas as pd
df = pd.json_normalize(output_data["lead_data"])
df.to_csv(output_file, index=False)
return output_data
async def batch_process_leads(self,
config_file: str,
progress_callback=None,
resume_from: int = 0) -> Dict[str, Any]:
"""Process multiple leads in batch with incremental updates and resume capability."""
with open(config_file, 'r') as f:
batch_config = json.load(f)
inputs = batch_config.get("inputs", [])
industry = batch_config.get("industry", "technology")
output_dir = batch_config.get("output_directory", "batch_results")
# Create output directory
os.makedirs(output_dir, exist_ok=True)
# Check for existing progress
summary_file = f"{output_dir}/batch_summary.json"
if resume_from == 0 and os.path.exists(summary_file):
try:
with open(summary_file, 'r') as f:
existing_summary = json.load(f)
resume_from = existing_summary.get("last_processed_index", 0)
if resume_from > 0:
logger.info(f"Resuming from index {resume_from}")
except Exception as e:
logger.warning(f"Could not load existing summary: {e}")
resume_from = 0
results = []
errors = []
# Load existing results if resuming
if resume_from > 0:
existing_files = glob.glob(f"{output_dir}/lead_*.json")
results = [{"output_file": f} for f in existing_files]
logger.info(f"Found {len(results)} existing lead files")
# Skip already processed inputs
inputs_to_process = inputs[resume_from:]
if HAS_RICH:
with Progress() as progress:
task = progress.add_task("Processing leads...", total=len(inputs_to_process))
# Process in batches with incremental updates
for i in range(0, len(inputs_to_process), self.config.batch_size):
batch = inputs_to_process[i:i + self.config.batch_size]
batch_results = await self._process_batch(batch, industry, output_dir)
# Process results and update summary incrementally
for j, result in enumerate(batch_results):
if isinstance(result, Exception):
error_result = {
"error": str(result),
"input": batch[j],
"timestamp": datetime.now().isoformat(),
"index": resume_from + i + j
}
errors.append(error_result)
elif "error" in result:
result["index"] = resume_from + i + j
errors.append(result)
else:
result["index"] = resume_from + i + j
results.append(result)
# Update summary after each batch
current_summary = self._generate_incremental_summary(
inputs, results, errors, output_dir, resume_from + i + len(batch)
)
# Save incremental summary
with open(summary_file, 'w') as f:
json.dump(current_summary, f, indent=2, default=str)
progress.update(task, advance=len(batch))
if progress_callback:
progress_callback(len(results), len(errors), len(inputs))
else:
# Fallback without rich progress bar
for i in range(0, len(inputs_to_process), self.config.batch_size):
batch = inputs_to_process[i:i + self.config.batch_size]
batch_results = await self._process_batch(batch, industry, output_dir)
for j, result in enumerate(batch_results):
if isinstance(result, Exception):
error_result = {
"error": str(result),
"input": batch[j],
"timestamp": datetime.now().isoformat(),
"index": resume_from + i + j
}
errors.append(error_result)
elif "error" in result:
result["index"] = resume_from + i + j
errors.append(result)
else:
result["index"] = resume_from + i + j
results.append(result)
# Update summary after each batch
current_summary = self._generate_incremental_summary(
inputs, results, errors, output_dir, resume_from + i + len(batch)
)
with open(summary_file, 'w') as f:
json.dump(current_summary, f, indent=2, default=str)
# Generate final summary with quality metrics
final_summary = self._generate_final_summary(inputs, results, errors, output_dir)
# Save final summary
with open(summary_file, 'w') as f:
json.dump(final_summary, f, indent=2, default=str)
return final_summary
def _generate_incremental_summary(self, inputs: List[Dict], results: List[Dict],
errors: List[Dict], output_dir: str,
last_processed_index: int) -> Dict[str, Any]:
"""Generate incremental summary during batch processing."""
total_processed = len(results) + len(errors)
success_rate = (len(results) / total_processed * 100) if total_processed > 0 else 0
return {
"timestamp": datetime.now().isoformat(),
"total_inputs": len(inputs),
"last_processed_index": last_processed_index,
"total_processed": total_processed,
"successful": len(results),
"failed": len(errors),
"success_rate": success_rate,
"output_directory": output_dir,
"processing_status": "in_progress",
"estimated_completion": f"{total_processed}/{len(inputs)} ({(total_processed/len(inputs)*100):.1f}%)",
"errors": errors[:5] if errors else [] # Keep only first 5 errors for size
}
def _generate_final_summary(self, inputs: List[Dict], results: List[Dict],
errors: List[Dict], output_dir: str) -> Dict[str, Any]:
"""Generate comprehensive final summary with quality metrics."""
# Count actual lead files
lead_files = glob.glob(f"{output_dir}/lead_*.json")
actual_leads_generated = len(lead_files)
# Analyze lead quality by sampling files
quality_metrics = self._analyze_lead_quality(lead_files[:10]) # Sample first 10
# Calculate costs
total_cost = 0
total_tokens = 0
for lead_file in lead_files[:20]: # Sample 20 files for cost analysis
try:
with open(lead_file, 'r') as f:
lead_data = json.load(f)
token_usage = lead_data.get("metadata", {}).get("token_usage", {})
if "estimated_cost" in token_usage:
total_cost += float(token_usage["estimated_cost"])
if "total_tokens" in token_usage:
total_tokens += int(token_usage["total_tokens"])
except Exception:
continue
# Extrapolate costs
if total_cost > 0:
avg_cost_per_lead = total_cost / min(20, len(lead_files))
estimated_total_cost = avg_cost_per_lead * actual_leads_generated
else:
estimated_total_cost = 0
success_rate = (len(results) / len(inputs) * 100) if len(inputs) > 0 else 0
return {
"timestamp": datetime.now().isoformat(),
"total_processed": len(inputs),
"successful": len(results),
"failed": len(errors),
"success_rate": success_rate,
"output_directory": output_dir,
"processing_status": "completed",
"campaign_summary": {
"total_leads_generated": actual_leads_generated,
"target_met": actual_leads_generated >= 80, # 80% of 100 target
"estimated_total_cost": round(estimated_total_cost, 3),
"average_cost_per_lead": round(estimated_total_cost / actual_leads_generated, 4) if actual_leads_generated > 0 else 0,
"total_tokens_estimated": total_tokens * (actual_leads_generated / min(20, len(lead_files))) if total_tokens > 0 else 0
},
"quality_metrics": quality_metrics,
"results": results[:10], # First 10 successful results
"errors": errors[:10] # First 10 errors
}
def _analyze_lead_quality(self, sample_files: List[str]) -> Dict[str, Any]:
"""Analyze quality metrics from sample lead files."""
if not sample_files:
return {"error": "No lead files to analyze"}
hot_leads = 0
warm_leads = 0
cold_leads = 0
total_confidence = 0
total_fit = 0
decision_makers_count = 0
companies_with_ceo = 0
companies_with_cto = 0
valid_samples = 0
for file_path in sample_files:
try:
with open(file_path, 'r') as f:
lead_data = json.load(f)
lead_info = lead_data.get("lead_data", {})
# Quality analysis
quality = lead_info.get("lead_quality", "").lower()
if "hot" in quality:
hot_leads += 1
elif "warm" in quality:
warm_leads += 1
else:
cold_leads += 1
# Confidence and fit scores
total_confidence += lead_info.get("confidence_score", 0)
total_fit += lead_info.get("fit_score", 0)
# Decision makers analysis
decision_makers = lead_info.get("decision_makers", [])
decision_makers_count += len(decision_makers)
# Executive analysis
for dm in decision_makers:
title = dm.get("title", "").lower()
if "ceo" in title or "chief executive" in title:
companies_with_ceo += 1
break
for dm in decision_makers:
title = dm.get("title", "").lower()
if "cto" in title or "chief technology" in title or "chief information" in title:
companies_with_cto += 1
break
valid_samples += 1
except Exception as e:
continue
if valid_samples == 0:
return {"error": "No valid lead files found"}
return {
"sample_size": valid_samples,
"hot_leads": hot_leads,
"warm_leads": warm_leads,
"cold_leads": cold_leads,
"average_confidence_score": round(total_confidence / valid_samples, 2),
"average_fit_score": round(total_fit / valid_samples, 2),
"total_decision_makers": decision_makers_count,
"avg_decision_makers_per_company": round(decision_makers_count / valid_samples, 1),
"companies_with_ceo_contact": companies_with_ceo,
"companies_with_cto_contact": companies_with_cto,
"executive_coverage": round((companies_with_ceo + companies_with_cto) / (valid_samples * 2) * 100, 1)
}
async def _process_batch(self, batch: List[Dict], industry: str, output_dir: str) -> List[Dict]:
"""Process a batch of leads concurrently."""
tasks = []
for item in batch:
task = self._process_single_item(item, industry, output_dir)
tasks.append(task)
return await asyncio.gather(*tasks, return_exceptions=True)
async def _process_single_item(self, item: Dict, industry: str, output_dir: str) -> Dict:
"""Process a single lead extraction item."""
try:
result = await self.extract_leads(
content=item.get("content"),
url=item.get("url"),
file_path=item.get("file_path"),
industry=industry
)
# Save individual result
filename = f"lead_{hash(str(item))}.json"
filepath = os.path.join(output_dir, filename)
with open(filepath, 'w') as f:
json.dump(result, f, indent=2, default=str)
result["output_file"] = filepath
return result
except Exception as e:
return {
"error": str(e),
"input": item,
"timestamp": datetime.now().isoformat()
}
# SmartLead campaign creation method removed
# Cost tracking report method removed - was broken and added complexity
def start_dashboard(self):
"""Start the web dashboard (if implemented)."""
# This would start a web server for monitoring
# Implementation would depend on chosen web framework (FastAPI, Flask, etc.)
logger.info("Dashboard feature not yet implemented")
pass
# CLI Commands using Click
@click.group()
@click.option('--debug', is_flag=True, help='Enable debug mode')
@click.option('--log-level', default='INFO', help='Set log level')
@click.pass_context
def cli(ctx, debug, log_level):
"""AgentLead - Lead Extraction, Enrichment, and Campaign Management Platform
Features:
- Lead extraction from URLs, files, and content using Kimi K2
- Multi-source research with AI-powered intelligence gathering
- Personalized outreach generation using CrewAI agents
- Cost tracking and usage analytics
- Real-time progress tracking
- Export capabilities and batch processing
- Health monitoring and configuration validation
Examples:
# Traditional lead extraction
python run.py extract --url https://company.com --enrich
python run.py batch --config batch_config.json --enrich
# Multi-agent research and outreach (NEW!)
python run.py research --leads-file leads.csv --output results --progress
python run.py outreach --leads-file leads.csv --output campaigns --concurrent 3
python run.py full-pipeline --leads-file leads.csv --output complete --progress
# Clay enrichment
python run.py enrich leads --leads-file leads.json
python run.py enrich status <enrichment-id>
python run.py enrich report --days 7 --detailed
# System monitoring
python run.py health --full
python run.py validate
"""
ctx.ensure_object(dict)
ctx.obj['debug'] = debug
ctx.obj['log_level'] = log_level
@cli.command()
@click.option('--content', help='Direct content input')
@click.option('--url', help='URL to extract content from')
@click.option('--file', 'file_path', help='File path to read content from')
@click.option('--industry', default='technology', help='Industry type for specialized extraction')
@click.option('--output-format', default='json', type=click.Choice(['json', 'csv']), help='Output format')
@click.option('--output-file', help='Output file path')
@click.option('--enrich', is_flag=True, help='Automatically enrich extracted leads with Clay')
@click.option('--enrich-types', default='email,phone,linkedin,company', help='Clay enrichment types (if --enrich used)')
@click.option('--enrich-priority', default='normal', type=click.Choice(['low', 'normal', 'high']), help='Clay enrichment priority')
@click.pass_context
async def extract(ctx, content, url, file_path, industry, output_format, output_file, enrich, enrich_types, enrich_priority):
"""Extract leads from content, URL, or file."""
app_config = AppConfig(
debug=ctx.obj['debug'],
log_level=ctx.obj['log_level'],
clay_enabled=enrich
)
app = AgentLeadApp(app_config)
try:
if not await app.initialize():
click.echo("❌ Failed to initialize application", err=True)
return
with console.status("[bold green]Extracting leads..."):
result = await app.extract_leads(
content=content,
url=url,
file_path=file_path,
industry=industry,
output_format=output_format,
output_file=output_file
)
# Enrich extracted lead if requested
if enrich and result.get("lead_data"):
try:
enrichment_types = [t.strip() for t in enrich_types.split(',')]
click.echo("🔄 Enriching extracted lead with Clay...")
with console.status("[bold green]Enriching lead..."):
enrichment_result = await app.enrich_lead_with_clay(
lead_data=result["lead_data"],
enrichment_types=enrichment_types,
priority=enrich_priority
)
# Add enrichment info to result
result["enrichment"] = enrichment_result
click.echo(f"✅ Lead enrichment initiated:")
click.echo(f" Enrichment ID: {enrichment_result['enrichment_id']}")
click.echo(f" Status: {enrichment_result['status']}")
if enrichment_result.get('cost_estimate'):
click.echo(f" Estimated cost: ${enrichment_result['cost_estimate']:.2f}")
# Save updated result if output file specified
if output_file:
if output_format.lower() == "json":
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(result, f, indent=2, default=str)
except Exception as e:
click.echo(f"⚠️ Enrichment failed: {e}")
click.echo("✅ Lead extraction completed without enrichment")
# Display results
if output_file:
click.echo(f"✅ Results saved to: {output_file}")
else:
click.echo(json.dumps(result, indent=2, default=str))
except Exception as e:
click.echo(f"❌ Error: {e}", err=True)
finally:
await app.shutdown()
@cli.command()
@click.option('--config', required=True, help='Batch configuration file')
@click.option('--progress/--no-progress', default=True, help='Show progress bar (default: enabled)')
@click.option('--resume', is_flag=True, help='Resume from last processed index')
@click.option('--resume-from', default=0, help='Resume from specific index')
@click.option('--enrich', is_flag=True, help='Automatically enrich processed leads with Clay')
@click.option('--enrich-types', default='email,phone,linkedin,company', help='Clay enrichment types (if --enrich used)')
@click.option('--enrich-priority', default='normal', type=click.Choice(['low', 'normal', 'high']), help='Clay enrichment priority')
@click.pass_context
async def batch(ctx, config, progress, resume, resume_from, enrich, enrich_types, enrich_priority):
"""Process multiple leads in batch."""
app_config = AppConfig(
debug=ctx.obj['debug'],
log_level=ctx.obj['log_level'],
clay_enabled=enrich
)
app = AgentLeadApp(app_config)
try:
if not await app.initialize():
click.echo("❌ Failed to initialize application", err=True)
return
def progress_callback(successful, failed, total):
if progress:
click.echo(f"Progress: {successful + failed}/{total} processed ({successful} successful, {failed} failed)")
# Determine resume index
start_index = resume_from if resume_from > 0 else (0 if not resume else 0)
result = await app.batch_process_leads(
config_file=config,
progress_callback=progress_callback if progress else None,
resume_from=start_index
)
click.echo(f"✅ Batch processing complete:")
click.echo(f" Total: {result['total_processed']}")
click.echo(f" Successful: {result['successful']}")
click.echo(f" Failed: {result['failed']}")
click.echo(f" Success Rate: {result['success_rate']:.1f}%")
click.echo(f" Results saved to: {result['output_directory']}")
# Auto-enrich if requested and we have successful results
if enrich and result['successful'] > 0:
try:
click.echo("\n🔄 Starting automatic enrichment of extracted leads...")
# Create a file with the batch results for enrichment
batch_leads_file = f"{result['output_directory']}/batch_leads_for_enrichment.json"
# Load successful lead files and create enrichment input
import glob
lead_files = glob.glob(f"{result['output_directory']}/lead_*.json")
enrichment_leads = []
for lead_file in lead_files[:result['successful']]: # Only successful ones
try:
with open(lead_file, 'r') as f:
lead_result = json.load(f)
if lead_result.get("lead_data"):
enrichment_leads.append(lead_result["lead_data"])
except Exception:
continue
if enrichment_leads:
# Save leads for enrichment
with open(batch_leads_file, 'w') as f:
json.dump(enrichment_leads, f, indent=2, default=str)
enrichment_types = [t.strip() for t in enrich_types.split(',')]
# Perform batch enrichment
enrichment_result = await app.batch_enrich_leads_with_clay(
leads_file=batch_leads_file,
enrichment_types=enrichment_types,
priority=enrich_priority,
output_file=f"{result['output_directory']}/enrichment_results.json"
)
click.echo(f"✅ Batch enrichment completed:")
click.echo(f" Leads sent for enrichment: {enrichment_result['total_leads']}")
click.echo(f" Successful submissions: {enrichment_result['successful_submissions']}")
click.echo(f" Failed submissions: {enrichment_result['failed_submissions']}")
click.echo(f" Estimated cost: ${enrichment_result['total_estimated_cost']:.2f}")
click.echo(f" Enrichment results saved to: {result['output_directory']}/enrichment_results.json")
else:
click.echo("⚠️ No valid leads found for enrichment")
except Exception as e:
click.echo(f"⚠️ Auto-enrichment failed: {e}")
click.echo("✅ Batch processing completed without enrichment")
except Exception as e:
click.echo(f"❌ Error: {e}", err=True)
finally:
await app.shutdown()
# SmartLead campaign CLI commands removed
@cli.command()
@click.option('--full', is_flag=True, help='Full health check including all components')
@click.option('--json-output', is_flag=True, help='Output in JSON format')
@click.pass_context
async def health(ctx, full, json_output):
"""Check system health and status."""
app_config = AppConfig(
debug=ctx.obj['debug'],
log_level=ctx.obj['log_level']
)
app = AgentLeadApp(app_config)
try:
# Always initialize for health check
if not await app.initialize():
click.echo("❌ Failed to initialize application", err=True)
return
health_status = await app.check_health()
if json_output:
click.echo(json.dumps(health_status, indent=2, default=str))
else:
# Pretty print health status
status_color = "green" if health_status["overall_status"] == "healthy" else "red"
table = Table(title="AgentLead Health Status")
table.add_column("Component", style="cyan")
table.add_column("Status", style=status_color)
table.add_column("Last Check", style="dim")