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
12123453 unmodified lines91011121314151618 unmodified lines3536373839404142434445464748498 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271 unmodified line129130131571321331341351361 unmodified line138139140651411421431441451467172731471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771787677787980818283179180181182183184185186187188189190191192193194195196197"""FastAPI Backend for OpenNL2SQL - Simplified for HuggingFace SpacesAuthor: Amal SP"""FastAPI Backend for OpenNL2SQL with Groq AI IntegrationAuthor: Amal SP Created: December 2025"""
3 unmodified linesfrom typing import Optional, List, Dict, Anyimport osimport loggingfrom groq import Groqimport json
# Configure logginglogging.basicConfig(18 unmodified lines allow_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 = None logger.warning("GROQ_API_KEY not found - running in demo mode")
# Request/Response Modelsclass QueryRequest(BaseModel): question: str8 unmodified lines error: Optional[str] = None session_id: str
def generate_sql_with_groq(question: str) -> tuple: """Generate SQL using Groq AI""" try: # Sample database schema schema = """ 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 SQL sql = sql.replace("```sql", "").replace("```", "").strip() return sql, None except 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 is running on Hugging Face Spaces!" "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": bool(os.getenv("GROQ_API_KEY")), "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""" # For now, return a placeholder response # This will be integrated with GROQ API and full backend logic """Process natural language query with Groq AI""" session_id = request.session_id or "demo-session" # Check if Groq is available if 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 Groq sql, 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 explanation explanation = explain_sql_with_groq(sql, request.question) # For demo: return mock results # In production, you'd execute the SQL against a real database results = [ {"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="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 ) 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 uvicornmain.py+126-15