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.
SqlAgent can automatically learn from its mistakes and improve over time without any manual intervention. The agent maintains two dynamic knowledge systems that grow as it processes queries.
The agent's system prompt instructs it to follow a learning-oriented workflow:
The system prompt defines two complementary knowledge systems:
Knowledge (static, curated) — Table schemas, business rules, and manually authored query patterns. These come from your Knowledge Base files and are loaded via sql-agent:load-knowledge.
Learnings (dynamic, discovered) — Patterns the agent discovers through its own interactions. These include type gotchas, date formats, column quirks, and validated queries. The agent manages these automatically using two tools:
save_learningThe agent saves a learning when it discovers something important about the database — typically after recovering from an error or when a user corrects it. Examples from the system prompt:
After fixing a type error:
save_learning(
title="users.status is VARCHAR not INT",
description="Use status = 'active' not status = 1",
category="type_error"
)
After discovering a date format:
save_learning(
title="orders.created_at date handling",
description="Use DATE(created_at) for date comparisons, stored as datetime",
category="query_pattern"
)
After a user corrects the agent:
save_learning(
title="Soft deletes on users table",
description="Always filter WHERE deleted_at IS NULL unless counting deleted records",
category="schema_fix"
)
save_validated_queryAfter successfully answering a question, the agent saves the query as a reusable pattern. This populates the same query patterns table used by the Knowledge Base, so future searches can find proven SQL for similar questions.
The agent saves:
:::tip The system prompt instructs the agent to always save validated queries after successful execution. This means the agent's knowledge grows organically as it handles more questions — common queries get faster and more reliable over time. :::
Learnings are automatically categorized:
| Category | Description |
|---|---|
type_error |
Data type mismatches or casting issues |
schema_fix |
Incorrect schema assumptions (wrong table or column names) |
query_pattern |
Learned patterns for constructing queries |
data_quality |
Observations about data quality or anomalies |
business_logic |
Learned business rules or domain knowledge |
Export and import learnings to share them across environments or back them up:
# Export all learnings to JSON
php artisan sql-agent:export-learnings
# Export a specific category
php artisan sql-agent:export-learnings --category=schema_fix
# Import learnings from a file
php artisan sql-agent:import-learnings learnings.json
# Prune learnings older than 90 days
php artisan sql-agent:prune-learnings --days=90
# Remove only duplicates
php artisan sql-agent:prune-learnings --duplicates
# Preview what would be removed
php artisan sql-agent:prune-learnings --dry-run
The agent's behavior is driven by a Blade template at resources/prompts/system.blade.php. This template defines the workflow, tool usage instructions, SQL rules, and response guidelines that the LLM follows.
To customize it, publish the prompt to your application:
php artisan vendor:publish --tag=sql-agent-prompts
This copies the template to resources/views/vendor/sql-agent/prompts/system.blade.php. Your published version takes precedence over the package default — Laravel's view override mechanism handles this automatically.
The system prompt is a standard Blade template with access to config values and a $context variable containing the assembled knowledge. Common customizations include:
You are an e-commerce analytics assistant that helps the team understand sales trends and customer behavior.
## Important Rules
- Always convert total_amount from cents to dollars in results
- Use fiscal quarters (Q1 = Feb-Apr) instead of calendar quarters
- Exclude test orders (email ending in [@example](https://github.com/example).com) from all metrics
- When reporting revenue, always break down by currency
{{-- Keep the rest of the default template --}}
[@if](https://github.com/if)(config('sql-agent.learning.enabled', true))
## When to save_learning
...
[@endif](https://github.com/endif)
## Context
{!! $context !!}
:::note
The {!! $context !!} variable at the end of the template is required — it injects the assembled knowledge (table metadata, business rules, query patterns, and learnings) that the agent needs to write accurate SQL.
:::
The temperature setting in config/sql-agent.php controls how deterministic or creative the LLM's responses are:
'llm' => [
'temperature' => (float) env('SQL_AGENT_LLM_TEMPERATURE', 0.3),
],
| Temperature | Behavior |
|---|---|
0.0 |
Most deterministic — the agent produces concise, consistent answers with minimal variation between runs |
0.3–0.5 |
Balanced — slight variation in wording and analysis while staying focused on the question |
0.7–1.0 |
More creative — the agent may run additional queries, produce richer analysis, and provide more detailed explanations |
Lower temperatures work best for production environments where you want predictable, repeatable results. Higher temperatures can be useful during development or when you want the agent to explore the data more thoroughly and provide deeper insights.
:::caution
Higher temperatures increase token usage and response time since the agent may take more steps (additional SQL queries, longer explanations). They also increase the chance of hallucinations — the agent may generate incorrect SQL, reference non-existent columns, misinterpret query results, etc. Start with 0.0 or 0.3 and increase only if you need more exploratory behavior.
:::
To disable the self-learning feature entirely:
SQL_AGENT_LEARNING_ENABLED=false
This removes both save_learning and save_validated_query tools from the agent and hides the related instructions from the system prompt.
To keep manual learning (via the save_learning tool) but disable automatic error-based learning:
SQL_AGENT_AUTO_SAVE_ERRORS=false
How can I help you explore Laravel packages today?