Jeremy Live commited on
Commit
c6828a0
1 Parent(s): 0f16c64

API solved v1

Browse files
Files changed (3) hide show
  1. api.py +2 -15
  2. app.py +3 -2
  3. shared.py +179 -0
api.py CHANGED
@@ -2,7 +2,7 @@ from flask import Flask, request, jsonify
2
  from typing import Dict, Optional
3
  import uuid
4
  import os
5
- from app import initialize_llm, setup_database_connection, create_agent, gr
6
 
7
  app = Flask(__name__)
8
 
@@ -84,20 +84,7 @@ def handle_ask():
84
  except Exception as e:
85
  return jsonify({'error': str(e)}), 500
86
 
87
- # Integraci贸n con Gradio para Hugging Face Spaces
88
- def mount_in_app(gradio_app):
89
- """Monta la API Flask en la aplicaci贸n Gradio."""
90
- return gradio_app
91
-
92
  if __name__ == '__main__':
93
  # Si se ejecuta directamente, inicia el servidor Flask
94
  port = int(os.environ.get('PORT', 5000))
95
- app.run(host='0.0.0.0', port=port)
96
- else:
97
- # Si se importa como m贸dulo (en Hugging Face Spaces),
98
- # expone la funci贸n para montar en Gradio
99
- gradio_app = gr.mount_gradio_app(
100
- app,
101
- "/api", # Prefijo para los endpoints de la API
102
- lambda: True # Autenticaci贸n deshabilitada
103
- )
 
2
  from typing import Dict, Optional
3
  import uuid
4
  import os
5
+ from shared import initialize_llm, setup_database_connection, create_agent
6
 
7
  app = Flask(__name__)
8
 
 
84
  except Exception as e:
85
  return jsonify({'error': str(e)}), 500
86
 
 
 
 
 
 
87
  if __name__ == '__main__':
88
  # Si se ejecuta directamente, inicia el servidor Flask
89
  port = int(os.environ.get('PORT', 5000))
90
+ app.run(host='0.0.0.0', port=port)
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -12,7 +12,7 @@ import pandas as pd
12
  import plotly.express as px
13
  import plotly.graph_objects as go
14
  from plotly.subplots import make_subplots
15
- from api import app as flask_app
16
 
17
  # ... (resto del c贸digo existente sin cambios) ...
18
 
@@ -23,8 +23,9 @@ def create_application():
23
 
24
  # Montar la API Flask en la aplicaci贸n Gradio
25
  if os.getenv('SPACE_ID'):
 
26
  demo = gr.mount_gradio_app(
27
- flask_app,
28
  "/api", # Prefijo para los endpoints de la API
29
  lambda: True # Autenticaci贸n deshabilitada
30
  )
 
12
  import plotly.express as px
13
  import plotly.graph_objects as go
14
  from plotly.subplots import make_subplots
15
+ from shared import initialize_llm, setup_database_connection, create_agent
16
 
17
  # ... (resto del c贸digo existente sin cambios) ...
18
 
 
23
 
24
  # Montar la API Flask en la aplicaci贸n Gradio
25
  if os.getenv('SPACE_ID'):
26
+ import api
27
  demo = gr.mount_gradio_app(
28
+ api.app,
29
  "/api", # Prefijo para los endpoints de la API
30
  lambda: True # Autenticaci贸n deshabilitada
31
  )
shared.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import re
4
+ import logging
5
+ from typing import Optional, Tuple
6
+
7
+ try:
8
+ from sqlalchemy import text as sa_text
9
+ except Exception:
10
+ sa_text = None
11
+
12
+ try:
13
+ # Intentar importar dependencias opcionales
14
+ from langchain_community.agent_toolkits import create_sql_agent
15
+ from langchain_community.agent_toolkits.sql.toolkit import SQLDatabaseToolkit
16
+ from langchain_community.utilities import SQLDatabase
17
+ from langchain_google_genai import ChatGoogleGenerativeAI
18
+ from langchain.agents.agent_types import AgentType
19
+ from langchain.memory import ConversationBufferWindowMemory
20
+ from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
21
+ import pymysql
22
+ from dotenv import load_dotenv
23
+
24
+ DEPENDENCIES_AVAILABLE = True
25
+ except ImportError as e:
26
+ logging.warning(f"Some dependencies are not available: {e}")
27
+ DEPENDENCIES_AVAILABLE = False
28
+
29
+ # Configure logging
30
+ logging.basicConfig(level=logging.INFO)
31
+ logger = logging.getLogger(__name__)
32
+
33
+ def check_environment():
34
+ """Verifica si el entorno est谩 configurado correctamente."""
35
+ if not DEPENDENCIES_AVAILABLE:
36
+ return False, "Missing required Python packages. Please install them with: pip install -r requirements.txt"
37
+
38
+ # Verificar si estamos en un entorno con variables de entorno
39
+ required_vars = ["DB_USER", "DB_PASSWORD", "DB_HOST", "DB_NAME", "GOOGLE_API_KEY"]
40
+ missing_vars = [var for var in required_vars if not os.getenv(var)]
41
+
42
+ if missing_vars:
43
+ return False, f"Missing required environment variables: {', '.join(missing_vars)}"
44
+
45
+ return True, "Environment is properly configured"
46
+
47
+ def setup_database_connection():
48
+ """Intenta establecer una conexi贸n a la base de datos."""
49
+ if not DEPENDENCIES_AVAILABLE:
50
+ return None, "Dependencies not available"
51
+
52
+ try:
53
+ load_dotenv(override=True)
54
+
55
+ db_user = os.getenv("DB_USER")
56
+ db_password = os.getenv("DB_PASSWORD")
57
+ db_host = os.getenv("DB_HOST")
58
+ db_name = os.getenv("DB_NAME")
59
+
60
+ if not all([db_user, db_password, db_host, db_name]):
61
+ missing = [var for var, val in [
62
+ ("DB_USER", db_user),
63
+ ("DB_PASSWORD", "*" if db_password else ""),
64
+ ("DB_HOST", db_host),
65
+ ("DB_NAME", db_name)
66
+ ] if not val]
67
+ logger.error(f"Missing required database configuration: {', '.join(missing)}")
68
+ return None, f"Missing database configuration: {', '.join(missing)}"
69
+
70
+ logger.info(f"Connecting to database: {db_user}@{db_host}/{db_name}")
71
+
72
+ # Probar conexi贸n
73
+ connection = pymysql.connect(
74
+ host=db_host,
75
+ user=db_user,
76
+ password=db_password,
77
+ database=db_name,
78
+ connect_timeout=5,
79
+ cursorclass=pymysql.cursors.DictCursor
80
+ )
81
+ connection.close()
82
+
83
+ # Si la conexi贸n es exitosa, crear motor SQLAlchemy
84
+ db_uri = f"mysql+pymysql://{db_user}:{db_password}@{db_host}/{db_name}"
85
+ logger.info("Database connection successful")
86
+ return SQLDatabase.from_uri(db_uri), ""
87
+
88
+ except Exception as e:
89
+ error_msg = f"Error connecting to database: {str(e)}"
90
+ logger.error(error_msg)
91
+ return None, error_msg
92
+
93
+ def initialize_llm():
94
+ """Inicializa el modelo de lenguaje."""
95
+ if not DEPENDENCIES_AVAILABLE:
96
+ error_msg = "Dependencies not available. Make sure all required packages are installed."
97
+ logger.error(error_msg)
98
+ return None, error_msg
99
+
100
+ google_api_key = os.getenv("GOOGLE_API_KEY")
101
+ logger.info(f"GOOGLE_API_KEY found: {'Yes' if google_api_key else 'No'}")
102
+
103
+ if not google_api_key:
104
+ error_msg = "GOOGLE_API_KEY not found in environment variables. Please check your Hugging Face Space secrets."
105
+ logger.error(error_msg)
106
+ return None, error_msg
107
+
108
+ try:
109
+ logger.info("Initializing Google Generative AI...")
110
+ llm = ChatGoogleGenerativeAI(
111
+ model="gemini-2.0-flash",
112
+ temperature=0,
113
+ google_api_key=google_api_key,
114
+ convert_system_message_to_human=True
115
+ )
116
+
117
+ # Test the model with a simple prompt
118
+ test_prompt = "Hello, this is a test."
119
+ logger.info(f"Testing model with prompt: {test_prompt}")
120
+ test_response = llm.invoke(test_prompt)
121
+ logger.info(f"Model test response: {str(test_response)[:100]}...")
122
+
123
+ logger.info("Google Generative AI initialized successfully")
124
+ return llm, ""
125
+
126
+ except Exception as e:
127
+ error_msg = f"Error initializing Google Generative AI: {str(e)}"
128
+ logger.error(error_msg, exc_info=True)
129
+ return None, error_msg
130
+
131
+ def create_agent(llm, db_connection):
132
+ """Create and return a SQL database agent with conversation memory."""
133
+ if not llm:
134
+ error_msg = "Cannot create agent: LLM is not available"
135
+ logger.error(error_msg)
136
+ return None, error_msg
137
+
138
+ if not db_connection:
139
+ error_msg = "Cannot create agent: Database connection is not available"
140
+ logger.error(error_msg)
141
+ return None, error_msg
142
+
143
+ try:
144
+ logger.info("Creating SQL agent with memory...")
145
+
146
+ # Create conversation memory
147
+ memory = ConversationBufferWindowMemory(
148
+ memory_key="chat_history",
149
+ k=5,
150
+ return_messages=True,
151
+ output_key="output"
152
+ )
153
+
154
+ # Create the database toolkit
155
+ toolkit = SQLDatabaseToolkit(
156
+ db=db_connection,
157
+ llm=llm
158
+ )
159
+
160
+ # Create the agent
161
+ agent = create_sql_agent(
162
+ llm=llm,
163
+ toolkit=toolkit,
164
+ agent_type=AgentType.OPENAI_FUNCTIONS,
165
+ verbose=True,
166
+ handle_parsing_errors=True,
167
+ max_iterations=10,
168
+ early_stopping_method="generate",
169
+ memory=memory,
170
+ return_intermediate_steps=True
171
+ )
172
+
173
+ logger.info("SQL agent created successfully")
174
+ return agent, ""
175
+
176
+ except Exception as e:
177
+ error_msg = f"Error creating SQL agent: {str(e)}"
178
+ logger.error(error_msg, exc_info=True)
179
+ return None, error_msg