Commit
·
2c7cbe3
1
Parent(s):
5bd02e3
debuging
Browse files
app.py
CHANGED
|
@@ -48,11 +48,31 @@ def setup_database_connection():
|
|
| 48 |
try:
|
| 49 |
load_dotenv(override=True)
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
db_user = os.getenv("DB_USER")
|
| 52 |
db_password = os.getenv("DB_PASSWORD")
|
| 53 |
db_host = os.getenv("DB_HOST")
|
| 54 |
db_name = os.getenv("DB_NAME")
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
if not all([db_user, db_password, db_host, db_name]):
|
| 57 |
return None, "Missing database configuration"
|
| 58 |
|
|
@@ -82,37 +102,74 @@ def setup_database_connection():
|
|
| 82 |
def initialize_llm():
|
| 83 |
"""Inicializa el modelo de lenguaje."""
|
| 84 |
if not DEPENDENCIES_AVAILABLE:
|
| 85 |
-
|
|
|
|
|
|
|
| 86 |
|
| 87 |
google_api_key = os.getenv("GOOGLE_API_KEY")
|
|
|
|
|
|
|
| 88 |
if not google_api_key:
|
| 89 |
-
|
|
|
|
|
|
|
| 90 |
|
| 91 |
try:
|
|
|
|
| 92 |
llm = ChatGoogleGenerativeAI(
|
| 93 |
model="gemini-2.0-flash",
|
| 94 |
temperature=0,
|
| 95 |
google_api_key=google_api_key
|
| 96 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
logger.info("Google Generative AI initialized successfully")
|
| 98 |
return llm, ""
|
|
|
|
| 99 |
except Exception as e:
|
| 100 |
error_msg = f"Error initializing Google Generative AI: {str(e)}"
|
| 101 |
-
logger.error(error_msg)
|
| 102 |
return None, error_msg
|
| 103 |
|
| 104 |
def create_agent():
|
| 105 |
"""Crea el agente SQL si es posible."""
|
| 106 |
if not DEPENDENCIES_AVAILABLE:
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
db, db_error = setup_database_connection()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
llm, llm_error = initialize_llm()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
|
|
|
| 112 |
if not db or not llm:
|
| 113 |
-
error_msg = "
|
| 114 |
-
|
|
|
|
| 115 |
|
|
|
|
| 116 |
try:
|
| 117 |
logger.info("Creating SQL agent...")
|
| 118 |
agent = create_sql_agent(
|
|
@@ -121,11 +178,21 @@ def create_agent():
|
|
| 121 |
agent_type=AgentType.OPENAI_FUNCTIONS,
|
| 122 |
verbose=True
|
| 123 |
)
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
return agent, ""
|
|
|
|
| 126 |
except Exception as e:
|
| 127 |
error_msg = f"Error creating SQL agent: {str(e)}"
|
| 128 |
-
logger.error(error_msg)
|
| 129 |
return None, error_msg
|
| 130 |
|
| 131 |
# Inicializar el agente
|
|
|
|
| 48 |
try:
|
| 49 |
load_dotenv(override=True)
|
| 50 |
|
| 51 |
+
# Debug: Log all environment variables (without sensitive values)
|
| 52 |
+
logger.info("Environment variables:")
|
| 53 |
+
for key, value in os.environ.items():
|
| 54 |
+
if any(s in key.lower() for s in ['pass', 'key', 'secret']):
|
| 55 |
+
logger.info(f" {key}: {'*' * 8} (hidden for security)")
|
| 56 |
+
else:
|
| 57 |
+
logger.info(f" {key}: {value}")
|
| 58 |
+
|
| 59 |
db_user = os.getenv("DB_USER")
|
| 60 |
db_password = os.getenv("DB_PASSWORD")
|
| 61 |
db_host = os.getenv("DB_HOST")
|
| 62 |
db_name = os.getenv("DB_NAME")
|
| 63 |
|
| 64 |
+
# Debug: Log database connection info (without password)
|
| 65 |
+
logger.info(f"Database connection attempt - Host: {db_host}, User: {db_user}, DB: {db_name}")
|
| 66 |
+
if not all([db_user, db_password, db_host, db_name]):
|
| 67 |
+
missing = [var for var, val in [
|
| 68 |
+
("DB_USER", db_user),
|
| 69 |
+
("DB_PASSWORD", "*" if db_password else ""),
|
| 70 |
+
("DB_HOST", db_host),
|
| 71 |
+
("DB_NAME", db_name)
|
| 72 |
+
] if not val]
|
| 73 |
+
logger.error(f"Missing required database configuration: {', '.join(missing)}")
|
| 74 |
+
return None, f"Missing database configuration: {', '.join(missing)}"
|
| 75 |
+
|
| 76 |
if not all([db_user, db_password, db_host, db_name]):
|
| 77 |
return None, "Missing database configuration"
|
| 78 |
|
|
|
|
| 102 |
def initialize_llm():
|
| 103 |
"""Inicializa el modelo de lenguaje."""
|
| 104 |
if not DEPENDENCIES_AVAILABLE:
|
| 105 |
+
error_msg = "Dependencies not available. Make sure all required packages are installed."
|
| 106 |
+
logger.error(error_msg)
|
| 107 |
+
return None, error_msg
|
| 108 |
|
| 109 |
google_api_key = os.getenv("GOOGLE_API_KEY")
|
| 110 |
+
logger.info(f"GOOGLE_API_KEY found: {'Yes' if google_api_key else 'No'}")
|
| 111 |
+
|
| 112 |
if not google_api_key:
|
| 113 |
+
error_msg = "GOOGLE_API_KEY not found in environment variables. Please check your Hugging Face Space secrets."
|
| 114 |
+
logger.error(error_msg)
|
| 115 |
+
return None, error_msg
|
| 116 |
|
| 117 |
try:
|
| 118 |
+
logger.info("Initializing Google Generative AI...")
|
| 119 |
llm = ChatGoogleGenerativeAI(
|
| 120 |
model="gemini-2.0-flash",
|
| 121 |
temperature=0,
|
| 122 |
google_api_key=google_api_key
|
| 123 |
)
|
| 124 |
+
|
| 125 |
+
# Test the model with a simple prompt
|
| 126 |
+
test_prompt = "Hello, this is a test."
|
| 127 |
+
logger.info(f"Testing model with prompt: {test_prompt}")
|
| 128 |
+
test_response = llm.invoke(test_prompt)
|
| 129 |
+
logger.info(f"Model test response: {str(test_response)[:100]}...") # Log first 100 chars
|
| 130 |
+
|
| 131 |
logger.info("Google Generative AI initialized successfully")
|
| 132 |
return llm, ""
|
| 133 |
+
|
| 134 |
except Exception as e:
|
| 135 |
error_msg = f"Error initializing Google Generative AI: {str(e)}"
|
| 136 |
+
logger.error(error_msg, exc_info=True) # Include full stack trace
|
| 137 |
return None, error_msg
|
| 138 |
|
| 139 |
def create_agent():
|
| 140 |
"""Crea el agente SQL si es posible."""
|
| 141 |
if not DEPENDENCIES_AVAILABLE:
|
| 142 |
+
error_msg = "Dependencies not available. Please check if all required packages are installed."
|
| 143 |
+
logger.error(error_msg)
|
| 144 |
+
return None, error_msg
|
| 145 |
+
|
| 146 |
+
logger.info("Starting agent creation process...")
|
| 147 |
+
|
| 148 |
+
# Step 1: Set up database connection
|
| 149 |
+
logger.info("Setting up database connection...")
|
| 150 |
db, db_error = setup_database_connection()
|
| 151 |
+
if not db:
|
| 152 |
+
error_msg = f"Failed to connect to database: {db_error}"
|
| 153 |
+
logger.error(error_msg)
|
| 154 |
+
else:
|
| 155 |
+
logger.info("Database connection successful")
|
| 156 |
+
|
| 157 |
+
# Step 2: Initialize LLM
|
| 158 |
+
logger.info("Initializing language model...")
|
| 159 |
llm, llm_error = initialize_llm()
|
| 160 |
+
if not llm:
|
| 161 |
+
error_msg = f"Failed to initialize language model: {llm_error}"
|
| 162 |
+
logger.error(error_msg)
|
| 163 |
+
else:
|
| 164 |
+
logger.info("Language model initialized successfully")
|
| 165 |
|
| 166 |
+
# Check if both components are available
|
| 167 |
if not db or not llm:
|
| 168 |
+
error_msg = f"Cannot create agent. {db_error if not db else ''} {llm_error if not llm else ''}"
|
| 169 |
+
logger.error(error_msg)
|
| 170 |
+
return None, error_msg
|
| 171 |
|
| 172 |
+
# Step 3: Create SQL agent
|
| 173 |
try:
|
| 174 |
logger.info("Creating SQL agent...")
|
| 175 |
agent = create_sql_agent(
|
|
|
|
| 178 |
agent_type=AgentType.OPENAI_FUNCTIONS,
|
| 179 |
verbose=True
|
| 180 |
)
|
| 181 |
+
|
| 182 |
+
# Test the agent with a simple query
|
| 183 |
+
try:
|
| 184 |
+
logger.info("Testing agent with a simple query...")
|
| 185 |
+
test_result = agent.invoke({"input": "What tables are available?"})
|
| 186 |
+
logger.info(f"Agent test response: {str(test_result)[:200]}...") # Log first 200 chars
|
| 187 |
+
except Exception as test_error:
|
| 188 |
+
logger.warning(f"Agent test query failed (this might be expected): {str(test_error)}")
|
| 189 |
+
|
| 190 |
+
logger.info("SQL agent created and tested successfully")
|
| 191 |
return agent, ""
|
| 192 |
+
|
| 193 |
except Exception as e:
|
| 194 |
error_msg = f"Error creating SQL agent: {str(e)}"
|
| 195 |
+
logger.error(error_msg, exc_info=True) # Include full stack trace
|
| 196 |
return None, error_msg
|
| 197 |
|
| 198 |
# Inicializar el agente
|