Spaces:
Sleeping
Sleeping
Add Groq AI integration for real NL2SQL functionality
Browse files- Integrated Groq AI (Mixtral-8x7b-32768) for SQL generation
- Added generate_sql_with_groq() function
- Added explain_sql_with_groq() for query explanations
- Replaced hardcoded demo responses with real AI-generated SQL
- Ready to process natural language questions dynamically
- Requires GROQ_API_KEY to be set in HF Spaces secrets
123453 unmodified lines9101112131418 unmodified lines3334353637388 unmodified lines4748495051521 unmodified line545556575859601 unmodified line62636465666768697071727374757677787980818283848586"""FastAPI Backend for OpenNL2SQL - Simplified for HuggingFace SpacesAuthor: Amal SPCreated: December 2025"""3 unmodified linesfrom typing import Optional, List, Dict, Anyimport osimport logging# Configure logginglogging.basicConfig(18 unmodified linesallow_headers=["*"],)# Request/Response Modelsclass QueryRequest(BaseModel):question: str8 unmodified lineserror: Optional[str] = Nonesession_id: str@app.get("/")async def root():"""Health check endpoint"""1 unmodified line"status": "healthy","service": "OpenNL2SQL API","version": "1.0.0","message": "FastAPI backend is running on Hugging Face Spaces!"}@app.get("/health")1 unmodified line"""Detailed health check"""return {"status": "healthy","groq_api_configured": bool(os.getenv("GROQ_API_KEY")),"service": "OpenNL2SQL API"}@app.post("/query", response_model=QueryResponse)async def process_query(request: QueryRequest):"""Process natural language query"""# For now, return a placeholder response# This will be integrated with GROQ API and full backend logicsession_id = request.session_id or "demo-session"return QueryResponse(success=True,sql="SELECT * FROM demo_table LIMIT 10;",results=[{"status": "Backend is running! Full implementation coming soon."}],sql_explanation="This is a demo response. Full NL2SQL functionality will be integrated.",results_explanation="The backend is successfully deployed on Hugging Face Spaces.",session_id=session_id)if __name__ == "__main__":import uvicorn123453 unmodified lines91011121314151618 unmodified lines3536373839404142434445464748498 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271 unmodified line1291301311321331341351361 unmodified line138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197"""FastAPI Backend for OpenNL2SQL with Groq AI IntegrationAuthor: Amal SPCreated: December 2025"""3 unmodified linesfrom typing import Optional, List, Dict, Anyimport osimport loggingfrom groq import Groqimport json# Configure logginglogging.basicConfig(18 unmodified linesallow_headers=["*"],)# Initialize Groq clientGROQ_API_KEY = os.getenv("GROQ_API_KEY")if GROQ_API_KEY:groq_client = Groq(api_key=GROQ_API_KEY)logger.info("Groq client initialized successfully")else:groq_client = Nonelogger.warning("GROQ_API_KEY not found - running in demo mode")# Request/Response Modelsclass QueryRequest(BaseModel):question: str8 unmodified lineserror: Optional[str] = Nonesession_id: strdef generate_sql_with_groq(question: str) -> tuple:"""Generate SQL using Groq AI"""try:# Sample database schemaschema = """Database Schema:- customers (id, name, email, created_at)- orders (id, customer_id, total, status, created_at)- products (id, name, price, category)- order_items (id, order_id, product_id, quantity, price)"""prompt = f"""{schema}Convert this natural language question to a SQL query:Question: {question}Generate ONLY a valid SELECT SQL query. No explanations.SQL Query:"""response = groq_client.chat.completions.create(model="mixtral-8x7b-32768",messages=[{"role": "system", "content": "You are a SQL expert. Generate only valid SQL SELECT queries without any explanations or markdown formatting."},{"role": "user", "content": prompt}],temperature=0.2,max_tokens=500)sql = response.choices[0].message.content.strip()# Clean up the SQLsql = sql.replace("```sql", "").replace("```", "").strip()return sql, Noneexcept Exception as e:logger.error(f"Error generating SQL: {str(e)}")return None, str(e)def explain_sql_with_groq(sql: str, question: str) -> str:"""Generate explanation for SQL query"""try:prompt = f"""Explain this SQL query in simple terms:Original Question: {question}SQL Query: {sql}Provide a brief, clear explanation:"""response = groq_client.chat.completions.create(model="mixtral-8x7b-32768",messages=[{"role": "system", "content": "You are a helpful assistant that explains SQL queries in simple terms."},{"role": "user", "content": prompt}],temperature=0.3,max_tokens=300)return response.choices[0].message.content.strip()except Exception as e:logger.error(f"Error explaining SQL: {str(e)}")return "SQL query generated successfully."@app.get("/")async def root():"""Health check endpoint"""1 unmodified line"status": "healthy","service": "OpenNL2SQL API","version": "1.0.0","message": "FastAPI backend with Groq AI integration running on Hugging Face Spaces!","groq_enabled": groq_client is not None}@app.get("/health")1 unmodified line"""Detailed health check"""return {"status": "healthy","groq_api_configured": groq_client is not None,"service": "OpenNL2SQL API"}@app.post("/query", response_model=QueryResponse)async def process_query(request: QueryRequest):"""Process natural language query with Groq AI"""session_id = request.session_id or "demo-session"# Check if Groq is availableif not groq_client:return QueryResponse(success=False,error="GROQ_API_KEY not configured. Please add it in HF Spaces Settings > Variables.",session_id=session_id)try:# Generate SQL using Groqsql, error = generate_sql_with_groq(request.question)if error:return QueryResponse(success=False,error=f"Failed to generate SQL: {error}",session_id=session_id)# Generate explanationexplanation = explain_sql_with_groq(sql, request.question)# For demo: return mock results# In production, you'd execute the SQL against a real databaseresults = [{"info": "SQL generated successfully! In production, this would execute against your database."},{"note": "Connect your database to see real query results."}]return QueryResponse(success=True,sql=sql,results=results,sql_explanation=explanation,results_explanation=f"Generated SQL query for: '{request.question}'. Ready to execute against your database.",session_id=session_id)except Exception as e:logger.error(f"Error processing query: {str(e)}")return QueryResponse(success=False,error=f"Error: {str(e)}",session_id=session_id)if __name__ == "__main__":import uvicorn
main.py+126-15