A hands-on educational repository demonstrating the evolution from basic SQL agents to secure, production-ready analytics systems using LangChain and OpenAI. Learn step-by-step how to build safe, effective SQL agents for business intelligence.
- Python 3.8+
- OpenAI API key (for scripts using LLMs)
- Basic knowledge of SQL and Python
# 1. Create and activate a virtual environment (from project root)
python -m venv .venv && source .venv/bin/activate
# 2. Install dependencies
pip install -r requirements.txt
# 3. Navigate to the SQLAgent folder
cd SQLAgent
# 4. (Optional) Reset the database to its initial state
python scripts/reset_db.py
# 5. Run the tutorial scripts in order
python scripts/00_simple_llm.py # Simple LLM usage (no agents/tools)
python scripts/01_simple_agent.py # Basic SQL agent
python scripts/02_risky_delete_demo.py # β οΈ Dangerous patterns (educational)
python scripts/03_guardrailed_agent.py # Secure implementation
python scripts/04_complex_queries.py # Advanced analytics
agent/
βββ requirements.txt
βββ README.md
βββ SQLAgent/
βββ sql_agent_class.db # SQLite database with sample data
βββ sql_agent_seed.sql # Database schema and seed data
βββ scripts/
βββ 00_simple_llm.py # Simple LLM usage
βββ 01_simple_agent.py # Basic SQL agent
βββ 02_risky_delete_demo.py # Dangerous patterns (educational)
βββ 03_guardrailed_agent.py # Secure SQL agent
βββ 04_complex_queries.py # Advanced analytics
βββ reset_db.py # Database reset utility
Each script demonstrates a new concept or security improvement:
- 00_simple_llm.py β Pure LLM usage, no database or agent
- 01_simple_agent.py β Basic SQL agent, unrestricted access
- 02_risky_delete_demo.py β Shows dangerous patterns and why security is needed
- 03_guardrailed_agent.py β Secure agent with input validation and guardrails
- 04_complex_queries.py β Advanced analytics and business intelligence
- Input validation and SQL injection prevention
- Whitelist-based security (only allow SELECT statements)
- Result set limiting
- Multi-statement prevention
- Error handling and safe reporting
The included SQLite database (sql_agent_class.db
) contains realistic e-commerce data with tables for customers, orders, order_items, products, payments, and refunds. The schema and seed data are in sql_agent_seed.sql
.
- Use the provided SQLite database for learning only
- Do NOT use dangerous patterns from
02_risky_delete_demo.py
in production - Always validate and restrict agent capabilities in real-world applications
Contributions to improve documentation, security, or analytics examples are welcome!
Start with the basics, understand the risks, and build robust, secure SQL agents!