pythonadvanced
Text-to-SQL with Validation Safety
Convert natural language to SQL with LLM and validate queries before execution for safety.
pythonPress ⌘/Ctrl + Shift + C to copy
import re
from openai import OpenAI
import sqlite3
client = OpenAI()
SAFE_OPERATIONS = {'select', 'with'}
def is_safe_query(sql: str) -> bool:
first_token = sql.strip().split()[0].lower()
has_drop = bool(re.search(r'\b(drop|delete|truncate|alter|create|insert|update)\b', sql, re.I))
return first_token in SAFE_OPERATIONS and not has_drop
def nl_to_sql(question: str, schema: str, model: str = 'gpt-4o-mini') -> str:
prompt = f'Schema:\n{schema}\n\nWrite a SQL SELECT query to answer: {question}\nReturn only the SQL query.'
resp = client.chat.completions.create(model=model, messages=[{'role':'user','content':prompt}], temperature=0)
sql = resp.choices[0].message.content.strip().strip('```sql').strip('```').strip()
return sql
schema = 'users(id, name, age, email); orders(id, user_id, amount, created_at)'
query = nl_to_sql('How many orders has each user placed?', schema)
print('Generated SQL:', query)
print('Is safe:', is_safe_query(query))Use Cases
- safe NL2SQL
- SQL generation
- database Q&A
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonadvanced
Output Guardrails for LLM Responses
Validate and sanitize LLM outputs to prevent hallucination and injection.
Best for: Safety filtering
#ai#guardrails
pythonadvanced
LangChain SQL Database Agent
Create an AI agent that answers natural language questions by querying a SQL database.
Best for: NL2SQL
#langchain#sql
pythonintermediate
LangChain create_sql_query_chain
Generate SQL from natural language using LangChain's create_sql_query_chain with schema awareness.
Best for: NL to SQL
#langchain#nl2sql
typescriptbeginner
Content Moderation with OpenAI
Check user input for harmful content using the OpenAI Moderation API before processing.
Best for: user input safety
#openai#moderation