File size: 12,099 Bytes
8bf4d58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Main orchestrator for coordinating all components."""

import logging
from typing import Dict, Any, Optional
from enum import Enum
from src.core.config import get_settings
from src.retrieval.vector_store import get_vector_store
from src.agents.local_data_agent import LocalDataAgent
from src.agents.search_agent import SearchAgent
from src.agents.cloud_agent import CloudAgent
from src.agents.aggregator_agent import AggregatorAgent
from src.agents.snowflake_agent import SnowflakeAgent
from src.tools.calculator import get_calculator
from src.tools.web_search import get_web_search
from src.tools.database_query import get_database_query
from openai import OpenAI

logger = logging.getLogger(__name__)


class Tier(Enum):
    """System tiers."""
    BASIC_RAG = "basic"
    AGENT_WITH_TOOLS = "agent"
    ADVANCED_AGENTIC = "advanced"


class Orchestrator:
    """Main orchestrator for the RAG system."""

    def __init__(self):
        """Initialize orchestrator."""
        self.settings = get_settings()
        self.client = OpenAI(**self.settings.get_openai_client_kwargs())
        self.model = self.settings.openai_model

        # Initialize components
        self.vector_store = get_vector_store()

        # Initialize agents (lazy loading)
        self._local_agent: Optional[LocalDataAgent] = None
        self._search_agent: Optional[SearchAgent] = None
        self._cloud_agent: Optional[CloudAgent] = None
        self._snowflake_agent: Optional[SnowflakeAgent] = None
        self._aggregator_agent: Optional[AggregatorAgent] = None

        # Initialize tools
        self.calculator = get_calculator()
        self.web_search = get_web_search()
        self.database_query = get_database_query()

    async def process_query(
        self,
        query: str,
        tier: str = "basic",
        session_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        """
        Process a query using the specified tier.

        Args:
            query: User query
            tier: System tier ("basic", "agent", or "advanced")
            session_id: Optional session ID for memory

        Returns:
            Response dictionary
        """
        try:
            tier_enum = Tier(tier.lower())

            if tier_enum == Tier.BASIC_RAG:
                return await self._process_basic_rag(query, session_id)
            elif tier_enum == Tier.AGENT_WITH_TOOLS:
                return await self._process_agent_with_tools(query, session_id)
            elif tier_enum == Tier.ADVANCED_AGENTIC:
                return await self._process_advanced_agentic(query, session_id)
            else:
                raise ValueError(f"Unknown tier: {tier}")

        except ValueError as e:
            logger.error(f"Invalid tier: {e}")
            return {
                "success": False,
                "error": f"Invalid tier: {tier}",
            }
        except Exception as e:
            logger.error(f"Error processing query: {e}")
            return {
                "success": False,
                "error": str(e),
            }

    async def _process_basic_rag(
        self,
        query: str,
        session_id: Optional[str],
    ) -> Dict[str, Any]:
        """Process query using basic RAG (retrieval + generation)."""
        try:
            # Check if OpenAI API key is configured
            if not self.settings.openai_api_key:
                return {
                    "success": False,
                    "error": "OpenAI API key not configured. Please set OPENAI_API_KEY in your .env file.",
                    "tier": "basic",
                }

            # Retrieve relevant documents
            results = self.vector_store.search(query=query, n_results=5)

            # Build context - use retrieved documents if available, otherwise use empty context
            if results["documents"]:
                context_parts = ["Retrieved documents:"]
                for i, (doc, metadata) in enumerate(
                    zip(results["documents"], results["metadatas"]), 1
                ):
                    source = metadata.get("source", "Unknown")
                    context_parts.append(f"\n[{i}] Source: {source}")
                    # Ensure doc is a string
                    doc_str = str(doc) if doc else ""
                    context_parts.append(f"Content: {doc_str[:500]}...")
                context = "\n".join(context_parts)
                sources = [
                    {"id": id, "metadata": meta}
                    for id, meta in zip(results["ids"], results["metadatas"])
                ]
            else:
                context = "No relevant documents found in the knowledge base."
                sources = []

            # Generate response using LLM
            messages = [
                {
                    "role": "system",
                    "content": "You are a helpful assistant that answers questions based on the provided context.",
                },
                {
                    "role": "user",
                    "content": f"Context:\n{context}\n\nQuestion: {query}",
                },
            ]

            try:
                response = self.client.chat.completions.create(
                    model=self.model,
                    messages=messages,
                    temperature=0.7,
                )

                answer = response.choices[0].message.content
            except Exception as api_error:
                error_msg = str(api_error)
                if "quota" in error_msg.lower() or "429" in error_msg:
                    raise Exception("OpenAI API quota exceeded. Please check your billing and plan details.")
                elif "api key" in error_msg.lower() or "401" in error_msg:
                    raise Exception("Invalid OpenAI API key. Please check your .env file.")
                else:
                    raise Exception(f"OpenAI API error: {error_msg}")

            return {
                "success": True,
                "answer": answer,
                "tier": "basic",
                "sources": sources,
                "model": self.model,
            }

        except Exception as e:
            logger.error(f"Error in basic RAG: {e}", exc_info=True)
            return {
                "success": False,
                "error": f"Error processing query: {str(e)}",
                "tier": "basic",
            }

    async def _process_agent_with_tools(
        self,
        query: str,
        session_id: Optional[str],
    ) -> Dict[str, Any]:
        """Process query using agent with tools."""
        try:
            # Check if OpenAI API key is configured
            if not self.settings.openai_api_key:
                return {
                    "success": False,
                    "error": "OpenAI API key not configured. Please set OPENAI_API_KEY in your .env file.",
                    "tier": "agent",
                }

            # Use local agent with tools enabled
            if not self._local_agent:
                self._local_agent = LocalDataAgent(use_planning=True)

            # Add tools to agent
            self._local_agent.add_tool(
                tool=self.calculator.get_tool_schema(),
                tool_function=lambda expression: self.calculator.calculate(expression),
            )

            if self.settings.has_web_search():
                async def web_search_tool(query: str, max_results: int = 5):
                    return await self.web_search.search(query, max_results)
                
                self._local_agent.add_tool(
                    tool=self.web_search.get_tool_schema(),
                    tool_function=web_search_tool,
                )

            if self.settings.database_url:
                def db_query_tool(sql: str, limit: int = 100):
                    return self.database_query.query(sql, limit)
                
                self._local_agent.add_tool(
                    tool=self.database_query.get_tool_schema(),
                    tool_function=db_query_tool,
                )

            # Process query
            response = await self._local_agent.process(query, session_id)

            return {
                **response,
                "tier": "agent",
            }

        except Exception as e:
            logger.error(f"Error in agent with tools: {e}", exc_info=True)
            return {
                "success": False,
                "error": f"Error processing query: {str(e)}",
                "tier": "agent",
            }

    async def _process_advanced_agentic(
        self,
        query: str,
        session_id: Optional[str],
    ) -> Dict[str, Any]:
        """Process query using advanced agentic RAG with multiple agents."""
        try:
            # Check if OpenAI API key is configured
            if not self.settings.openai_api_key:
                return {
                    "success": False,
                    "error": "OpenAI API key not configured. Please set OPENAI_API_KEY in your .env file.",
                    "tier": "advanced",
                }

            # Use aggregator agent
            if not self._aggregator_agent:
                self._aggregator_agent = AggregatorAgent(use_planning=True)
                
                # Add Snowflake agent if configured
                if self.settings.has_snowflake() and not self._snowflake_agent:
                    snowflake_config = self.settings.get_snowflake_config()
                    self._snowflake_agent = SnowflakeAgent(
                        snowflake_config=snowflake_config,
                        use_planning=False
                    )
                    # Note: AggregatorAgent will automatically discover SnowflakeAgent
                    # through its agent selection logic

            # Process query
            response = await self._aggregator_agent.process(query, session_id)

            return {
                **response,
                "tier": "advanced",
            }

        except Exception as e:
            logger.error(f"Error in advanced agentic: {e}", exc_info=True)
            return {
                "success": False,
                "error": f"Error processing query: {str(e)}",
                "tier": "advanced",
            }

    def get_agent_status(self) -> Dict[str, Any]:
        """Get status of all agents."""
        status = {
            "tiers_available": ["basic", "agent", "advanced"],
            "agents": {},
        }

        if self._local_agent:
            status["agents"]["local"] = self._local_agent.get_status()
        if self._search_agent:
            status["agents"]["search"] = self._search_agent.get_status()
        if self._cloud_agent:
            status["agents"]["cloud"] = self._cloud_agent.get_status()
        if self._snowflake_agent:
            status["agents"]["snowflake"] = self._snowflake_agent.get_status()
        if self._aggregator_agent:
            status["agents"]["aggregator"] = self._aggregator_agent.get_status()

        return status

    def get_system_info(self) -> Dict[str, Any]:
        """Get system information."""
        return {
            "vector_store": {
                "document_count": self.vector_store.count(),
                "collection_name": self.settings.chroma_collection_name,
            },
            "tools": {
                "calculator": True,
                "web_search": self.settings.has_web_search(),
                "database": bool(self.settings.database_url),
                "snowflake": self.settings.has_snowflake(),
            },
            "memory": {
                "short_term_enabled": True,
                "long_term_enabled": self.settings.long_term_memory_enabled,
            },
            "model": self.model,
        }


# Global instance
_orchestrator: Optional[Orchestrator] = None


def get_orchestrator() -> Orchestrator:
    """Get or create the global orchestrator instance."""
    global _orchestrator
    if _orchestrator is None:
        _orchestrator = Orchestrator()
    return _orchestrator