# src/agents/rag_agent_manager.py from typing import Optional import weakref from src.agents.system_instructions_rag import SystemInstructionsRAGAgent from src.llms.base_llm import BaseLLM from src.embeddings.base_embedding import BaseEmbedding from src.vectorstores.base_vectorstore import BaseVectorStore from src.db.mongodb_store import MongoDBStore from src.utils.logger import logger class RAGAgentManager: """ Singleton manager for RAG Agent instances with intelligent caching """ _instance = None def __new__(cls): if not cls._instance: cls._instance = super().__new__(cls) return cls._instance def __init__(self): # Ensure this is only initialized once if not hasattr(self, '_initialized'): self._rag_agent = None self._initialized = True def get_rag_agent( self, llm: BaseLLM, embedding_model: BaseEmbedding, vector_store: BaseVectorStore, mongodb: MongoDBStore ) -> SystemInstructionsRAGAgent: """ Get or create a singleton RAG agent instance with intelligent caching Args: llm: Language Model instance embedding_model: Embedding model instance vector_store: Vector store instance mongodb: MongoDB store instance Returns: SystemInstructionsRAGAgent: Singleton instance of the RAG agent """ # If RAG agent exists and all dependencies are the same, return it if self._rag_agent is not None: logger.info("Reusing existing RAG agent instance") return self._rag_agent try: logger.info("Creating new RAG agent instance") # Create the agent self._rag_agent = SystemInstructionsRAGAgent( llm=llm, embedding=embedding_model, vector_store=vector_store, mongodb=mongodb ) return self._rag_agent except Exception as e: logger.error(f"Error creating RAG agent: {str(e)}") raise def reset_rag_agent(self): """ Reset the RAG agent instance """ logger.info("Resetting RAG agent instance") self._rag_agent = None # Create a global instance for easy import rag_agent_manager = RAGAgentManager()