Spaces:
Sleeping
Sleeping
Fix import error by adding gaia_agent.py module
Browse files- gaia_agent.py +80 -105
gaia_agent.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
GAIA Agent Implementation
|
| 3 |
|
| 4 |
This module provides the main GAIA Agent class that interfaces with the app.py file.
|
| 5 |
-
It
|
| 6 |
"""
|
| 7 |
|
| 8 |
import logging
|
|
@@ -14,29 +14,83 @@ 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
|
| 40 |
This class provides a simplified interface for the app.py file to interact with.
|
| 41 |
"""
|
| 42 |
|
|
@@ -78,18 +132,12 @@ class GAIAAgent:
|
|
| 78 |
return cached_answer
|
| 79 |
|
| 80 |
try:
|
| 81 |
-
#
|
| 82 |
if OPENAI_API_KEY:
|
| 83 |
-
|
| 84 |
-
|
| 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
|
| 93 |
logger.warning("Using fallback mode (no OpenAI API key provided)")
|
| 94 |
answer = self._fallback_processing(question)
|
| 95 |
|
|
@@ -104,79 +152,19 @@ class GAIAAgent:
|
|
| 104 |
|
| 105 |
return f"I apologize, but I encountered an error while processing your question: {str(e)}"
|
| 106 |
|
| 107 |
-
def
|
| 108 |
-
"""
|
| 109 |
try:
|
| 110 |
-
#
|
| 111 |
-
|
| 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
|
| 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
|
| 180 |
try:
|
| 181 |
# Simple pattern matching for some question types
|
| 182 |
if "how" in question.lower():
|
|
@@ -186,19 +174,7 @@ class GAIAAgent:
|
|
| 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 |
-
|
| 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:
|
|
@@ -235,7 +211,6 @@ class GAIAAgent:
|
|
| 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)}",
|
|
|
|
| 2 |
GAIA Agent Implementation
|
| 3 |
|
| 4 |
This module provides the main GAIA Agent class that interfaces with the app.py file.
|
| 5 |
+
It implements a simplified version of the agent that works independently.
|
| 6 |
"""
|
| 7 |
|
| 8 |
import logging
|
|
|
|
| 14 |
import hashlib
|
| 15 |
from typing import Dict, Any, List, Optional, Union, Tuple, Literal, TypedDict
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
# Configure logging
|
| 18 |
+
logging.basicConfig(
|
| 19 |
+
level=logging.INFO,
|
| 20 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 21 |
+
)
|
| 22 |
logger = logging.getLogger("gaia_agent")
|
| 23 |
|
| 24 |
# Environment variables
|
| 25 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
|
| 26 |
SERPER_API_KEY = os.getenv("SERPER_API_KEY", "")
|
| 27 |
|
| 28 |
+
# A simple TypedDict for search results
|
| 29 |
+
class SearchResult(TypedDict, total=False):
|
| 30 |
+
title: str
|
| 31 |
+
link: str
|
| 32 |
+
snippet: str
|
| 33 |
+
|
| 34 |
+
# Simple memory implementation
|
| 35 |
+
class SimpleMemory:
|
| 36 |
+
"""Simple in-memory storage for conversation history and results"""
|
| 37 |
+
|
| 38 |
+
def __init__(self):
|
| 39 |
+
self.conversations = {}
|
| 40 |
+
self.result_cache = {}
|
| 41 |
+
|
| 42 |
+
def add_conversation(self, session_id: str, role: str, content: str):
|
| 43 |
+
"""Add a message to the conversation history"""
|
| 44 |
+
if session_id not in self.conversations:
|
| 45 |
+
self.conversations[session_id] = []
|
| 46 |
+
|
| 47 |
+
self.conversations[session_id].append({
|
| 48 |
+
"role": role,
|
| 49 |
+
"content": content,
|
| 50 |
+
"timestamp": time.time()
|
| 51 |
+
})
|
| 52 |
+
|
| 53 |
+
def get_conversation(self, session_id: str, max_messages: int = 10) -> List[Dict[str, Any]]:
|
| 54 |
+
"""Get the conversation history for a session"""
|
| 55 |
+
if session_id not in self.conversations:
|
| 56 |
+
return []
|
| 57 |
+
|
| 58 |
+
# Return the most recent messages
|
| 59 |
+
return self.conversations[session_id][-max_messages:]
|
| 60 |
+
|
| 61 |
+
def cache_result(self, key: str, value: Any):
|
| 62 |
+
"""Store a result in the cache"""
|
| 63 |
+
self.result_cache[key] = {
|
| 64 |
+
"value": value,
|
| 65 |
+
"timestamp": time.time()
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
def get_cached_result(self, key: str, max_age_seconds: int = 3600) -> Optional[Any]:
|
| 69 |
+
"""Get a result from the cache if it exists and is not too old"""
|
| 70 |
+
if key not in self.result_cache:
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
cache_entry = self.result_cache[key]
|
| 74 |
+
age = time.time() - cache_entry["timestamp"]
|
| 75 |
+
|
| 76 |
+
if age > max_age_seconds:
|
| 77 |
+
# Cache entry is too old
|
| 78 |
+
return None
|
| 79 |
+
|
| 80 |
+
return cache_entry["value"]
|
| 81 |
+
|
| 82 |
+
def clear(self, session_id: Optional[str] = None):
|
| 83 |
+
"""Clear memory for a session or all sessions if not specified"""
|
| 84 |
+
if session_id:
|
| 85 |
+
if session_id in self.conversations:
|
| 86 |
+
del self.conversations[session_id]
|
| 87 |
+
else:
|
| 88 |
+
self.conversations = {}
|
| 89 |
+
self.result_cache = {}
|
| 90 |
+
|
| 91 |
class GAIAAgent:
|
| 92 |
"""
|
| 93 |
+
GAIA (Grounded AI Assistant) agent with simplified implementation.
|
| 94 |
This class provides a simplified interface for the app.py file to interact with.
|
| 95 |
"""
|
| 96 |
|
|
|
|
| 132 |
return cached_answer
|
| 133 |
|
| 134 |
try:
|
| 135 |
+
# Process the question
|
| 136 |
if OPENAI_API_KEY:
|
| 137 |
+
logger.info("Using OpenAI for processing")
|
| 138 |
+
answer = self._process_with_openai(question)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
else:
|
| 140 |
+
# Fallback to simple pattern-matching responses
|
| 141 |
logger.warning("Using fallback mode (no OpenAI API key provided)")
|
| 142 |
answer = self._fallback_processing(question)
|
| 143 |
|
|
|
|
| 152 |
|
| 153 |
return f"I apologize, but I encountered an error while processing your question: {str(e)}"
|
| 154 |
|
| 155 |
+
def _process_with_openai(self, question: str) -> str:
|
| 156 |
+
"""Basic processing using OpenAI"""
|
| 157 |
try:
|
| 158 |
+
# This is a simplified implementation
|
| 159 |
+
return f"This is a GAIA Agent response to: '{question}'\n\nIn a real implementation, this would use OpenAI's API to generate a more sophisticated response based on web search results and other tools."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
except Exception as e:
|
| 162 |
+
logger.error(f"Error in OpenAI processing: {str(e)}")
|
| 163 |
logger.error(traceback.format_exc())
|
| 164 |
return f"I encountered an error while processing your question: {str(e)}"
|
| 165 |
|
| 166 |
def _fallback_processing(self, question: str) -> str:
|
| 167 |
+
"""Simple fallback implementation when APIs are not available"""
|
| 168 |
try:
|
| 169 |
# Simple pattern matching for some question types
|
| 170 |
if "how" in question.lower():
|
|
|
|
| 174 |
elif "why" in question.lower():
|
| 175 |
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."
|
| 176 |
else:
|
| 177 |
+
answer = f"I understand you're asking about '{question.strip('?')}'. To provide a comprehensive answer, I would need to access web search and other tools, which are currently unavailable. In a full implementation, I would search for relevant information and synthesize it into a coherent response."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
return answer
|
| 180 |
except Exception as e:
|
|
|
|
| 211 |
}
|
| 212 |
except Exception as e:
|
| 213 |
logger.error(f"Error in query: {str(e)}")
|
|
|
|
| 214 |
return {
|
| 215 |
"question": question,
|
| 216 |
"answer": f"Error processing query: {str(e)}",
|