knobik / sql-agent
Self-learning text-to-SQL agent for Laravel
Installs: 9
Dependents: 0
Suggesters: 0
Security: 0
Stars: 11
Watchers: 1
Forks: 1
Open Issues: 0
pkg:composer/knobik/sql-agent
Requires
- php: ^8.2
- illuminate/console: ^11.0|^12.0
- illuminate/database: ^11.0|^12.0
- illuminate/support: ^11.0|^12.0
- prism-php/prism: ^0.99
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/pint: ^1.27
- livewire/livewire: ^4.1
- orchestra/testbench: ^9.0|^10.0
- pestphp/pest: ^2.0|^3.0
- pestphp/pest-plugin-laravel: ^2.0|^3.0
- pgvector/pgvector: ^0.2
- phpstan/phpstan: ^2.1
Suggests
- livewire/livewire: Required for the chat UI
- pgvector/pgvector: Required for the pgvector search driver (vector similarity search)
- prism-php/relay: Required for MCP server tool integration (relay config)
This package is auto-updated.
Last update: 2026-02-18 12:09:45 UTC
README
SQL Agent for Laravel
A self-learning text-to-SQL agent that turns natural language into accurate SQL — with context, memory, and a built-in chat UI.
Beta Release — The core API is stabilizing but may still change before v1.0.
Quick Install
composer require knobik/sql-agent php artisan sql-agent:install
Add your LLM provider to .env:
SQL_AGENT_LLM_PROVIDER=openai # or anthropic, ollama, gemini, mistral, xai... SQL_AGENT_LLM_MODEL=gpt-4o
Code Example
use Knobik\SqlAgent\Facades\SqlAgent; $response = SqlAgent::run('Who are our top 5 customers by spending?'); $response->answer; // "Here are the top 5 customers..." $response->sql; // "SELECT c.name, SUM(o.total_amount) / 100 AS total_spent..." $response->results; // [['name' => 'Lowell Boyer', 'total_spent' => 3930.15], ...]
Why This Package?
- Knowledge Base — Curated table metadata, business rules, and query patterns give the LLM the context it needs
- Self-Learning — When a query fails and the agent recovers, it saves that learning. Next time, it knows.
- Multi-Layer Context — Schema introspection, semantic search, conversation history, and accumulated learnings
- SQL Safety — Configurable guardrails prevent destructive operations
How It Works
flowchart TD
A[User Question] --> B[Retrieve Knowledge + Learnings]
B --> C[Reason about intent]
C --> D[Generate grounded SQL]
D --> E[Execute and interpret]
E --> F{Result}
F -->|Success| G[Return insight]
F -->|Error| H[Diagnose & Fix]
H --> I[Save Learning]
I --> D
G --> J[Optionally save as Knowledge]
Loading
The agent uses six context layers to ground its SQL generation:
| # | 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 into the system prompt. 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.
Features
- Multi-LLM Support - Any provider supported by Prism PHP (OpenAI, Anthropic, Ollama, Gemini, Mistral, xAI, and more)
- Multi-Database Support - MySQL, PostgreSQL, SQLite, and SQL Server
- Self-Learning - Automatically learns from SQL errors and improves over time
- Multiple Search Drivers - Database full-text search or pgvector semantic search
- Agentic Loop - Uses tool calling to introspect schema, run queries, and refine results
- Livewire Chat UI - Ready-to-use chat interface with conversation history
- Knowledge Base System - Define table metadata, business rules, and query patterns
- SQL Safety - Configurable statement restrictions and row limits
- Evaluation Framework - Test your agent's accuracy with automated evaluations
Requirements
- PHP 8.2 or higher
- Laravel 11.x or 12.x
- Prism PHP (installed automatically as a dependency)
- An LLM API key or local Ollama installation
- Optional: Livewire 3.x for the chat UI
- Optional: PostgreSQL with pgvector for semantic similarity search via vector embeddings
Documentation
- Configuration - All config options (database, LLM, search, safety, etc.)
- Knowledge Base - Table metadata, business rules, and query patterns
- LLM & Search Drivers - Configure LLM providers and search drivers
- Artisan Commands - All available commands and options
- Programmatic API - Facade, streaming, and dependency injection
- Web Interface - Livewire chat UI and debug mode
- Evaluation - Test accuracy with automated evaluations
- Self-Learning - Automatic learning from errors
- Events - Event hooks for custom behavior
- Agent Tools - All LLM tools with parameters and JSON schemas
- Database Support - MySQL, PostgreSQL, SQLite, SQL Server
- Troubleshooting - Common issues and solutions
Testing
# Run all tests composer test # Run with coverage composer test-coverage
When testing code that uses SqlAgent, you can mock the facade:
use Knobik\SqlAgent\Facades\SqlAgent; use Knobik\SqlAgent\Data\AgentResponse; public function test_it_handles_sql_agent_response(): void { SqlAgent::shouldReceive('run') ->with('How many users?') ->andReturn(new AgentResponse( answer: 'There are 100 users.', sql: 'SELECT COUNT(*) FROM users', results: [['count' => 100]], )); $response = $this->post('/api/query', ['question' => 'How many users?']); $response->assertJson(['answer' => 'There are 100 users.']); }
Contributing
Please see CONTRIBUTING.md for details.
License
SQL Agent for Laravel is open-sourced software licensed under the Apache-2.0 License.
