jm-vis commited on
Commit
f0396fb
·
1 Parent(s): a3fb832

Fix import error by adding gaia_agent.py module

Browse files
Files changed (1) hide show
  1. gaia_agent.py +251 -0
gaia_agent.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ GAIA Agent Implementation
3
+
4
+ This module provides the main GAIA Agent class that interfaces with the app.py file.
5
+ It wraps the core agent functionality in a simpler interface.
6
+ """
7
+
8
+ import logging
9
+ import time
10
+ import os
11
+ import json
12
+ import re
13
+ import traceback
14
+ import hashlib
15
+ from typing import Dict, Any, List, Optional, Union, Tuple, Literal, TypedDict
16
+
17
+ # Import components from agent.py
18
+ from agent import (
19
+ SimpleMemory, WebSearchTool, ContentExtractor, AgentState,
20
+ analyze_question, create_plan, execute_tool, formulate_answer,
21
+ create_fallback_plan
22
+ )
23
+
24
+ # LangChain & LangGraph imports
25
+ from langchain_core.prompts import ChatPromptTemplate
26
+ from langchain_core.output_parsers import StrOutputParser
27
+ from langgraph.graph import StateGraph, END
28
+ from langchain_openai import ChatOpenAI
29
+
30
+ # Configure logging
31
+ logger = logging.getLogger("gaia_agent")
32
+
33
+ # Environment variables
34
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
35
+ SERPER_API_KEY = os.getenv("SERPER_API_KEY", "")
36
+
37
+ class GAIAAgent:
38
+ """
39
+ GAIA (Grounded AI Assistant) agent with web search and content extraction capabilities.
40
+ This class provides a simplified interface for the app.py file to interact with.
41
+ """
42
+
43
+ def __init__(self):
44
+ """Initialize the GAIA agent with simplified configuration"""
45
+ self.memory = SimpleMemory()
46
+ logger.info("GAIA Agent initialized")
47
+
48
+ def __call__(self, question: str) -> str:
49
+ """
50
+ Process a question and generate an answer.
51
+ Compatible with the interface expected by app.py.
52
+
53
+ Args:
54
+ question (str): The question to process
55
+
56
+ Returns:
57
+ str: The answer to the question
58
+ """
59
+ return self.process_question(question)
60
+
61
+ def process_question(self, question: str) -> str:
62
+ """
63
+ Process a question and generate an answer.
64
+
65
+ Args:
66
+ question (str): The question to process
67
+
68
+ Returns:
69
+ str: The answer to the question
70
+ """
71
+ # Generate a cache key for this question
72
+ cache_key = f"question_{hashlib.md5(question.encode()).hexdigest()}"
73
+
74
+ # Check if we have a cached result
75
+ cached_answer = self.memory.get_cached_result(cache_key)
76
+ if cached_answer:
77
+ logger.info(f"Using cached answer for question: {question[:50]}...")
78
+ return cached_answer
79
+
80
+ try:
81
+ # Initialize LLM with error handling
82
+ if OPENAI_API_KEY:
83
+ llm = ChatOpenAI(
84
+ temperature=0,
85
+ model="gpt-3.5-turbo",
86
+ api_key=OPENAI_API_KEY
87
+ )
88
+
89
+ # Process with LangGraph
90
+ answer = self._process_with_langgraph(question, llm)
91
+ else:
92
+ # Fallback to simple pattern-matching responses when LLM is not available
93
+ logger.warning("Using fallback mode (no OpenAI API key provided)")
94
+ answer = self._fallback_processing(question)
95
+
96
+ # Cache the result
97
+ self.memory.cache_result(cache_key, answer)
98
+
99
+ return answer
100
+
101
+ except Exception as e:
102
+ logger.error(f"Error processing question: {str(e)}")
103
+ logger.error(traceback.format_exc())
104
+
105
+ return f"I apologize, but I encountered an error while processing your question: {str(e)}"
106
+
107
+ def _process_with_langgraph(self, question: str, llm) -> str:
108
+ """Process question using LangGraph workflow"""
109
+ try:
110
+ # Define state transitions
111
+ def should_continue(state: AgentState) -> Literal["continue", "complete"]:
112
+ """Determine if the agent should continue or is finished"""
113
+ current_step = state.get("current_step", 0)
114
+ plan = state.get("plan", [])
115
+
116
+ # Check if we still have steps to execute
117
+ if current_step is None or plan is None:
118
+ return "complete"
119
+
120
+ if current_step < len(plan):
121
+ return "continue"
122
+ else:
123
+ return "complete"
124
+
125
+ # Create the graph
126
+ workflow = StateGraph(AgentState)
127
+
128
+ # Add nodes
129
+ workflow.add_node("analyze", analyze_question)
130
+ workflow.add_node("create_plan", create_plan)
131
+ workflow.add_node("execute_tool", execute_tool)
132
+ workflow.add_node("formulate_answer", formulate_answer)
133
+
134
+ # Add edges
135
+ workflow.add_edge("analyze", "create_plan")
136
+ workflow.add_edge("create_plan", "execute_tool")
137
+ workflow.add_edge("execute_tool", should_continue)
138
+ workflow.add_conditional_edges(
139
+ "execute_tool",
140
+ should_continue,
141
+ {
142
+ "continue": "execute_tool",
143
+ "complete": "formulate_answer"
144
+ }
145
+ )
146
+ workflow.add_edge("formulate_answer", END)
147
+
148
+ # Set entry point
149
+ workflow.set_entry_point("analyze")
150
+
151
+ # Compile the graph
152
+ app = workflow.compile()
153
+
154
+ # Run the graph
155
+ state = {
156
+ "question": question,
157
+ "tool_results": []
158
+ }
159
+
160
+ result = app.invoke({
161
+ **state,
162
+ "llm": llm
163
+ })
164
+
165
+ # Return the answer or an error message
166
+ if "answer" in result and result["answer"]:
167
+ return result["answer"]
168
+ elif "error" in result and result["error"]:
169
+ return f"I encountered an error: {result['error']}"
170
+ else:
171
+ return "I was unable to generate an answer based on the available information."
172
+
173
+ except Exception as e:
174
+ logger.error(f"Error in LangGraph processing: {str(e)}")
175
+ logger.error(traceback.format_exc())
176
+ return f"I encountered an error while processing your question: {str(e)}"
177
+
178
+ def _fallback_processing(self, question: str) -> str:
179
+ """Simple fallback implementation when LLM is not available"""
180
+ try:
181
+ # Simple pattern matching for some question types
182
+ if "how" in question.lower():
183
+ answer = f"To address '{question.strip('?')}', I would recommend following these steps: 1) Understand the core concepts, 2) Apply a structured approach, 3) Evaluate results, and 4) Refine as needed. Without being able to access external knowledge at the moment, this is a general framework for addressing how-to questions."
184
+ elif "what" in question.lower():
185
+ answer = f"Regarding '{question.strip('?')}', this typically involves understanding several key factors. While I don't have access to external knowledge at the moment, this type of question usually requires defining terms, establishing context, and examining relevant concepts."
186
+ elif "why" in question.lower():
187
+ answer = f"The question '{question.strip('?')}' relates to causality and explanation. Such questions typically involve understanding underlying mechanisms, historical context, and logical relationships between factors."
188
+ else:
189
+ # Try a web search if available
190
+ try:
191
+ search_tool = WebSearchTool()
192
+ search_results = search_tool.search(question)
193
+
194
+ if search_results and search_results[0].get("snippet"):
195
+ snippet = search_results[0]["snippet"]
196
+ answer = f"Based on available information: {snippet}\n\nPlease note that without access to a language model, I can only provide this basic search result."
197
+ else:
198
+ answer = f"I'm sorry, but I cannot provide a comprehensive answer to '{question}' at this moment due to limited access to external knowledge and language model capabilities."
199
+ except Exception as search_err:
200
+ logger.error(f"Error in fallback search: {str(search_err)}")
201
+ answer = f"I'm sorry, but I cannot provide a comprehensive answer to '{question}' at this moment due to limited access to external knowledge and language model capabilities."
202
+
203
+ return answer
204
+ except Exception as e:
205
+ logger.error(f"Error in fallback processing: {str(e)}")
206
+ return f"I apologize, but I'm currently unable to process your question due to system limitations."
207
+
208
+ def query(self, question: str) -> Dict[str, Any]:
209
+ """
210
+ Query the agent with a question to get an answer with metadata.
211
+
212
+ Args:
213
+ question (str): The question to answer
214
+
215
+ Returns:
216
+ Dict[str, Any]: Dictionary containing the answer and metadata
217
+ """
218
+ try:
219
+ # Track timing
220
+ start_time = time.time()
221
+
222
+ # Process the question
223
+ answer = self.process_question(question)
224
+
225
+ # Calculate processing time
226
+ processing_time = time.time() - start_time
227
+
228
+ # Return result with metadata
229
+ return {
230
+ "question": question,
231
+ "answer": answer,
232
+ "processing_time": processing_time,
233
+ "timestamp": time.time(),
234
+ "status": "success"
235
+ }
236
+ except Exception as e:
237
+ logger.error(f"Error in query: {str(e)}")
238
+
239
+ return {
240
+ "question": question,
241
+ "answer": f"Error processing query: {str(e)}",
242
+ "processing_time": time.time() - start_time,
243
+ "timestamp": time.time(),
244
+ "status": "error",
245
+ "error": str(e)
246
+ }
247
+
248
+ def clear_memory(self):
249
+ """Clear the agent's memory"""
250
+ self.memory.clear()
251
+ logger.info("Agent memory cleared")