A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
feat: add Agentic SQL Search project and update root README
cyberholicseaa2c3837f54
diff --git a/README.md b/README.mdindex 6b40a88..8180c68 100644--- a/README.md+++ b/README.md@@ -48,6 +48,7 @@ Intelligent ai agents for various automation tasks.- [**Competitive Intelligence Agent**](./ai_agents/competitive_intelligence_agent) — Multi-agent AI system that generates strategic sales battlecards by analyzing competitors through the unique lens of your own business context.- [**Multi-Agent Research Assistant (AG2)**](./ai_agents/multi_agent_research_assistant_ag2) — Production-grade multi-agent research pipeline using AG2 (formerly AutoGen). Three specialists collaborate under GroupChat with LLM-driven speaker selection to research any topic and produce a structured Markdown report.- [**Self-Reflective Agentic RAG**](./ai_agents/agentic_rag_system) — LangGraph-driven RAG system that grades retrieved context for relevance and sufficiency, rewrites the query if needed, and only generates an answer once the context passes validation — reducing hallucinations through an iterative retrieval loop.+- [**Agentic SQL Search**](./ai_agents/agentic_sql_search) — Natural language to SQL agent powered by Gemma 4. Ask plain-English questions about an e-commerce database and the agent writes, executes, and explains the SQL query — with full reasoning transparency in the Streamlit UI.### 📸 OCRdiff --git a/ai_agents/agentic_sql_search/.env.example b/ai_agents/agentic_sql_search/.env.examplenew file mode 100644index 0000000..1885955--- /dev/null+++ b/ai_agents/agentic_sql_search/.env.example@@ -0,0 +1 @@+GEMINI_API_KEY=your_google_ai_studio_key_herediff --git a/ai_agents/agentic_sql_search/.gitignore b/ai_agents/agentic_sql_search/.gitignorenew file mode 100644index 0000000..26b5dc4--- /dev/null+++ b/ai_agents/agentic_sql_search/.gitignore@@ -0,0 +1,23 @@+# Environment+.env++# Virtual environment+.venv/+venv/+__pycache__/+*.pyc++# Database (auto-generated at runtime)+data/ecommerce.db++# uv+.python-version+uv.lock++# IDE+.vscode/+.idea/++# OS+.DS_Store+Thumbs.dbdiff --git a/ai_agents/agentic_sql_search/README.md b/ai_agents/agentic_sql_search/README.mdnew file mode 100644index 0000000..fbe6d11--- /dev/null+++ b/ai_agents/agentic_sql_search/README.md@@ -0,0 +1,151 @@+# 🔍 Agentic SQL Search++++## Overview++A natural language to SQL agent that lets you query an e-commerce SQLite database in plain English, no SQL knowledge required.++Instead of hardcoding SQL, the agent follows a deliberate three-step process before answering: it loads a SQL skill document for syntax rules and query patterns, inspects the live database schema to confirm column names, then writes and executes the appropriate query. The Streamlit UI exposes the full reasoning trace so you can see every tool call and its result.++## Features++- **Natural Language Queries:** Ask questions in plain English and the agent figures out the SQL+- **Skill-Based Reasoning:** Agent loads a SQL skill document before writing queries, reducing syntax errors and hallucinations+- **Schema Inspection:** Agent always checks the live schema before querying, never guesses column names+- **Full Reasoning Trace:** Every tool call, query, and result is visible in the UI's Agent Reasoning expander+- **Bundled Dataset:** Ships with a ready-to-use e-commerce SQLite database, no external setup required+- **Bring Your Own Database:** Upload any SQLite `.db` file from the sidebar and the agent will inspect its schema and answer questions against it immediately+- **Sample Questions:** Sidebar includes 8 pre-built questions to get started immediately++## Tech Stack++**Frameworks & Libraries:**+- [LangGraph](https://langchain-ai.github.io/langgraph/): ReAct agent via `create_react_agent`+- [LangChain](https://python.langchain.com/): Tool definitions and LLM integration+- [Streamlit](https://streamlit.io/): Interactive web UI with chat interface++**Models (via Google AI / Gemini API):**+- **LLM:** [`gemma-4-26b-a4b-it`](https://ai.google.dev/gemma/docs/core/gemma_on_gemini_api)++**Database:**+- SQLite (bundled sample dataset, auto-generated on first run)++## Dataset++The bundled e-commerce database includes:++| Table | Description |+|---|---|+| `customers` | 20 customers across 10 countries |+| `products` | 25 products across 5 categories |+| `orders` | 40 orders with statuses: pending, processing, shipped, delivered, cancelled |+| `order_items` | 78 line items linking orders to products |++Categories: Electronics, Clothing, Books, Home & Garden, Sports++## How It Works++```+User Question+ │+ ▼+ load_skill('sql') ← loads syntax rules + query patterns+ │+ ▼+ get_schema() ← inspects live table/column structure+ │+ ▼+ execute_sql(query) ← runs the generated SELECT query+ │+ ▼+ Answer + Reasoning Trace+```++**Tools:**+- **`load_skill`** — reads `skills/sql.md`, which contains SQLite syntax rules, common query patterns, and schema reference+- **`get_schema`** — queries `sqlite_master` and `PRAGMA table_info` to return the live database structure+- **`execute_sql`** — runs any SELECT query and returns a formatted table (SELECT-only for safety)++## Prerequisites++- Python 3.12 or higher+- [uv](https://docs.astral.sh/uv/)+- A Google AI Studio API key++## Installation++### 1. Clone the Repository++```bash+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/agentic_sql_search+```++### 2. Set Up Environment Variables++```bash+cp .env.example .env+```++Open `.env` and add your key:++```env+GEMINI_API_KEY=your_google_ai_studio_key_here+```++Get your API key at [Google AI Studio](https://aistudio.google.com/app/apikey).++### 3. Install Dependencies++```bash+uv sync+```++## Usage++```bash+uv run streamlit run app.py+```++Navigate to `http://localhost:8501` in your browser.++The bundled e-commerce SQLite database is created automatically on first run. No extra setup needed.++To query your own database, select **Upload Your Own** in the sidebar and upload any `.db`, `.sqlite`, or `.sqlite3` file. The agent will inspect the schema automatically and you can start asking questions right away.++**Example questions to try (bundled dataset):**+- "Who are the top 5 customers by total spend?"+- "Which product category generates the most revenue?"+- "What is the average order value per country?"+- "Which customers placed more than 2 orders?"++## Project Structure++```text+agentic_sql_search/+├── app.py # Streamlit UI and chat interface+├── agent.py # LangGraph ReAct agent and tool definitions+├── database.py # SQLite schema and sample data seeder+├── skills/+│ └── sql.md # SQL syntax rules and query patterns loaded by the agent+├── assets/+│ └── demo.png # App screenshot+├── data/+│ └── ecommerce.db # SQLite database (auto-generated, gitignored)+├── .env.example # API key template+├── pyproject.toml # Project dependencies (uv)+└── README.md+```++## Contributing++Contributions are welcome! Please feel free to submit a Pull Request.++## License++This project is licensed under the MIT License. See the [LICENSE](../../LICENSE) file for details.++---++[⬆ Back to Top](#-agentic-sql-search)diff --git a/ai_agents/agentic_sql_search/agent.py b/ai_agents/agentic_sql_search/agent.pynew file mode 100644index 0000000..3431f79--- /dev/null+++ b/ai_agents/agentic_sql_search/agent.py@@ -0,0 +1,183 @@+"""+Agentic SQL Search — LangGraph ReAct agent with three tools:+ • load_skill — loads SQL syntax rules and schema reference+ • get_schema — inspects the live database schema+ • execute_sql — runs a SELECT query and returns results+"""++import os+import sqlite3+from pathlib import Path++from dotenv import load_dotenv+from langchain_core.messages import AIMessage, ToolMessage+from langchain_core.tools import tool+from langchain_google_genai import ChatGoogleGenerativeAI+from langgraph.prebuilt import create_react_agent++load_dotenv()++DB_PATH = Path(__file__).parent / "data" / "ecommerce.db"+SKILLS_DIR = Path(__file__).parent / "skills"++# Mutable active path — updated at runtime when user uploads their own database+_active_db_path: Path = DB_PATH+++def set_db_path(path) -> None:+ """Switch the database the agent tools query against."""+ global _active_db_path+ _active_db_path = Path(path)++llm = ChatGoogleGenerativeAI(+ model="gemma-4-26b-a4b-it",+ google_api_key=os.getenv("GEMINI_API_KEY"),+ temperature=0,+)+++# ── Tools ──────────────────────────────────────────────────────────────────────++@tool+def load_skill(skill_name: str) -> str:+ """+ Load a skill document with syntax rules and query patterns.+ Always call this first with skill_name='sql' before writing any query.+ """+ path = SKILLS_DIR / f"{skill_name}.md"+ if not path.exists():+ available = [p.stem for p in SKILLS_DIR.glob("*.md")]+ return f"Skill '{skill_name}' not found. Available: {', '.join(available)}"+ return path.read_text()+++@tool+def get_schema() -> str:+ """+ Return the full database schema — table names, column names, and types.+ Call this to understand what tables and columns are available before writing SQL.+ """+ conn = sqlite3.connect(_active_db_path)+ cursor = conn.cursor()+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")+ tables = [row[0] for row in cursor.fetchall()]++ schema_parts = []+ for table in tables:+ cursor.execute(f"PRAGMA table_info({table})")+ cols = cursor.fetchall()+ col_defs = "\n".join([f" {c[1]:30s} {c[2]}" for c in cols])+ schema_parts.append(f"TABLE: {table}\n{col_defs}")++ conn.close()+ return "\n\n".join(schema_parts)+++@tool+def execute_sql(query: str) -> str:+ """+ Execute a SQL SELECT query against the e-commerce SQLite database.+ Returns results as a formatted table. Only SELECT queries are allowed.+ """+ query = query.strip()+ if not query.upper().startswith("SELECT"):+ return "Error: Only SELECT queries are allowed."++ try:+ conn = sqlite3.connect(_active_db_path)+ cursor = conn.cursor()+ cursor.execute(query)+ rows = cursor.fetchall()+ columns = [desc[0] for desc in cursor.description]+ conn.close()++ if not rows:+ return "Query executed successfully but returned no results."++ col_widths = [+ max(len(col), max((len(str(row[i])) for row in rows), default=0))+ for i, col in enumerate(columns)+ ]+ header = " | ".join(col.ljust(w) for col, w in zip(columns, col_widths))+ separator = "-+-".join("-" * w for w in col_widths)+ data_rows = [+ " | ".join(str(row[i]).ljust(col_widths[i]) for i in range(len(columns)))+ for row in rows[:100]+ ]+ result = "\n".join([header, separator] + data_rows)+ if len(rows) > 100:+ result += f"\n... ({len(rows)} total rows, showing first 100)"+ return result++ except sqlite3.Error as e:+ return f"SQL Error: {e}"+++# ── Agent ──────────────────────────────────────────────────────────────────────++tools = [load_skill, get_schema, execute_sql]++SYSTEM_PROMPT = """You are a data analyst agent with access to an e-commerce SQLite database \+containing customers, products, orders, and order items.++Your job is to answer the user's question by querying the database.++Always follow this exact workflow:+1. Call load_skill with skill_name='sql' to review SQL syntax rules and query patterns+2. Call get_schema to confirm available tables and column names+3. Write and run the SQL query with execute_sql+4. Return a clear, concise summary of the results++Never guess column names — always check the schema first.+Only write SELECT queries. Be precise with JOINs and aggregations."""++graph = create_react_agent(llm, tools=tools, prompt=SYSTEM_PROMPT)+++def run_agent(question: str) -> dict:+ """+ Run the agent on a question and return:+ {"answer": str, "steps": [{"tool": str, "input": dict, "output": str}]}+ """+ result = graph.invoke({"messages": [("human", question)]})+ messages = result["messages"]++ # ── Extract final text answer (last non-tool AI message) ──+ answer = ""+ for msg in reversed(messages):+ if isinstance(msg, AIMessage) and not msg.tool_calls:+ content = msg.content+ if isinstance(content, str):+ answer = content.strip()+ elif isinstance(content, list):+ parts = [+ p.get("text", "") if isinstance(p, dict) else str(p)+ for p in content+ ]+ answer = " ".join(parts).strip()+ if answer:+ break++ # ── Extract tool call steps ──+ steps = []+ tool_outputs: dict[str, str] = {}++ # First pass: collect tool outputs keyed by tool_call_id+ for msg in messages:+ if isinstance(msg, ToolMessage):+ content = msg.content+ tool_outputs[msg.tool_call_id] = (+ content if isinstance(content, str) else str(content)+ )++ # Second pass: pair AI tool calls with their outputs+ for msg in messages:+ if isinstance(msg, AIMessage) and msg.tool_calls:+ for tc in msg.tool_calls:+ steps.append({+ "tool": tc["name"],+ "input": tc["args"],+ "output": tool_outputs.get(tc["id"], ""),+ })++ return {"answer": answer, "steps": steps}diff --git a/ai_agents/agentic_sql_search/app.py b/ai_agents/agentic_sql_search/app.pynew file mode 100644index 0000000..e3e3860--- /dev/null+++ b/ai_agents/agentic_sql_search/app.py@@ -0,0 +1,224 @@+"""+Agentic SQL Search — Streamlit UI+Run: streamlit run app.py+"""++import sqlite3+import tempfile+from pathlib import Path++import streamlit as st++from database import DB_PATH, init_db+from agent import run_agent, set_db_path++# ── Page config ────────────────────────────────────────────────────────────────+st.set_page_config(+ page_title="Agentic SQL Search",+ page_icon="🔍",+ layout="wide",+ initial_sidebar_state="expanded",+)++# Ensure the bundled DB exists on every startup+init_db()+++# ── Helpers ────────────────────────────────────────────────────────────────────++def get_schema_map(db_path) -> dict[str, list[tuple]]:+ """Return {table_name: [column_info, ...]} for the given database."""+ try:+ conn = sqlite3.connect(db_path)+ cursor = conn.cursor()+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")+ tables = [row[0] for row in cursor.fetchall()]+ schema = {}+ for table in tables:+ cursor.execute(f"PRAGMA table_info({table})")+ schema[table] = cursor.fetchall()+ conn.close()+ return schema+ except Exception:+ return {}+++def get_active_db_path() -> Path:+ """Return the currently active database path from session state."""+ return st.session_state.get("active_db_path", DB_PATH)+++def render_steps(steps: list):+ """Render agent intermediate steps inside a Streamlit expander."""+ with st.expander("🔎 Agent Reasoning", expanded=False):+ for i, step in enumerate(steps, 1):+ tool_name = step["tool"]+ tool_input = step["input"]+ tool_output = step["output"]++ st.markdown(f"**Step {i} — `{tool_name}`**")++ if tool_name == "execute_sql":+ query = tool_input.get("query", str(tool_input))+ st.code(query, language="sql")+ elif tool_name == "load_skill":+ skill = tool_input.get("skill_name", str(tool_input))+ st.markdown(f"Loading skill: `{skill}`")+ else:+ st.code(str(tool_input))++ preview = tool_output[:600] + (" …" if len(tool_output) > 600 else "")+ st.markdown("**Result:**")+ st.text(preview)++ if i < len(steps):+ st.divider()+++# ── Sidebar ────────────────────────────────────────────────────────────────────+with st.sidebar:+ st.title("🔍 Agentic SQL Search")+ st.divider()++ # ── Database selector ──+ st.markdown("### 🗄️ Database")+ db_mode = st.radio(+ "Choose a database",+ options=["Bundled E-Commerce Dataset", "Upload Your Own"],+ index=0,+ label_visibility="collapsed",+ )++ if db_mode == "Upload Your Own":+ uploaded_file = st.file_uploader(+ "Upload a SQLite database",+ type=["db", "sqlite", "sqlite3"],+ help="Upload any SQLite .db file. The agent will inspect its schema automatically.",+ )+ if uploaded_file is not None:+ # Save to a temp file that persists for this session+ if "uploaded_db_path" not in st.session_state or \+ st.session_state.get("uploaded_db_name") != uploaded_file.name:+ tmp = tempfile.NamedTemporaryFile(+ suffix=".db", delete=False, dir=Path(__file__).parent / "data"+ )+ tmp.write(uploaded_file.getbuffer())+ tmp.close()+ st.session_state["uploaded_db_path"] = tmp.name+ st.session_state["uploaded_db_name"] = uploaded_file.name+ st.session_state["messages"] = [] # clear chat for new DB++ active_path = Path(st.session_state["uploaded_db_path"])+ st.session_state["active_db_path"] = active_path+ set_db_path(active_path)+ st.success(f"Using: {uploaded_file.name}")+ else:+ # No file uploaded yet — fall back to bundled+ st.session_state["active_db_path"] = DB_PATH+ set_db_path(DB_PATH)+ st.caption("No file uploaded yet. Showing bundled dataset schema.")+ else:+ st.session_state["active_db_path"] = DB_PATH+ set_db_path(DB_PATH)+ st.caption("20 customers · 25 products · 40 orders · 5 categories")++ st.divider()++ # ── Schema viewer (reflects active DB) ──+ active_db = get_active_db_path()+ st.markdown("### 📊 Schema")+ schema_map = get_schema_map(active_db)+ if schema_map:+ for table_name, columns in schema_map.items():+ with st.expander(f"`{table_name}`"):+ for col in columns:+ pk_badge = " 🔑" if col[5] else ""+ st.markdown(f"`{col[1]}` — *{col[2]}*{pk_badge}")+ else:+ st.caption("No tables found in this database.")++ st.divider()++ # ── Sample questions (only for bundled dataset) ──+ if db_mode == "Bundled E-Commerce Dataset":+ st.markdown("### 💡 Try These")+ SAMPLE_QUESTIONS = [+ "Who are the top 5 customers by total spend?",+ "Which product category generates the most revenue?",+ "What are the 3 best-selling products by units sold?",+ "How many orders are in each status?",+ "What is the average order value per country?",+ "List all products with less than 100 units in stock.",+ "Which customers placed more than 2 orders?",+ "What's the total revenue from Electronics?",+ ]+ for q in SAMPLE_QUESTIONS:+ if st.button(q, use_container_width=True, key=f"btn_{q[:20]}"):+ st.session_state["pending_q"] = q+ st.divider()++ if st.button("🗑️ Clear Chat", use_container_width=True):+ st.session_state["messages"] = []+ st.rerun()+++# ── Main ───────────────────────────────────────────────────────────────────────+st.title("🔍 Agentic SQL Search")++active_db = get_active_db_path()+if active_db == DB_PATH:+ st.markdown(+ "Ask any question about the e-commerce data in plain English. "+ "The agent writes the SQL, runs it, and explains the results."+ )+else:+ st.markdown(+ f"Querying **{st.session_state.get('uploaded_db_name', 'uploaded database')}**. "+ "The agent will inspect the schema and write the SQL for you."+ )++st.divider()++# Init chat history+if "messages" not in st.session_state:+ st.session_state["messages"] = []++# Render chat history+for msg in st.session_state["messages"]:+ with st.chat_message(msg["role"]):+ st.markdown(msg["content"])+ if msg.get("steps"):+ render_steps(msg["steps"])++# Resolve input — typed or clicked from sidebar+question: str | None = st.chat_input("Ask a question about the data…")+if "pending_q" in st.session_state:+ question = st.session_state.pop("pending_q")++if question:+ # Ensure agent is pointed at the active DB before running+ set_db_path(get_active_db_path())++ st.session_state["messages"].append({"role": "user", "content": question})+ with st.chat_message("user"):+ st.markdown(question)++ with st.chat_message("assistant"):+ with st.spinner("Querying the database…"):+ try:+ result = run_agent(question)+ answer = result.get("answer", "No answer generated.")+ steps = result.get("steps", [])+ except Exception as e:+ answer = f"❌ Error: {e}"+ steps = []++ st.markdown(answer)+ if steps:+ render_steps(steps)++ st.session_state["messages"].append({+ "role": "assistant",+ "content": answer,+ "steps": steps,+ })diff --git a/ai_agents/agentic_sql_search/assets/demo.png b/ai_agents/agentic_sql_search/assets/demo.pngnew file mode 100644index 0000000..2f1365eBinary files /dev/null and b/ai_agents/agentic_sql_search/assets/demo.png differdiff --git a/ai_agents/agentic_sql_search/database.py b/ai_agents/agentic_sql_search/database.pynew file mode 100644index 0000000..681ba36--- /dev/null+++ b/ai_agents/agentic_sql_search/database.py@@ -0,0 +1,266 @@+"""+SQLite e-commerce database — schema definition and sample data seeding.+Run this file directly to (re)create the database: python database.py+"""++import sqlite3+from pathlib import Path++DB_PATH = Path(__file__).parent / "data" / "ecommerce.db"++CREATE_TABLES = [+ """CREATE TABLE IF NOT EXISTS customers (+ id INTEGER PRIMARY KEY,+ name TEXT NOT NULL,+ email TEXT NOT NULL,+ city TEXT,+ country TEXT,+ signup_date TEXT+ )""",+ """CREATE TABLE IF NOT EXISTS products (+ id INTEGER PRIMARY KEY,+ name TEXT NOT NULL,+ category TEXT NOT NULL,+ price REAL NOT NULL,+ stock INTEGER NOT NULL DEFAULT 0+ )""",+ """CREATE TABLE IF NOT EXISTS orders (+ id INTEGER PRIMARY KEY,+ customer_id INTEGER NOT NULL,+ order_date TEXT NOT NULL,+ status TEXT NOT NULL,+ FOREIGN KEY (customer_id) REFERENCES customers(id)+ )""",+ """CREATE TABLE IF NOT EXISTS order_items (+ id INTEGER PRIMARY KEY,+ order_id INTEGER NOT NULL,+ product_id INTEGER NOT NULL,+ quantity INTEGER NOT NULL,+ unit_price REAL NOT NULL,+ FOREIGN KEY (order_id) REFERENCES orders(id),+ FOREIGN KEY (product_id) REFERENCES products(id)+ )""",+]++CUSTOMERS = [+ (1, "Alice Johnson", "[email protected]", "New York", "US", "2022-03-10"),+ (2, "Bob Martinez", "[email protected]", "Los Angeles", "US", "2022-05-22"),+ (3, "Clara Schmidt", "[email protected]", "Berlin", "DE", "2022-07-14"),+ (4, "David Chen", "[email protected]", "Shanghai", "CN", "2022-08-01"),+ (5, "Eva Rossi", "[email protected]", "Milan", "IT", "2022-09-30"),+ (6, "Frank Dubois", "[email protected]", "Paris", "FR", "2022-11-05"),+ (7, "Grace Kim", "[email protected]", "Seoul", "KR", "2023-01-18"),+ (8, "Henry Brown", "[email protected]", "London", "UK", "2023-02-27"),+ (9, "Isabelle Nguyen", "[email protected]", "Toronto", "CA", "2023-04-03"),+ (10, "James Wilson", "[email protected]", "Sydney", "AU", "2023-05-11"),+ (11, "Karen Davis", "[email protected]", "Chicago", "US", "2023-06-15"),+ (12, "Luis Fernandez", "[email protected]", "Madrid", "ES", "2023-07-20"),+ (13, "Mia Tanaka", "[email protected]", "Tokyo", "JP", "2023-08-08"),+ (14, "Noah Anderson", "[email protected]", "Boston", "US", "2023-09-14"),+ (15, "Olivia Taylor", "[email protected]", "Amsterdam", "NL", "2023-10-22"),+ (16, "Paul Müller", "[email protected]", "Munich", "DE", "2023-11-30"),+ (17, "Quinn Patel", "[email protected]", "Mumbai", "IN", "2024-01-07"),+ (18, "Rachel Lee", "[email protected]", "San Francisco", "US", "2024-02-19"),+ (19, "Samuel Okafor", "[email protected]", "Lagos", "NG", "2024-03-03"),+ (20, "Tina Kowalski", "[email protected]", "Warsaw", "PL", "2024-04-11"),+]++PRODUCTS = [+ # Electronics+ (1, "Wireless Headphones", "Electronics", 89.99, 120),+ (2, "Bluetooth Speaker", "Electronics", 49.99, 200),+ (3, "USB-C Hub", "Electronics", 34.99, 350),+ (4, "Mechanical Keyboard", "Electronics", 109.99, 80),+ (5, "4K Webcam", "Electronics", 79.99, 90),+ (6, "Portable Charger", "Electronics", 29.99, 400),+ # Clothing+ (7, "Merino Wool Sweater", "Clothing", 69.99, 160),+ (8, "Running Shoes", "Clothing", 94.99, 210),+ (9, "Waterproof Jacket", "Clothing", 129.99, 75),+ (10, "Cotton T-Shirt", "Clothing", 19.99, 500),+ (11, "Slim Fit Chinos", "Clothing", 54.99, 180),+ # Books+ (12, "Clean Code", "Books", 35.99, 300),+ (13, "Designing Data-Intensive Applications", "Books", 49.99, 250),+ (14, "The Pragmatic Programmer","Books", 42.99, 280),+ (15, "Deep Learning with Python","Books", 44.99, 190),+ (16, "Atomic Habits", "Books", 18.99, 450),+ # Home & Garden+ (17, "Bamboo Desk Organizer", "Home & Garden", 24.99, 310),+ (18, "Ceramic Plant Pot", "Home & Garden", 14.99, 420),+ (19, "LED Desk Lamp", "Home & Garden", 39.99, 150),+ (20, "Memory Foam Pillow", "Home & Garden", 44.99, 200),+ (21, "Stainless Steel Water Bottle","Home & Garden",22.99,380),+ # Sports+ (22, "Yoga Mat", "Sports", 32.99, 260),+ (23, "Resistance Bands Set", "Sports", 18.99, 330),+ (24, "Jump Rope", "Sports", 9.99, 500),+ (25, "Foam Roller", "Sports", 27.99, 175),+]++ORDERS = [+ # (id, customer_id, order_date, status)+ (1, 1, "2024-01-05", "delivered"),+ (2, 2, "2024-01-08", "delivered"),+ (3, 3, "2024-01-12", "delivered"),+ (4, 4, "2024-01-15", "delivered"),+ (5, 5, "2024-01-20", "delivered"),+ (6, 6, "2024-02-01", "delivered"),+ (7, 7, "2024-02-05", "delivered"),+ (8, 8, "2024-02-10", "delivered"),+ (9, 9, "2024-02-14", "delivered"),+ (10, 10, "2024-02-18", "delivered"),+ (11, 1, "2024-02-22", "delivered"),+ (12, 2, "2024-03-01", "delivered"),+ (13, 3, "2024-03-05", "delivered"),+ (14, 11, "2024-03-10", "delivered"),+ (15, 12, "2024-03-15", "delivered"),+ (16, 13, "2024-03-20", "delivered"),+ (17, 14, "2024-03-25", "delivered"),+ (18, 15, "2024-04-01", "delivered"),+ (19, 16, "2024-04-05", "delivered"),+ (20, 17, "2024-04-10", "shipped"),+ (21, 1, "2024-04-12", "shipped"),+ (22, 5, "2024-04-14", "shipped"),+ (23, 8, "2024-04-16", "processing"),+ (24, 18, "2024-04-18", "processing"),+ (25, 19, "2024-04-19", "processing"),+ (26, 20, "2024-04-20", "pending"),+ (27, 3, "2024-04-21", "pending"),+ (28, 7, "2024-04-22", "pending"),+ (29, 10, "2024-04-23", "pending"),+ (30, 2, "2024-04-23", "cancelled"),+ (31, 6, "2024-03-28", "cancelled"),+ (32, 9, "2024-03-02", "delivered"),+ (33, 11, "2024-03-08", "delivered"),+ (34, 13, "2024-02-25", "delivered"),+ (35, 14, "2024-01-30", "delivered"),+ (36, 15, "2024-02-08", "delivered"),+ (37, 16, "2024-01-22", "delivered"),+ (38, 17, "2024-03-18", "delivered"),+ (39, 18, "2024-02-28", "delivered"),+ (40, 19, "2024-04-02", "shipped"),+]++ORDER_ITEMS = [+ # (id, order_id, product_id, quantity, unit_price)+ (1, 1, 1, 1, 89.99),+ (2, 1, 6, 2, 29.99),+ (3, 2, 8, 1, 94.99),+ (4, 2, 10, 3, 19.99),+ (5, 3, 4, 1,109.99),+ (6, 3, 12, 1, 35.99),+ (7, 4, 2, 2, 49.99),+ (8, 4, 18, 3, 14.99),+ (9, 5, 9, 1,129.99),+ (10, 5, 22, 1, 32.99),+ (11, 6, 3, 2, 34.99),+ (12, 6, 19, 1, 39.99),+ (13, 7, 5, 1, 79.99),+ (14, 7, 15, 1, 44.99),+ (15, 8, 13, 1, 49.99),+ (16, 8, 16, 2, 18.99),+ (17, 9, 7, 2, 69.99),+ (18, 9, 21, 1, 22.99),+ (19,10, 11, 1, 54.99),+ (20,10, 24, 2, 9.99),+ (21,11, 1, 1, 89.99),+ (22,11, 14, 1, 42.99),+ (23,12, 8, 1, 94.99),+ (24,12, 23, 2, 18.99),+ (25,13, 4, 1,109.99),+ (26,13, 17, 2, 24.99),+ (27,14, 2, 1, 49.99),+ (28,14, 20, 1, 44.99),+ (29,15, 9, 1,129.99),+ (30,15, 25, 1, 27.99),+ (31,16, 5, 1, 79.99),+ (32,16, 12, 2, 35.99),+ (33,17, 6, 3, 29.99),+ (34,17, 16, 1, 18.99),+ (35,18, 3, 2, 34.99),+ (36,18, 22, 1, 32.99),+ (37,19, 15, 1, 44.99),+ (38,19, 10, 5, 19.99),+ (39,20, 7, 1, 69.99),+ (40,20, 18, 2, 14.99),+ (41,21, 1, 2, 89.99),+ (42,21, 3, 1, 34.99),+ (43,22, 9, 1,129.99),+ (44,22, 24, 3, 9.99),+ (45,23, 13, 1, 49.99),+ (46,23, 21, 2, 22.99),+ (47,24, 4, 1,109.99),+ (48,24, 19, 1, 39.99),+ (49,25, 8, 1, 94.99),+ (50,25, 11, 2, 54.99),+ (51,26, 16, 3, 18.99),+ (52,26, 23, 1, 18.99),+ (53,27, 2, 1, 49.99),+ (54,27, 17, 1, 24.99),+ (55,28, 5, 1, 79.99),+ (56,28, 20, 1, 44.99),+ (57,29, 14, 2, 42.99),+ (58,29, 25, 1, 27.99),+ (59,30, 6, 2, 29.99),+ (60,31, 12, 1, 35.99),+ (61,32, 7, 1, 69.99),+ (62,32, 10, 4, 19.99),+ (63,33, 1, 1, 89.99),+ (64,33, 22, 2, 32.99),+ (65,34, 9, 1,129.99),+ (66,34, 15, 1, 44.99),+ (67,35, 4, 1,109.99),+ (68,35, 3, 2, 34.99),+ (69,36, 13, 1, 49.99),+ (70,36, 16, 2, 18.99),+ (71,37, 8, 1, 94.99),+ (72,37, 24, 2, 9.99),+ (73,38, 2, 2, 49.99),+ (74,38, 21, 1, 22.99),+ (75,39, 5, 1, 79.99),+ (76,39, 11, 1, 54.99),+ (77,40, 6, 3, 29.99),+ (78,40, 18, 2, 14.99),+]+++def init_db():+ """Create tables and seed sample data if the database doesn't exist yet."""+ DB_PATH.parent.mkdir(parents=True, exist_ok=True)++ conn = sqlite3.connect(DB_PATH)+ conn.execute("PRAGMA foreign_keys = ON")+ cursor = conn.cursor()++ for stmt in CREATE_TABLES:+ cursor.execute(stmt)+ conn.commit()++ # Only seed if tables are empty+ if cursor.execute("SELECT COUNT(*) FROM customers").fetchone()[0] == 0:+ cursor.executemany(+ "INSERT INTO customers VALUES (?,?,?,?,?,?)", CUSTOMERS+ )+ cursor.executemany(+ "INSERT INTO products VALUES (?,?,?,?,?)", PRODUCTS+ )+ cursor.executemany(+ "INSERT INTO orders VALUES (?,?,?,?)", ORDERS+ )+ cursor.executemany(+ "INSERT INTO order_items VALUES (?,?,?,?,?)", ORDER_ITEMS+ )++ conn.commit()+ conn.close()+++if __name__ == "__main__":+ init_db()+ print(f"✅ Database created at {DB_PATH}")+ conn = sqlite3.connect(DB_PATH)+ for table in ["customers", "products", "orders", "order_items"]:+ count = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]+ print(f" {table}: {count} rows")+ conn.close()diff --git a/ai_agents/agentic_sql_search/pyproject.toml b/ai_agents/agentic_sql_search/pyproject.tomlnew file mode 100644index 0000000..c549ec8--- /dev/null+++ b/ai_agents/agentic_sql_search/pyproject.toml@@ -0,0 +1,13 @@+[project]+name = "agentic-sql-search"+version = "0.1.0"+description = "Natural language to SQL agent — ask questions about an e-commerce database in plain English"+readme = "README.md"+requires-python = ">=3.12"+dependencies = [+ "streamlit>=1.45.0",+ "langchain>=0.3.0",+ "langchain-google-genai>=4.2.2",+ "langgraph>=0.2.0",+ "python-dotenv>=1.1.1",+]diff --git a/ai_agents/agentic_sql_search/skills/sql.md b/ai_agents/agentic_sql_search/skills/sql.mdnew file mode 100644index 0000000..175c869--- /dev/null+++ b/ai_agents/agentic_sql_search/skills/sql.md@@ -0,0 +1,94 @@+# SQL Skill — E-Commerce Database++## Database Schema++```+customers (id, name, email, city, country, signup_date)+products (id, name, category, price, stock)+orders (id, customer_id, order_date, status)+order_items (id, order_id, product_id, quantity, unit_price)+```++### Column notes+- `orders.status` — one of: `pending`, `processing`, `shipped`, `delivered`, `cancelled`+- `products.category` — one of: `Electronics`, `Clothing`, `Books`, `Home & Garden`, `Sports`+- All dates are stored as ISO strings: `YYYY-MM-DD`+- Revenue for an item = `quantity * unit_price`++---++## Common Query Patterns++### Total revenue per order+```sql+SELECT order_id, SUM(quantity * unit_price) AS total+FROM order_items+GROUP BY order_id;+```++### Top customers by spend+```sql+SELECT c.name, SUM(oi.quantity * oi.unit_price) AS total_spend+FROM customers c+JOIN orders o ON c.id = o.customer_id+JOIN order_items oi ON o.id = oi.order_id+WHERE o.status != 'cancelled'+GROUP BY c.id, c.name+ORDER BY total_spend DESC+LIMIT 10;+```++### Best-selling products (by quantity)+```sql+SELECT p.name, SUM(oi.quantity) AS units_sold+FROM products p+JOIN order_items oi ON p.id = oi.product_id+GROUP BY p.id, p.name+ORDER BY units_sold DESC;+```++### Revenue by category+```sql+SELECT p.category, SUM(oi.quantity * oi.unit_price) AS revenue+FROM products p+JOIN order_items oi ON p.id = oi.product_id+JOIN orders o ON oi.order_id = o.id+WHERE o.status != 'cancelled'+GROUP BY p.category+ORDER BY revenue DESC;+```++### Orders in a date range+```sql+SELECT * FROM orders+WHERE order_date BETWEEN '2024-01-01' AND '2024-03-31';+```++### Orders by status count+```sql+SELECT status, COUNT(*) AS count+FROM orders+GROUP BY status+ORDER BY count DESC;+```++---++## SQLite Syntax Rules++1. **String literals** use single quotes: `WHERE city = 'London'`+2. **Date functions**: Use `strftime('%Y', order_date)` to extract year; `DATE('now')` for today+3. **LIKE wildcards**: `%` matches any sequence, `_` matches one character — `WHERE name LIKE '%phone%'`+4. **No ILIKE**: SQLite `LIKE` is case-insensitive for ASCII by default+5. **Integer division**: Cast explicitly — `CAST(a AS REAL) / b` for decimal results+6. **No RIGHT JOIN**: Rewrite as LEFT JOIN with tables swapped+7. **LIMIT always at end**: Place `LIMIT` after `ORDER BY`+8. **Subqueries**: Supported — wrap in parentheses with an alias: `FROM (SELECT ...) AS sub`++---++## Safety Rules++- Only write `SELECT` queries — never `INSERT`, `UPDATE`, `DELETE`, or `DROP`+- Always alias aggregated columns for clarity: `SUM(...) AS revenue`+- Check column names against the schema — never assume a column exists