File size: 33,333 Bytes
e0aa230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

AI Embedded Knowledge Agent - Main Application Entry Point



This is the main entry point for the RAG AI system that integrates all components

and launches the Gradio interface for deployment on Hugging Face.

"""

import nltk

nltk.download("punkt_tab")


import spacy.cli

spacy.cli.download("en_core_web_sm")
nlp = spacy.load("en_core_web_sm")


import os
import sys
import logging
from pathlib import Path
from typing import Optional

# Load environment variables from .env file
try:
    from dotenv import load_dotenv

    load_dotenv()
except ImportError:
    print(
        "python-dotenv not installed. Please install it with: pip install python-dotenv"
    )

# Add src directory to Python path
src_path = Path(__file__).parent / "src"
sys.path.insert(0, str(src_path))

# Import all components
from utils.config_manager import ConfigManager
from utils.error_handler import ErrorHandler, ErrorType
from ingestion.document_processor import DocumentProcessor
from ingestion.url_processor import URLProcessor
from ingestion.text_extractor import TextExtractor
from embedding.embedding_generator import EmbeddingGenerator
from storage.vector_db import VectorDB
from rag.optimized_query_processor import OptimizedQueryProcessor
from rag.response_generator import ResponseGenerator
from rag.live_search import LiveSearchProcessor
from rag.query_router import QueryRouter
from ui.gradio_app import GradioApp


class RAGSystem:
    """

    Main RAG AI system that orchestrates all components.



    This class integrates document processing, embedding generation,

    vector storage, and query processing into a unified system.

    """

    def __init__(self, config_path: Optional[str] = None):
        """

        Initialize the RAG system with all components.



        Args:

            config_path: Path to configuration file

        """
        # Initialize configuration
        self.config_manager = ConfigManager(config_path)
        self.config = self.config_manager.config

        # Setup logging
        self._setup_logging()
        self.logger = logging.getLogger(__name__)
        self.logger.info("Initializing RAG AI System...")

        # Initialize error handler
        self.error_handler = ErrorHandler()

        # Validate environment and configuration
        self._validate_environment()

        # Initialize components
        self._initialize_components()

        # Run health checks
        self._run_startup_health_checks()

        self.logger.info("RAG AI System initialized successfully! ")

    def _setup_logging(self):
        """Setup comprehensive logging configuration."""
        log_config = self.config.get("logging", {})
        log_level = getattr(logging, log_config.get("level", "INFO").upper())
        log_format = log_config.get(
            "format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        )

        # Configure root logger with UTF-8 encoding
        import io

        utf8_stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
        logging.basicConfig(
            level=log_level,
            format=log_format,
            handlers=[logging.StreamHandler(utf8_stdout)],
        )

        # Create logs directory if specified
        log_file = log_config.get("file")
        if log_file:
            log_dir = Path(log_file).parent
            log_dir.mkdir(parents=True, exist_ok=True)

            # Add file handler with rotation
            try:
                from logging.handlers import RotatingFileHandler

                file_handler = RotatingFileHandler(
                    log_file,
                    maxBytes=log_config.get("max_file_size_mb", 10) * 1024 * 1024,
                    backupCount=log_config.get("backup_count", 5),
                )
                file_handler.setFormatter(logging.Formatter(log_format))
                logging.getLogger().addHandler(file_handler)
            except Exception as e:
                self.logger.warning(f"Could not setup file logging: {e}")

    def _validate_environment(self):
        """Validate environment variables and configuration."""
        self.logger.info("Validating environment...")

        # Check required API keys
        required_keys = ["GEMINI_API_KEY"]
        optional_keys = ["PINECONE_API_KEY", "OPENAI_API_KEY"]

        missing_required = []
        for key in required_keys:
            if not os.getenv(key):
                missing_required.append(key)

        if missing_required:
            self.logger.error(
                f" Missing required environment variables: {missing_required}"
            )
            self.logger.error(
                "Please set the required API keys as environment variables"
            )
            # Don't raise error in demo mode, just warn
            self.logger.warning("Running in demo mode with limited functionality")

        # Check optional keys
        missing_optional = []
        for key in optional_keys:
            if not os.getenv(key):
                missing_optional.append(key)

        if missing_optional:
            self.logger.warning(
                f"Missing optional environment variables: {missing_optional}"
            )
            self.logger.warning("Some features may be limited without these keys")

        # Validate configuration
        self._validate_configuration()

        self.logger.info("Environment validation completed")

    def _validate_configuration(self):
        """Validate configuration settings."""
        try:
            # Check embedding configuration
            embedding_config = self.config.get("embedding", {})
            if not embedding_config.get("model"):
                self.logger.warning("Embedding model not specified, using default")

            # Check vector database configuration
            vector_db_config = self.config.get("vector_db", {})
            if not vector_db_config.get("provider"):
                self.logger.warning(
                    "Vector database provider not specified, using default"
                )

            # Check RAG configuration
            rag_config = self.config.get("rag", {})
            if rag_config.get("top_k", 5) <= 0:
                self.logger.warning("Invalid top_k value, using default")

            self.logger.info("Configuration validation completed")

        except Exception as e:
            self.logger.warning(f"Configuration validation warning: {e}")

    def _initialize_components(self):
        """Initialize all system components with error handling."""
        try:
            self.logger.info("Initializing system components...")

            # Document processing components
            self.logger.info(" Initializing document processing components...")
            self.document_processor = DocumentProcessor(
                self.config_manager.get_section("document_processing")
            )

            self.url_processor = URLProcessor(
                self.config_manager.get_section("url_processing")
            )

            self.text_extractor = TextExtractor(
                self.config_manager.get_section("document_processing")
            )

            # Embedding and storage components
            self.logger.info("Initializing embedding and storage components...")
            embedding_config = self.config_manager.get_section("embedding")
            embedding_config["api_key"] = os.getenv("GEMINI_API_KEY")

            self.embedding_generator = EmbeddingGenerator(embedding_config)

            vector_db_config = self.config_manager.get_section("vector_db")
            vector_db_config["api_key"] = os.getenv("PINECONE_API_KEY")

            self.vector_db = VectorDB(vector_db_config)

            # RAG components
            self.logger.info("Initializing RAG components...")
            self.query_processor = OptimizedQueryProcessor(
                self.embedding_generator,
                self.vector_db,
                self.config_manager.get_section("rag"),
            )

            rag_config = self.config_manager.get_section("rag")
            # Add API keys to RAG config for LLM initialization
            rag_config["gemini_api_key"] = os.getenv("GEMINI_API_KEY")
            rag_config["openai_api_key"] = os.getenv("OPENAI_API_KEY")

            self.response_generator = ResponseGenerator(rag_config)

            # Live Search components
            self.logger.info("Initializing Live Search components...")
            live_search_config = self.config_manager.get_section("live_search") or {}
            self.live_search_processor = LiveSearchProcessor(live_search_config)

            # Query Router for intelligent routing
            router_config = self.config_manager.get_section("query_router") or {}
            self.query_router = QueryRouter(
                self.query_processor, self.live_search_processor, router_config
            )

            self.logger.info("All components initialized successfully")

        except Exception as e:
            self.logger.error(f" Failed to initialize components: {str(e)}")
            # Don't raise in demo mode, continue with limited functionality
            self.logger.warning("Some components may not be fully functional")

    def _run_startup_health_checks(self):
        """Run health checks on all components."""
        self.logger.info("Running startup health checks...")

        health_status = {
            "document_processor": False,
            "url_processor": False,
            "text_extractor": False,
            "embedding_generator": False,
            "vector_db": False,
            "query_processor": False,
            "response_generator": False,
        }

        # Check each component
        try:
            if hasattr(self, "document_processor"):
                health_status["document_processor"] = True
                self.logger.info("Document processor: Healthy")
        except:
            self.logger.warning("Document processor: Not available")

        try:
            if hasattr(self, "url_processor"):
                health_status["url_processor"] = True
                self.logger.info("URL processor: Healthy")
        except:
            self.logger.warning("URL processor: Not available")

        try:
            if hasattr(self, "text_extractor"):
                health_status["text_extractor"] = True
                self.logger.info("Text extractor: Healthy")
        except:
            self.logger.warning("Text extractor: Not available")

        try:
            if hasattr(self, "embedding_generator"):
                health_status["embedding_generator"] = True
                self.logger.info("Embedding generator: Healthy")
        except:
            self.logger.warning("Embedding generator: Not available")

        try:
            if hasattr(self, "vector_db"):
                health_status["vector_db"] = True
                self.logger.info("Vector database: Healthy")
        except:
            self.logger.warning("Vector database: Not available")

        try:
            if hasattr(self, "query_processor"):
                health_status["query_processor"] = True
                self.logger.info("Query processor: Healthy")
        except:
            self.logger.warning("Query processor: Not available")

        try:
            if hasattr(self, "response_generator"):
                health_status["response_generator"] = True
                self.logger.info("Response generator: Healthy")
        except:
            self.logger.warning("Response generator: Not available")

        # Overall health
        healthy_components = sum(health_status.values())
        total_components = len(health_status)

        self.logger.info(
            f"Health check complete: {healthy_components}/{total_components} components healthy"
        )

        if healthy_components < total_components:
            self.logger.warning("Some components are not fully functional")
            self.logger.warning("The system will run with limited capabilities")

    def process_document(self, file_path: str) -> dict:
        """

        Process a document through the complete pipeline.



        Args:

            file_path: Path to the document file



        Returns:

            Dictionary with processing results

        """
        try:
            self.logger.info(f" Processing document: {file_path}")

            # Check if components are available
            if not all(
                hasattr(self, attr)
                for attr in [
                    "document_processor",
                    "text_extractor",
                    "embedding_generator",
                    "vector_db",
                ]
            ):
                return {
                    "status": "error",
                    "error": "Required components not available",
                    "chunks_processed": 0,
                }

            # Step 1: Extract content from document
            doc_result = self.document_processor.process_document(file_path)

            if not doc_result or "content" not in doc_result:
                return {
                    "status": "error",
                    "error": "Failed to extract content from document",
                    "chunks_processed": 0,
                }

            # Step 2: Extract and chunk text
            text_chunks = self.text_extractor.process_text(
                doc_result["content"], doc_result.get("metadata", {})
            )

            if not text_chunks:
                return {
                    "status": "error",
                    "error": "No text chunks generated",
                    "chunks_processed": 0,
                }

            # Step 3: Generate embeddings
            embedded_chunks = self.embedding_generator.generate_embeddings(text_chunks)

            if not embedded_chunks:
                return {
                    "status": "error",
                    "error": "Failed to generate embeddings",
                    "chunks_processed": len(text_chunks),
                }

            # Step 4: Store in vector database
            storage_success = self.vector_db.store_embeddings(embedded_chunks)

            return {
                "status": "success" if storage_success else "partial_success",
                "chunks_processed": len(text_chunks),
                "chunks_stored": len(embedded_chunks) if storage_success else 0,
                "source": file_path,
            }

        except Exception as e:
            self.logger.error(f" Error processing document: {str(e)}")
            error_info = self.error_handler.handle_error(e, {"file_path": file_path})
            return {
                "status": "error",
                "error": str(e),
                "error_info": error_info,
                "chunks_processed": 0,
            }

    def process_url(

        self, url: str, max_depth: int = 1, follow_links: bool = True

    ) -> dict:
        """

        Process a URL through the complete pipeline with advanced options.



        Args:

            url: URL to process

            max_depth: Maximum crawling depth

            follow_links: Whether to follow links



        Returns:

            Dictionary with processing results

        """
        try:
            self.logger.info(f"Processing URL: {url}")

            # Check if components are available
            if not all(
                hasattr(self, attr)
                for attr in [
                    "url_processor",
                    "text_extractor",
                    "embedding_generator",
                    "vector_db",
                ]
            ):
                return {
                    "status": "error",
                    "error": "Required components not available",
                    "chunks_processed": 0,
                }

            # Step 1: Configure URL processor with advanced options
            # Update URL processor configuration dynamically
            self.url_processor.max_depth = max_depth
            self.url_processor.follow_links = follow_links

            # Reset processor state for fresh crawl
            self.url_processor.reset()

            # Extract content from URL
            url_result = self.url_processor.process_url(url)

            if not url_result or "content" not in url_result:
                return {
                    "status": "error",
                    "error": "Failed to extract content from URL",
                    "chunks_processed": 0,
                }

            # Step 2: Extract and chunk text
            text_chunks = self.text_extractor.process_text(
                url_result["content"], url_result.get("metadata", {})
            )

            if not text_chunks:
                return {
                    "status": "error",
                    "error": "No text chunks generated",
                    "chunks_processed": 0,
                }

            # Step 3: Generate embeddings
            embedded_chunks = self.embedding_generator.generate_embeddings(text_chunks)

            if not embedded_chunks:
                return {
                    "status": "error",
                    "error": "Failed to generate embeddings",
                    "chunks_processed": len(text_chunks),
                }

            # Step 4: Store in vector database
            storage_success = self.vector_db.store_embeddings(embedded_chunks)

            # Process linked documents if any
            linked_processed = 0
            for linked_doc in url_result.get("linked_documents", []):
                if linked_doc and "content" in linked_doc:
                    try:
                        linked_chunks = self.text_extractor.process_text(
                            linked_doc["content"], linked_doc.get("metadata", {})
                        )
                        if linked_chunks:
                            linked_embedded = (
                                self.embedding_generator.generate_embeddings(
                                    linked_chunks
                                )
                            )
                            if linked_embedded and self.vector_db.store_embeddings(
                                linked_embedded
                            ):
                                linked_processed += 1
                    except Exception as e:
                        self.logger.warning(f"Failed to process linked document: {e}")

            return {
                "status": "success" if storage_success else "partial_success",
                "chunks_processed": len(text_chunks),
                "chunks_stored": len(embedded_chunks) if storage_success else 0,
                "linked_documents_processed": linked_processed,
                "source": url,
            }

        except Exception as e:
            self.logger.error(f" Error processing URL: {str(e)}")
            error_info = self.error_handler.handle_error(e, {"url": url})
            return {
                "status": "error",
                "error": str(e),
                "error_info": error_info,
                "chunks_processed": 0,
            }

    def query(

        self,

        question: str,

        max_results: int = 5,

        use_live_search: bool = False,

        search_mode: str = "auto",

    ) -> dict:
        """

        Process a query and generate a response with enhanced search control.



        Args:

            question: User question

            max_results: Maximum number of results to retrieve

            use_live_search: Whether to enable live web search (uses hybrid approach)

            search_mode: Search mode - "auto", "local_only", "live_only", "hybrid"



        Returns:

            Dictionary with response and metadata

        """
        try:
            self.logger.info(
                f"Processing query: {question[:100]}... (live_search: {use_live_search})"
            )

            # Check if components are available
            if not all(
                hasattr(self, attr)
                for attr in ["query_processor", "response_generator"]
            ):
                return {
                    "query": question,
                    "response": "Query processing components not available. Please check system configuration.",
                    "sources": [],
                    "confidence": 0.0,
                    "error": "Components not available",
                }

            # Use Query Router for intelligent routing if available
            if hasattr(self, "query_router") and (
                use_live_search or search_mode != "auto"
            ):
                self.logger.info(f" Using Query Router with mode: {search_mode}")

                search_options = {"search_depth": "basic", "time_range": "month"}

                router_result = self.query_router.route_query(
                    question,
                    use_live_search=use_live_search,
                    max_results=max_results,
                    search_options=search_options,
                    search_mode=search_mode,
                )

                # Convert router result to standard format
                if router_result.get("results"):
                    # Format sources from router results
                    sources = []
                    for result in router_result["results"]:
                        sources.append(
                            {
                                "title": result.get("title", ""),
                                "source": result.get("source", ""),
                                "content": result.get("content", ""),
                                "score": result.get("score", 0.0),
                                "type": result.get("type", "unknown"),
                            }
                        )

                    # Generate response using response generator
                    context_items = []
                    for result in router_result["results"]:
                        context_items.append(
                            {
                                "text": result.get("content", ""),
                                "source": result.get("source", ""),
                                "score": result.get("score", 0.0),
                                "metadata": result.get("metadata", {}),
                            }
                        )

                    response_result = self.response_generator.generate_response(
                        question, context_items
                    )

                    return {
                        "query": question,
                        "response": response_result.get(
                            "response", "No response generated"
                        ),
                        "sources": sources,
                        "confidence": response_result.get("confidence", 0.0),
                        "context_items": len(context_items),
                        "processing_time": router_result.get("processing_time", 0),
                        "generation_time": response_result.get("generation_time", 0),
                        "model_used": response_result.get("model_used", "unknown"),
                        "routing_decision": router_result.get(
                            "routing_decision", "unknown"
                        ),
                        "search_type": "routed_search",
                    }
                else:
                    # Fallback to local search if router fails
                    self.logger.warning(
                        "Router returned no results, falling back to local search"
                    )

            # Traditional local search path
            # Step 1: Process query and retrieve context with max_results
            # Update query processor config temporarily
            original_top_k = self.query_processor.top_k
            self.query_processor.top_k = max_results

            query_result = self.query_processor.process_query(question)

            # Restore original top_k
            self.query_processor.top_k = original_top_k

            if query_result.get("error"):
                return {
                    "query": question,
                    "response": f"Query processing failed: {query_result['error']}",
                    "sources": [],
                    "confidence": 0.0,
                    "error": query_result["error"],
                }

            # Step 2: Generate response
            response_result = self.response_generator.generate_response(
                question, query_result.get("context", [])
            )

            # Combine results
            return {
                "query": question,
                "response": response_result.get("response", "No response generated"),
                "sources": response_result.get("sources", []),
                "confidence": response_result.get("confidence", 0.0),
                "context_items": query_result.get("total_results", 0),
                "processing_time": query_result.get("processing_time", 0),
                "generation_time": response_result.get("generation_time", 0),
                "model_used": response_result.get("model_used", "unknown"),
                "search_type": "local_search",
            }

        except Exception as e:
            self.logger.error(f"Error processing query: {str(e)}")
            error_info = self.error_handler.handle_error(e, {"query": question})
            return {
                "query": question,
                "response": "I encountered an error while processing your question. Please try again.",
                "sources": [],
                "confidence": 0.0,
                "error": str(e),
                "error_info": error_info,
            }

    def get_system_status(self) -> dict:
        """

        Get comprehensive system status.



        Returns:

            Dictionary with system status information

        """
        try:
            status = {
                "overall_status": "healthy",
                "components": {},
                "configuration": {},
                "environment": {},
            }

            # Check component status
            components = [
                "document_processor",
                "url_processor",
                "text_extractor",
                "embedding_generator",
                "vector_db",
                "query_processor",
                "response_generator",
            ]

            for component in components:
                status["components"][component] = hasattr(self, component)

            # Configuration info
            status["configuration"] = {
                "embedding_model": self.config.get("embedding", {}).get(
                    "model", "unknown"
                ),
                "vector_db_provider": self.config.get("vector_db", {}).get(
                    "provider", "unknown"
                ),
                "rag_top_k": self.config.get("rag", {}).get("top_k", 5),
            }

            # Environment info
            status["environment"] = {
                "gemini_api_available": bool(os.getenv("GEMINI_API_KEY")),
                "pinecone_api_available": bool(os.getenv("PINECONE_API_KEY")),
                "openai_api_available": bool(os.getenv("OPENAI_API_KEY")),
            }

            # Overall status
            healthy_components = sum(status["components"].values())
            total_components = len(status["components"])

            if healthy_components < total_components * 0.8:
                status["overall_status"] = "degraded"
            elif healthy_components < total_components * 0.5:
                status["overall_status"] = "unhealthy"

            return status

        except Exception as e:
            self.logger.error(f" Error getting system status: {e}")
            return {"overall_status": "error", "error": str(e)}


def create_app():
    """

    Create and configure the RAG application.



    Returns:

        Tuple of (RAG system instance, Gradio app instance)

    """
    try:
        # Initialize the RAG system
        rag_system = RAGSystem()

        # Create Gradio interface
        ui_config = rag_system.config_manager.get_section("ui")
        gradio_app = GradioApp(rag_system, ui_config)

        return rag_system, gradio_app

    except Exception as e:
        print(f" Failed to create application: {str(e)}")
        # Create a minimal system for demo purposes
        print("Creating minimal demo system...")

        # Create minimal config
        minimal_config = {
            "ui": {
                "title": "AI Embedded Knowledge Agent (Demo Mode)",
                "description": "Demo mode - some features may be limited. Please configure API keys for full functionality.",
            }
        }

        # Create minimal RAG system
        class MinimalRAGSystem:
            def __init__(self):
                self.config_manager = type(
                    "ConfigManager",
                    (),
                    {
                        "get_section": lambda self, section: minimal_config.get(
                            section, {}
                        )
                    },
                )()

            def process_document(self, file_path):
                return {
                    "status": "error",
                    "error": "Demo mode - document processing not available",
                }

            def process_url(self, url):
                return {
                    "status": "error",
                    "error": "Demo mode - URL processing not available",
                }

            def query(self, question):
                return {
                    "query": question,
                    "response": "Demo mode: Please configure your API keys (GEMINI_API_KEY, PINECONE_API_KEY) to enable full functionality.",
                    "sources": [],
                    "confidence": 0.0,
                }

        rag_system = MinimalRAGSystem()
        gradio_app = GradioApp(rag_system, minimal_config.get("ui", {}))

        return rag_system, gradio_app


def main():
    """Main function to run the application."""
    try:
        print("Starting AI Embedded Knowledge Agent...")
        print("=" * 50)

        # Create the application
        rag_system, gradio_app = create_app()

        # Get launch configuration
        try:
            ui_config = rag_system.config_manager.get_section("ui")
        except:
            ui_config = {}

        # Launch the Gradio interface
        base_port = ui_config.get("port", 7860)
        launch_config = {
            "server_name": ui_config.get("server_name", "0.0.0.0"),
            "server_port": base_port,
            "share": ui_config.get("share", False),
            "show_error": True,
            "quiet": False,
        }

        # Try different ports if the default is in use
        for port_offset in range(10):  # Try ports 7860-7869
            try:
                current_port = base_port + port_offset
                launch_config["server_port"] = current_port

                print(
                    f"Launching interface on {launch_config['server_name']}:{current_port}"
                )
                print("=" * 50)

                gradio_app.launch(**launch_config)
                break  # If successful, break out of the loop

            except Exception as e:
                if (
                    "bind" in str(e).lower()
                    or "address already in use" in str(e).lower()
                ):
                    print(f"Port {current_port} is in use, trying next port...")
                    continue
                else:
                    # If it's a different error, re-raise it
                    raise e
        else:
            # If we've tried all ports without success
            print(
                "Could not find an available port. Please close other applications using ports 7860-7869."
            )
            raise Exception("No available ports found")

    except KeyboardInterrupt:
        print("\n👋 Shutting down gracefully...")
    except Exception as e:
        print(f" Failed to start application: {str(e)}")
        print("Please check your configuration and API keys.")
        sys.exit(1)


if __name__ == "__main__":
    main()