-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrag_memecoin_generation_workflow.py
More file actions
800 lines (655 loc) · 29.9 KB
/
rag_memecoin_generation_workflow.py
File metadata and controls
800 lines (655 loc) · 29.9 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
#!/usr/bin/env python3
"""
RAG v2 Generation Workflow for Web-based AI-powered memecoin creation
Production implementation using real stages for the complete Input → Processing → Execution pattern
for web interface integration with domain architecture.
"""
import asyncio
import logging
# Add src to path for imports
import os
import signal
import sys
import uuid
from pathlib import Path
from typing import Dict, Any, Optional
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from src.workflows.rag_memecoin_insertion_workflow import RAGMemecoinInsertionWorkflow
# FastAPI imports for HTTP API
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
# Load environment variables from .env file
from dotenv import load_dotenv
load_dotenv()
from src.domain.workflow.default_workflow import DefaultWorkflow
from src.domain.input_source.web_generation_input_source import WebGenerationInputSource
from src.domain.processor.rag_memecoin_generation_processor import (
RAGMemecoinGenerationProcessor,
)
from src.domain.executor.executor_router import ExecutorRouter
from src.domain.executor.similar_examples_executor import SimilarExamplesExecutor
from src.domain.executor.generated_token_metadata_executor import (
GeneratedTokenMetadataExecutor,
)
from src.domain.executor.generated_image_executor import GeneratedImageExecutor
from src.domain.executor.output_file_executor import OutputFileExecutor
from src.domain.executor.session_status_update_executor import (
SessionStatusUpdateExecutor,
)
from src.domain.model.actions.rag_generation_actions import (
SimilarExamplesAction,
GeneratedTokenMetadataAction,
GeneratedImageAction,
OutputFileAction,
SessionStatusUpdateAction,
)
from src.services.ai.litellm_service import LiteLLMService
from src.services.ai.clip_embedding_service import CLIPEmbeddingService
from src.services.ai.image_generation_service import ImageGenerationService
from src.web_ui.services.memecoin_service import MemecoinService
from src.constants import RES_ROOT
# Enhanced error handling imports
from src.domain.exceptions import (
ValidationError,
APIServiceError,
with_retry,
API_RETRY_CONFIG,
)
logger = logging.getLogger(__name__)
# API Models
class GenerationRequest(BaseModel):
prompt: str
generation_count: int = 1
max_examples: int = 5
selected_tags: list = []
session_id: Optional[str] = None
class GenerationResponse(BaseModel):
success: bool
session_id: str
message: str
estimated_completion_time: str
class GenerationStatus(BaseModel):
session_id: str
status: str
message: str
progress: Dict[str, Any]
stage_timestamps: Dict[str, str]
class HealthResponse(BaseModel):
healthy: bool
status: str
workflow_initialized: bool
services: Dict[str, str]
def create_executor_router() -> ExecutorRouter:
"""
Create and configure an ExecutorRouter with all necessary executors
Returns:
Configured ExecutorRouter instance
"""
router = ExecutorRouter()
# Register executors for each action type
router.register_executor(SimilarExamplesAction, SimilarExamplesExecutor())
router.register_executor(
GeneratedTokenMetadataAction, GeneratedTokenMetadataExecutor()
)
router.register_executor(GeneratedImageAction, GeneratedImageExecutor())
router.register_executor(OutputFileAction, OutputFileExecutor())
# Register status update executor for incremental progress updates
router.register_executor(
SessionStatusUpdateAction, SessionStatusUpdateExecutor()
)
return router
# Global state for workflow service
_workflow_instance: Optional["RAGMemecoinGenerationWorkflow"] = None
_session_tracking: Dict[str, Dict[str, Any]] = {}
# Create FastAPI app for workflow service
app = FastAPI(
title="RAG v2 Generation Workflow Service",
description="AI-powered memecoin generation service",
version="2.0.0",
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["http://127.0.0.1:8000", "http://localhost:8000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class RAGMemecoinGenerationWorkflow:
"""
Main workflow for real RAG v2 memecoin generation
Supports two modes:
1. Orchestrator mode: Services provided via constructor (dependency injection)
2. Standalone mode: Services initialized automatically during initialize()
"""
def __init__(
self,
llm_service: Optional[LiteLLMService] = None,
clip_service: Optional[CLIPEmbeddingService] = None,
image_service: Optional[ImageGenerationService] = None,
validation_delay=0.5,
retrieval_delay=1.0,
generation_delay=2.0,
image_delay=1.5,
output_delay=0.3,
):
"""Initialize workflow
Args:
llm_service: Pre-initialized LLM service (optional, will auto-init if None)
clip_service: Pre-initialized CLIP service (optional, will auto-init if None)
image_service: Pre-initialized image service (optional, will auto-init if None)
validation_delay: Delay for validation stage (unused, for compatibility)
retrieval_delay: Delay for retrieval stage (unused, for compatibility)
generation_delay: Delay for generation stage (unused, for compatibility)
image_delay: Delay for image generation stage (unused, for compatibility)
output_delay: Delay for output stage (unused, for compatibility)
"""
# Store provided services (may be None for standalone mode)
self.llm_service = llm_service
self.clip_service = clip_service
self.image_service = image_service
self.memecoin_service = None # Initialized in initialize()
# Workflow components (initialized in initialize())
self.workflow = None
self.input_source = None
self.processor = None
self.executor = None
# Store delays for potential future use or compatibility
self.validation_delay = validation_delay
self.retrieval_delay = retrieval_delay
self.generation_delay = generation_delay
self.image_delay = image_delay
self.output_delay = output_delay
async def initialize(self):
"""
Initialize workflow components with proper configuration
Supports two modes:
- If services provided (orchestrator mode): Use them directly
- If services not provided (standalone mode): Initialize them internally
"""
logger.info("🔧 Initializing RAG v2 generation workflow...")
try:
# Determine if we need to initialize services ourselves
services_provided = all([self.llm_service, self.clip_service, self.image_service])
if not services_provided:
# Standalone mode: Validate environment and initialize services
logger.info("📦 Standalone mode: Initializing services internally...")
await self._validate_environment()
# Initialize LLM service if not provided
if not self.llm_service:
logger.info("🚀 Initializing LLM service...")
try:
self.llm_service = await self._initialize_llm_service()
logger.info("✅ LLM service initialized successfully")
except Exception as e:
logger.warning(f"⚠️ LLM service initialization failed: {e}")
self.llm_service = None
# Initialize CLIP service if not provided
if not self.clip_service:
logger.info("🚀 Initializing CLIP embedding service...")
try:
self.clip_service = await self._initialize_clip_service()
logger.info("✅ CLIP service initialized successfully")
except Exception as e:
logger.warning(f"⚠️ CLIP service initialization failed: {e}")
self.clip_service = None
# Initialize Image service if not provided
if not self.image_service:
logger.info("🚀 Initializing Image Generation service...")
try:
self.image_service = ImageGenerationService()
logger.info("✅ Image Generation service initialized successfully")
except Exception as e:
logger.warning(f"⚠️ Image Generation service initialization failed: {e}")
self.image_service = None
# Health checks for auto-initialized services
await self._perform_health_checks()
else:
# Orchestrator mode: Services provided, use them
logger.info("🔗 Orchestrator mode: Using provided services")
# Initialize MemecoinService (required for both modes)
logger.info("🚀 Initializing Memecoin service...")
try:
self.memecoin_service = MemecoinService()
logger.info("✅ Memecoin service initialized successfully")
except Exception as e:
logger.warning(f"⚠️ Memecoin service initialization failed: {e}")
self.memecoin_service = None
# Create workflow components (same for both modes)
logger.info(" 📥 Creating WebGenerationInputSource...")
self.input_source = WebGenerationInputSource()
# Note: input_source will be initialized by DefaultWorkflow with the callback
logger.info(" 🎯 Creating ExecutorRouter with registered executors...")
executor_router = create_executor_router()
# Inject router reference into executors for status updates
logger.info(" 🔗 Injecting router reference into executors...")
executor_router.inject_router_to_executors()
logger.info(" ⚙️ Creating RAGMemecoinGenerationProcessor...")
processor = RAGMemecoinGenerationProcessor(
llm_service=self.llm_service,
clip_service=self.clip_service,
image_service=self.image_service,
memecoin_service=self.memecoin_service,
executor_router=executor_router,
)
await processor.initialize()
logger.info(" 🔄 Creating DefaultWorkflow...")
self.workflow = DefaultWorkflow(self.input_source, processor, executor_router)
await self.workflow.initialize()
# Store component references for external access
self.processor = processor
self.executor = executor_router
logger.info("✅ RAG v2 generation workflow initialized successfully")
except Exception as e:
logger.error(f"❌ Failed to initialize RAG v2 workflow: {e}")
await self._cleanup_on_error()
raise
async def _validate_environment(self):
"""Validate required environment variables and configuration"""
logger.info("🔍 Validating environment configuration...")
required_keys = {
"REPLICATE_API_KEY": "CLIP embedding service",
"OPENAI_API_KEY": "LLM services (primary)",
}
optional_keys = {
"OPENROUTER_API_KEY": "OpenRouter LLM services (fallback)",
"LANGFUSE_SECRET_KEY": "LLM observability (optional)",
}
missing_required = []
missing_optional = []
# Check required keys
for key, service in required_keys.items():
if not os.getenv(key):
missing_required.append(f" ❌ {key}: Required for {service}")
# Check optional keys
for key, service in optional_keys.items():
if not os.getenv(key):
missing_optional.append(f" ⚠️ {key}: Optional for {service}")
# Report missing keys
if missing_required:
error_msg = "Missing required environment variables:\n" + "\n".join(
missing_required
)
logger.error(error_msg)
raise ValidationError("environment_variables", error_msg)
if missing_optional:
logger.warning(
"Missing optional environment variables:\n"
+ "\n".join(missing_optional)
)
logger.info("💡 Services will operate with graceful degradation")
logger.info("✅ Environment validation passed")
async def _initialize_llm_service(self) -> LiteLLMService:
"""Initialize LLM service with image generation models"""
@with_retry(API_RETRY_CONFIG)
async def _initialize_with_retry():
config_path = RES_ROOT / "config" / "image_generation_llm.yaml"
llm_service = LiteLLMService(config_path=str(config_path))
await llm_service.initialize()
return llm_service
try:
return await _initialize_with_retry()
except Exception as e:
logger.error(f"Failed to initialize LLM service after retries: {e}")
raise APIServiceError("LLM", f"Service initialization failed: {e}") from e
async def _initialize_clip_service(self) -> CLIPEmbeddingService:
"""Initialize CLIP service with proper configuration adapter and retry logic"""
@with_retry(API_RETRY_CONFIG)
async def _initialize_with_retry():
# Check if we should use Replicate API directly
replicate_key = os.getenv("REPLICATE_API_KEY")
if replicate_key:
logger.info("🔧 Using Replicate API directly for CLIP embeddings")
from src.services.ai.clip_embedding_service import CLIPEmbeddingConfig
config = CLIPEmbeddingConfig(
api_key=replicate_key,
model="openai/clip",
max_retries=3,
timeout=60,
)
clip_service = CLIPEmbeddingService(config=config)
await clip_service.initialize()
return clip_service
else:
# Fallback to YAML config (though this path may need LiteLLM integration)
logger.warning(
"⚠️ No REPLICATE_API_KEY found, attempting YAML config fallback"
)
clip_config_path = RES_ROOT / "config" / "clip_litellm.yaml"
import yaml
with open(clip_config_path, "r") as f:
yaml_config = yaml.safe_load(f)
# Extract API key from YAML config
openrouter_key = os.getenv("OPENROUTER_API_KEY")
if not openrouter_key:
raise ValidationError(
"api_keys",
"No REPLICATE_API_KEY or OPENROUTER_API_KEY available for CLIP service",
)
# Create CLIPEmbeddingConfig from YAML
from src.services.ai.clip_embedding_service import CLIPEmbeddingConfig
config = CLIPEmbeddingConfig(
api_key=openrouter_key,
model="openrouter/openai/clip-vit-large-patch14",
max_retries=3,
timeout=60,
)
clip_service = CLIPEmbeddingService(config=config)
await clip_service.initialize()
return clip_service
try:
return await _initialize_with_retry()
except Exception as e:
logger.error(f"Failed to initialize CLIP service after retries: {e}")
raise APIServiceError("CLIP", f"Service initialization failed: {e}") from e
async def _perform_health_checks(self):
"""Perform health checks on initialized services"""
logger.info("🏥 Performing service health checks...")
health_status = {}
# Check LLM service health
try:
if self.llm_service and hasattr(self.llm_service, "router"):
# Simple health check - verify service is initialized
health_status["llm_service"] = (
"healthy" if self.llm_service.router else "unhealthy"
)
logger.info(f"✅ LLM service: {health_status['llm_service']}")
else:
health_status["llm_service"] = "uninitialized"
logger.warning("⚠️ LLM service: uninitialized")
except Exception as e:
health_status["llm_service"] = f"error: {e}"
logger.warning(f"⚠️ LLM service health check failed: {e}")
# Check CLIP service health
try:
if self.clip_service and hasattr(self.clip_service, "client"):
health_status["clip_service"] = (
"healthy" if self.clip_service.client else "unhealthy"
)
logger.info(f"✅ CLIP service: {health_status['clip_service']}")
else:
health_status["clip_service"] = "uninitialized"
logger.warning("⚠️ CLIP service: uninitialized")
except Exception as e:
health_status["clip_service"] = f"error: {e}"
logger.warning(f"⚠️ CLIP service health check failed: {e}")
# Verify at least one service is healthy (for demo purposes, accept either)
all_services = ["llm_service", "clip_service"]
healthy_services = sum(
1 for service in all_services if health_status.get(service) == "healthy"
)
if healthy_services == 0:
raise APIServiceError(
"Workflow", "No services are healthy - cannot proceed"
)
# Warn if critical services are missing but allow continuation for demo
if health_status.get("llm_service") != "healthy":
logger.warning(
"⚠️ LLM service unavailable - workflow will run with limited functionality"
)
logger.info(
f"🏥 Health check summary: {healthy_services}/{len(all_services)} services healthy"
)
# Log service degradation warnings
if health_status.get("clip_service") != "healthy":
logger.warning(
"⚠️ CLIP service unavailable - RAG functionality will be limited"
)
async def _cleanup_on_error(self):
"""Cleanup resources on initialization error"""
# Services no longer need explicit cleanup
pass
async def process_web_request(self, request_data: Dict[str, Any]) -> bool:
"""Process a web generation request through the workflow"""
if not self.input_source:
logger.error("❌ Workflow not initialized")
return False
# Log the incoming request details
logger.info("=" * 60)
logger.info("🎨 NEW GENERATION REQUEST FROM WEB UI")
logger.info("=" * 60)
logger.info(f"📝 Prompt: {request_data.get('prompt', 'N/A')}")
logger.info(f"🏷️ Tags: {request_data.get('selected_tags', [])}")
logger.info(f"🔢 Generation Count: {request_data.get('generation_count', 1)}")
logger.info(f"📊 Max Examples: {request_data.get('max_examples', 5)}")
logger.info(f"🆔 Session ID: {request_data.get('session_id', 'N/A')}")
logger.info("=" * 60)
return await self.input_source.process_request(request_data)
async def run(self):
"""Run the workflow"""
try:
await self.workflow.run_indefinitely()
except KeyboardInterrupt:
logger.info("🛑 Stopping RAG v2 generation workflow...")
await self.workflow.stop()
async def stop(self):
"""Stop the workflow with coordinated cleanup"""
logger.info("🛑 Starting coordinated workflow shutdown...")
cleanup_results = {}
# Stop workflow first
try:
if self.workflow:
await asyncio.wait_for(self.workflow.stop(), timeout=10.0)
cleanup_results["workflow"] = "success"
logger.info("✅ Workflow stopped successfully")
except asyncio.TimeoutError:
cleanup_results["workflow"] = "timeout"
logger.warning("⚠️ Workflow stop timed out after 10s")
except Exception as e:
cleanup_results["workflow"] = f"error: {e}"
logger.warning(f"⚠️ Error stopping workflow: {e}")
# Services don't need explicit cleanup anymore
cleanup_results["llm_service"] = "no_cleanup_needed"
cleanup_results["clip_service"] = "no_cleanup_needed"
# Log final cleanup summary
successful = sum(
1 for result in cleanup_results.values() if result == "success"
)
total = len(cleanup_results)
logger.info(
f"🧹 Cleanup complete: {successful}/{total} components cleaned successfully"
)
if successful < total:
logger.warning(
"⚠️ Some components failed to clean up properly - check logs above"
)
return cleanup_results
# API Endpoints
@app.post("/workflow/generate", response_model=GenerationResponse)
async def generate_memecoin(
request: GenerationRequest, background_tasks: BackgroundTasks
) -> GenerationResponse:
"""Start a new memecoin generation request"""
global _workflow_instance
if not _workflow_instance:
raise HTTPException(status_code=503, detail="Workflow service not initialized")
# Generate session ID if not provided
session_id = request.session_id or str(uuid.uuid4())
# Convert to dict and add session_id
request_data = request.model_dump()
request_data["session_id"] = session_id
# Initialize session tracking
_session_tracking[session_id] = {
"session_id": session_id,
"status": "pending",
"message": "Generation request accepted",
"progress": {"completed_stages": 0, "total_stages": 5, "percentage": 0},
"stage_timestamps": {},
"created_at": asyncio.get_event_loop().time(),
}
# Start processing in background
background_tasks.add_task(_process_generation_request, session_id, request_data)
logger.info(f"🚀 Started generation request: {session_id[:8]}")
return GenerationResponse(
success=True,
session_id=session_id,
message="Generation request accepted and processing started",
estimated_completion_time="8-15 seconds",
)
@app.get("/workflow/status/{session_id}", response_model=GenerationStatus)
async def get_generation_status(session_id: str) -> GenerationStatus:
"""Get the status of a generation request"""
if session_id not in _session_tracking:
raise HTTPException(status_code=404, detail=f"Session {session_id} not found")
session_data = _session_tracking[session_id]
return GenerationStatus(
session_id=session_id,
status=session_data.get("status", "unknown"),
message=session_data.get("message", ""),
progress=session_data.get("progress", {}),
stage_timestamps=session_data.get("stage_timestamps", {}),
)
@app.get("/workflow/health", response_model=HealthResponse)
async def get_workflow_health() -> HealthResponse:
"""Get workflow service health status"""
global _workflow_instance
if not _workflow_instance:
return HealthResponse(
healthy=False,
status="uninitialized",
workflow_initialized=False,
services={},
)
# Check service health
services = {}
try:
if (
hasattr(_workflow_instance, "llm_service")
and _workflow_instance.llm_service
):
services["llm_service"] = "healthy"
else:
services["llm_service"] = "unavailable"
if (
hasattr(_workflow_instance, "clip_service")
and _workflow_instance.clip_service
):
services["clip_service"] = "healthy"
else:
services["clip_service"] = "unavailable"
except Exception as e:
logger.error(f"Error checking service health: {e}")
services["error"] = str(e)
is_healthy = any(status == "healthy" for status in services.values())
return HealthResponse(
healthy=is_healthy,
status="running" if is_healthy else "degraded",
workflow_initialized=True,
services=services,
)
async def _process_generation_request(session_id: str, request_data: Dict[str, Any]):
"""Process generation request in background"""
global _workflow_instance
try:
logger.info(f"🎨 Processing generation for session: {session_id[:8]}")
# Update status
_session_tracking[session_id].update(
{"status": "processing", "message": "Processing generation request"}
)
# Process through workflow
success = await _workflow_instance.process_web_request(request_data)
if success:
_session_tracking[session_id].update(
{
"status": "completed",
"message": "Generation completed successfully",
"progress": {
"completed_stages": 5,
"total_stages": 5,
"percentage": 100,
},
}
)
logger.info(f"✅ Generation completed: {session_id[:8]}")
else:
_session_tracking[session_id].update(
{"status": "failed", "message": "Generation failed"}
)
logger.error(f"❌ Generation failed: {session_id[:8]}")
except Exception as e:
logger.error(f"❌ Error processing generation {session_id[:8]}: {e}")
_session_tracking[session_id].update(
{"status": "failed", "message": f"Generation error: {str(e)}"}
)
# Web UI launching removed - workflow should connect to existing web server
async def start_workflow_service():
"""Initialize and start the workflow service"""
global _workflow_instance
logger.info("🔧 Initializing workflow service...")
# Create and initialize workflow
_workflow_instance = RAGMemecoinGenerationWorkflow()
await _workflow_instance.initialize()
logger.info("✅ Workflow service initialized successfully")
async def main():
"""Main entry point for the RAG v2 generation workflow
This workflow connects to an existing web server and listens for generation requests.
The web server must be running before starting this workflow.
"""
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
# Check if web server is running (optional - we can run independently)
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
web_server_running = sock.connect_ex(("127.0.0.1", 8000)) == 0
sock.close()
if not web_server_running:
print("\n⚠️ Web server is not running on port 8000")
print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
print("The workflow service will run independently.")
print("To use the web UI, start it separately:")
print(" uvicorn src.web_ui.main:app --port 8000 --host 127.0.0.1")
print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
else:
print("\n✅ Web server detected on port 8000")
print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
print("\n🚀 Starting RAG v2 Workflow Service on port 8001...")
print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
print("🤖 AI-Powered Memecoin Generation Service")
print("🔍 Initializing workflow and services...")
if web_server_running:
print("🌐 Web UI available at: http://127.0.0.1:8000/generation.html")
print("🔧 Service API available at: http://127.0.0.1:8001/docs")
print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")
# Initialize workflow service
await start_workflow_service()
# Handle graceful shutdown
def signal_handler(signum, frame):
logger.info("🛑 Received shutdown signal")
if _workflow_instance:
asyncio.create_task(_workflow_instance.stop())
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
try:
print("✅ Workflow service initialized successfully!")
print("🎯 Using real stages with LLM and CLIP services")
print("🛑 Press Ctrl+C to stop\n")
logger.info("🌐 RAG workflow service ready! Serving HTTP API on port 8001")
logger.info("💡 API documentation: http://127.0.0.1:8001/docs")
# Start FastAPI server
config = uvicorn.Config(app=app, host="127.0.0.1", port=8001, log_level="info")
server = uvicorn.Server(config)
await server.serve()
except ValidationError as e:
logger.error(f"❌ Configuration validation failed: {e}")
logger.info(
"💡 Please check your environment variables and configuration files"
)
sys.exit(1)
except APIServiceError as e:
logger.error(f"❌ Service initialization failed: {e}")
logger.info("💡 Please check your API keys and network connectivity")
if _workflow_instance:
await _workflow_instance.stop()
sys.exit(1)
except Exception as e:
logger.error(f"❌ Unexpected workflow error: {e}")
if _workflow_instance:
await _workflow_instance.stop()
sys.exit(1)
if __name__ == "__main__":
asyncio.run(main())