knobik/sql-agent
Self-learning text-to-SQL agent for Laravel that turns natural language into accurate, safe SQL. Uses schema introspection, a curated knowledge base, query patterns, and conversation memory; recovers from errors and saves learnings. Includes built-in chat UI.
SQL Agent for Laravel is a self-learning text-to-SQL agent that converts natural language questions into SQL queries using LLMs.
This package is based on Dash and OpenAI's in-house data agent.
SqlAgent converts questions to SQL through multi-layer context assembly, an agentic tool-calling loop, and a self-learning feedback system. Each query goes through three phases.
Before the LLM sees the question, the ContextBuilder retrieves and assembles six context layers:
| # | Layer | What it contains | Source |
|---|---|---|---|
| 1 | Table Usage | Schema, columns, relationships | knowledge/tables/*.json |
| 2 | Human Annotations | Metrics, definitions, business rules | knowledge/business/*.json |
| 3 | Query Patterns | SQL known to work | knowledge/queries/*.json and *.sql |
| 4 | Learnings | Error patterns and discovered fixes | save_learning tool (on-demand) |
| 5 | Runtime Context | Live schema inspection | introspect_schema tool (on-demand) |
| 6 | Institutional Knowledge | Docs, wikis, external references | Custom tools (agent.tools config) |
Layers 1–3 are loaded from the Knowledge Base and assembled into the system prompt automatically. Layer 4 is built up over time as the agent learns from errors. Layers 5 and 6 are available on-demand — the LLM calls them during the tool loop when it needs live schema details or external context.
The LLM doesn't just receive context and generate one response. It enters an iterative tool-calling loop where it can:
search_knowledge) — Find additional query patterns and learnings mid-conversationintrospect_schema) — Check actual table structures, column types, and indexesrun_sql) — Run queries, observe results, and refine if neededsave_learning, save_validated_query) — Record what it learns for future queriesIf a query fails, the agent can diagnose the error, fix the SQL, and try again — all within the same loop.
The agent improves with use through two mechanisms:
Both feed back into the context assembly phase, so the agent's knowledge grows organically over time. See the Self-Learning guide for details.
:::tip The more questions the agent handles, the richer its context becomes for future queries. Common questions get faster and more reliable as validated patterns accumulate, and past mistakes are avoided as learnings build up. :::
This architecture follows a retrieval-augmented generation (RAG) pattern — but with multiple retrieval layers and a self-improving feedback loop.
pgvector/pgvector package + PostgreSQL with pgvector for semantic similarity searchHow can I help you explore Laravel packages today?