PHPackages                             knobik/laravel-sql-agent - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. knobik/laravel-sql-agent

Abandoned → [knobik/sql-agent](/?search=knobik%2Fsql-agent)Library[Database &amp; ORM](/categories/database)

knobik/laravel-sql-agent
========================

Self-learning text-to-SQL agent for Laravel

0.8.1(2mo ago)1322[2 PRs](https://github.com/knobik/sql-agent/pulls)Apache-2.0PHPPHP ^8.2CI passing

Since Feb 4Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/knobik/sql-agent)[ Packagist](https://packagist.org/packages/knobik/laravel-sql-agent)[ RSS](/packages/knobik-laravel-sql-agent/feed)WikiDiscussions main Synced 2mo ago

READMEChangelog (9)Dependencies (12)Versions (21)Used By (0)

 [![SQL Agent for Laravel](art/logo.svg)](art/logo.svg)

SQL Agent for Laravel
=====================

[](#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.

 [![SQL Agent chat UI showing a natural language query being converted to SQL with results](art/screenshot.png)](art/screenshot.png)

> **Beta Release** — The core API is stabilizing but may still change before v1.0.

Quick Install
-------------

[](#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
------------

[](#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?
-----------------

[](#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
------------

[](#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:

\#LayerWhat it containsSource1Table UsageSchema, columns, relationships`knowledge/tables/*.json`2Human AnnotationsMetrics, definitions, business rules`knowledge/business/*.json`3Query PatternsSQL known to work`knowledge/queries/*.json` and `*.sql`4LearningsError patterns and discovered fixes`save_learning` tool (on-demand)5Runtime ContextLive schema inspection`introspect_schema` tool (on-demand)6Institutional KnowledgeDocs, wikis, external referencesCustom 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
--------

[](#features)

- **Multi-LLM Support** - Any provider supported by [Prism PHP](https://prismphp.com) (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
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 11.x or 12.x
- [Prism PHP](https://prismphp.com) (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
-------------

[](#documentation)

**[Read the full documentation](https://knobik.github.io/sql-agent/)**

- [Configuration](https://knobik.github.io/sql-agent/guides/configuration/) - All config options (database, LLM, search, safety, etc.)
- [Knowledge Base](https://knobik.github.io/sql-agent/guides/knowledge-base/) - Table metadata, business rules, and query patterns
- [LLM &amp; Search Drivers](https://knobik.github.io/sql-agent/guides/drivers/) - Configure LLM providers and search drivers
- [Artisan Commands](https://knobik.github.io/sql-agent/reference/commands/) - All available commands and options
- [Programmatic API](https://knobik.github.io/sql-agent/reference/api/) - Facade, streaming, and dependency injection
- [Web Interface](https://knobik.github.io/sql-agent/guides/web-interface/) - Livewire chat UI and debug mode
- [Evaluation](https://knobik.github.io/sql-agent/guides/evaluation/) - Test accuracy with automated evaluations
- [Self-Learning](https://knobik.github.io/sql-agent/guides/self-learning/) - Automatic learning from errors
- [Events](https://knobik.github.io/sql-agent/reference/events/) - Event hooks for custom behavior
- [Agent Tools](https://knobik.github.io/sql-agent/reference/tools/) - All LLM tools with parameters and JSON schemas
- [Database Support](https://knobik.github.io/sql-agent/reference/database-support/) - MySQL, PostgreSQL, SQLite, SQL Server
- [Troubleshooting](https://knobik.github.io/sql-agent/troubleshooting/) - Common issues and solutions

Testing
-------

[](#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
------------

[](#contributing)

Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

License
-------

[](#license)

SQL Agent for Laravel is open-sourced software licensed under the [Apache-2.0 License](LICENSE).

###  Health Score

42

—

FairBetter than 89% of packages

Maintenance94

Actively maintained with recent releases

Popularity12

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

17

Last Release

84d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5526cc21c5910dfac44c0a253b2c93ab9080c0a78c172849a3a7690b0ec560b5?d=identicon)[knobik](/maintainers/knobik)

---

Top Contributors

[![knobik](https://avatars.githubusercontent.com/u/795254?v=4)](https://github.com/knobik "knobik (98 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (8 commits)")

---

Tags

laravelaisqleloquentAgentllmtext-to-sql

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/knobik-laravel-sql-agent/health.svg)

```
[![Health](https://phpackages.com/badges/knobik-laravel-sql-agent/health.svg)](https://phpackages.com/packages/knobik-laravel-sql-agent)
```

###  Alternatives

[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[baril/bonsai

An implementation of the Closure Tables pattern for Eloquent.

3593.5k](/packages/baril-bonsai)[toponepercent/baum

Baum is an implementation of the Nested Set pattern for Eloquent models.

3154.7k](/packages/toponepercent-baum)[eusonlito/laravel-database-cache

Cache Database Query results on Laravel Query Builder or Eloquent

194.2k](/packages/eusonlito-laravel-database-cache)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
