PHPackages                             emon/larabot-ai - 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. emon/larabot-ai

ActiveLibrary[Database &amp; ORM](/categories/database)

emon/larabot-ai
===============

Conversational AI database assistant for Laravel with Schema-RAG and NL→SQL capabilities

v1.3.0(6mo ago)421MITPHPPHP ^8.1|^8.2|^8.3

Since Nov 9Pushed 6mo agoCompare

[ Source](https://github.com/MdIshtiaque/larabot-ai)[ Packagist](https://packagist.org/packages/emon/larabot-ai)[ RSS](/packages/emon-larabot-ai/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (8)Versions (6)Used By (0)

LaraBot AI
==========

[](#larabot-ai)

[![Latest Version](https://camo.githubusercontent.com/9d9bd6b962f0aa868fb783591eb8e4d98f6c221e392f7ae3e073e7a36f4bae5a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f656d6f6e2f6c617261626f742d61692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/emon/larabot-ai)[![Total Downloads](https://camo.githubusercontent.com/4195453d2a695375d33674e979353ee58ef310f505f8ccf3410e67020e9a189d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f656d6f6e2f6c617261626f742d61692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/emon/larabot-ai)[![License](https://camo.githubusercontent.com/98129e4c2a1bf0650bd4d82c401d185660beda09eb34eb7f7510f53e3f673877/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f4d644973687469617175652f6c617261626f742d61692e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/7b9aeb7935f4ec7c8ec3a7091c148e173106a5eba76cee8f51f31935729f15ea/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f656d6f6e2f6c617261626f742d61693f7374796c653d666c61742d737175617265)](composer.json)

Conversational AI database assistant for Laravel that combines **Schema-RAG** and **NL→SQL** capabilities using Google Gemini AI.

🚀 Features
----------

[](#-features)

- 🤖 **Natural Language to SQL** - Ask questions about your database in plain English
- 🎨 **HTML Visualizations** - AI generates beautiful charts, tables, and cards automatically
- 📚 **Documentation RAG** - Retrieval Augmented Generation from your project docs
- 🔍 **Semantic Schema Search** - AI embeddings for intelligent table discovery
- 🔐 **Secure by Design** - Read-only DB connection + SQL injection prevention
- ⚡ **Auto-Discovery** - Automatically learns your database structure
- 📊 **Query Logging** - Track all queries with performance metrics
- 🛡️ **Rate Limiting** - Built-in protection against abuse
- 🎯 **Column-Aware** - Matches queries to specific columns
- 🔗 **Relationship Discovery** - Automatically follows foreign keys

📋 Requirements
--------------

[](#-requirements)

- PHP 8.1 or higher
- Laravel 10.x or 11.x
- MySQL 5.7+ / MariaDB 10.3+
- Google Gemini API key ([Get free key](https://aistudio.google.com/))

📦 Installation
--------------

[](#-installation)

### Step 1: Install via Composer

[](#step-1-install-via-composer)

```
composer require emon/larabot-ai
```

### Step 2: Publish Configuration

[](#step-2-publish-configuration)

```
php artisan vendor:publish --tag=larabot-config
```

### Step 3: Publish Migrations

[](#step-3-publish-migrations)

```
php artisan vendor:publish --tag=larabot-migrations
```

### Step 4: Configure Environment

[](#step-4-configure-environment)

Add to your `.env` file:

```
GEMINI_API_KEY=your_api_key_here
GEMINI_EMBED_MODEL=models/text-embedding-004
GEMINI_LLM_MODEL=models/gemini-2.0-flash-exp
```

Get your free API key from [Google AI Studio](https://aistudio.google.com/).

### Step 5: Add Read-Only Database Connection

[](#step-5-add-read-only-database-connection)

Add this to `config/database.php`:

```
'mysql_readonly' => [
    'driver' => 'mysql',
    'url' => env('DB_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'laravel'),
    'username' => env('DB_READONLY_USERNAME', env('DB_USERNAME')),
    'password' => env('DB_READONLY_PASSWORD', env('DB_PASSWORD')),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
],
```

**Security Tip:** Create a read-only MySQL user:

```
CREATE USER 'readonly'@'localhost' IDENTIFIED BY 'password';
GRANT SELECT ON your_database.* TO 'readonly'@'localhost';
FLUSH PRIVILEGES;
```

Then add to `.env`:

```
DB_READONLY_USERNAME=readonly
DB_READONLY_PASSWORD=password
```

### Step 6: Run Migrations

[](#step-6-run-migrations)

```
php artisan migrate
```

### Step 7: Embed Your Database Schema

[](#step-7-embed-your-database-schema)

```
php artisan schema:embed
```

**Interactive Selection:** The command will display all available tables and let you select which ones to embed:

- Enter numbers separated by comma: `1,3,5`
- Use ranges: `1-5` or combine: `1,3,5-8`
- Type `all` to select all tables
- Press Enter to cancel

This command will:

- Discover all tables in your database
- Extract column information and relationships
- Generate AI embeddings for semantic search
- Store everything for lightning-fast queries

**Time:** ~1 second per table (API rate limits: 60 requests/minute)

**Example:**

```
Found 20 tables in the database:
  [1] users
  [2] posts
  [3] orders
  ...

Your selection: 1-3,5

Selected tables:
  ✓ users
  ✓ posts
  ✓ orders
  ✓ products

Embedding 4 table(s)...
 4/4 [============================] 100%
✅ Schema embedding completed successfully!

```

### Step 8 (Optional): Embed Documentation

[](#step-8-optional-embed-documentation)

If you have markdown documentation in a `docs/` directory:

```
php artisan docs:embed
```

🎯 Usage
-------

[](#-usage)

### API Endpoints

[](#api-endpoints)

The package automatically registers these routes:

```
POST   /api/bot/ask      - Ask a question
GET    /api/bot/history  - Get query history (requires auth)
GET    /api/bot/stats    - Get statistics

```

### Ask Questions

[](#ask-questions)

```
curl -X POST http://localhost:8000/api/bot/ask \
  -H "Content-Type: application/json" \
  -d '{"query": "How many users are active?"}'
```

**Response:**

```
{
  "success": true,
  "data": {
    "answer": "There are 150 active users in the system.",
    "html": "Beautiful HTML card",
    "visualization_type": "stats_card",
    "insights": ["Active user count has grown by 10% this month"],
    "intent": "sql",
    "response_time_ms": 1250,
    "sql": "SELECT COUNT(*) FROM users WHERE is_active = 1;"
  },
  "error": null
}
```

### 🎨 HTML Visualizations (New in v1.2.0)

[](#-html-visualizations-new-in-v120)

The bot now intelligently generates **beautiful HTML/CSS visualizations** along with natural language answers!

**Key Features:**

- ✅ Natural language answer (always included)
- ✅ Beautiful HTML visualization (when helpful)
- ✅ Self-contained (no external dependencies)
- ✅ Multiple types: stat cards, tables, bar charts, timelines, comparisons, and more

**Example:**

```
// Render the response
document.getElementById('answer').textContent = result.data.answer;

if (result.data.html) {
  document.getElementById('visualization').innerHTML = result.data.html;
}
```

**Visualization Types:**

- `stats_card` - Single values (counts, sums)
- `table` - Tabular data (5-20 rows)
- `bar_chart` - Categories with numbers
- `list` - Short lists (2-5 items)
- `comparison` - Side-by-side comparisons
- `metric_grid` - Dashboard-style metrics
- `timeline` - Date-ordered events
- `text` - Plain text (no visualization)

**Learn More:**

- 📖 [HTML Visualization Feature Guide](HTML_VISUALIZATION_FEATURE.md)
- 📝 [Real Examples](HTML_VISUALIZATION_EXAMPLES.md)
- 🚀 [What's New in v1.2.0](WHATS_NEW_HTML_VISUALIZATIONS.md)

### Example Queries

[](#example-queries)

**SQL Queries:**

```
- "How many orders were placed today?"
- "Show me the top 10 products by sales"
- "List all users who joined this month"
- "What's the average order value?"
- "Find customers with more than 5 orders"

```

**Documentation Queries:**

```
- "How do I set up authentication?"
- "Explain the payment flow"
- "What is the API rate limit?"

```

### Programmatic Usage

[](#programmatic-usage)

```
use Emon\LarabotAi\Services\HybridBotService;

class MyController
{
    public function __construct(private HybridBotService $bot) {}

    public function askQuestion(Request $request)
    {
        $result = $this->bot->ask(
            query: $request->input('question'),
            userId: auth()->id()
        );

        return response()->json($result);
    }
}
```

⚙️ Configuration
----------------

[](#️-configuration)

### Authentication

[](#authentication)

By default, bot routes are **publicly accessible**. To require authentication:

**Option 1: Environment Variables (Recommended)**

Add to `.env`:

```
GEMINI_REQUIRE_AUTH=true
GEMINI_AUTH_GUARD=sanctum  # or 'api', 'web'
```

**Option 2: Config File**

Edit `config/gemini.php`:

```
'require_auth' => true,
'auth_guard' => 'sanctum', // or 'api', 'web', 'passport'
```

**Option 3: Custom Middleware (Advanced)**

Edit `config/gemini.php` and customize the middleware array:

```
'route_middleware' => [
    'api',
    'auth:sanctum',           // Add authentication
    'bot.rate-limit',
    'verified',               // Add email verification
    'throttle:60,1',          // Additional rate limiting
],
```

**Testing Authenticated Requests:**

```
# With Sanctum token
curl -X POST http://localhost:8000/api/bot/ask \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{"query": "How many users?"}'
```

**Common Auth Guards:**

- `sanctum` - Laravel Sanctum (SPA/mobile apps)
- `api` - Token-based authentication
- `web` - Session-based authentication
- `passport` - Laravel Passport OAuth2

### Rate Limiting

[](#rate-limiting)

Default: 10 requests per minute per user/IP

To customize, modify `src/Http/Middleware/BotRateLimitMiddleware.php`:

```
$executed = RateLimiter::attempt("bot-query:{$userId}", 20, fn () => true);
```

### Query Length

[](#query-length)

Default: 500 characters max

Change in middleware:

```
if (strlen($query) > 1000) { // Increased to 1000
    // ...
}
```

### Gemini Models

[](#gemini-models)

In `config/gemini.php`:

```
'embed_model' => env('GEMINI_EMBED_MODEL', 'models/text-embedding-004'),
'llm_model' => env('GEMINI_LLM_MODEL', 'models/gemini-2.0-flash-exp'),
```

🔒 Security Features
-------------------

[](#-security-features)

✅ **Read-Only Database** - Queries execute on separate read-only connection
✅ **SQL Injection Prevention** - Blocks dangerous SQL patterns
✅ **No Mutations** - DROP, DELETE, UPDATE, INSERT automatically blocked
✅ **Optional Authentication** - Support for Sanctum, Passport, and custom guards
✅ **Rate Limiting** - Prevents API abuse (10 req/min default)
✅ **Query Validation** - Validates generated SQL before execution
✅ **Audit Logging** - All queries logged with user ID and timestamps

🧪 How It Works
--------------

[](#-how-it-works)

### Architecture

[](#architecture)

```
User Query → Intent Detection → Hybrid Bot Service
                                       ↓
                         ┌─────────────┴─────────────┐
                         ↓                           ↓
                   SQL Intent                    RAG Intent
                         ↓                           ↓
              Schema Retrieval              Knowledge Retrieval
            (Semantic Search + FKs)       (Document Embeddings)
                         ↓                           ↓
               SQL Generation                  Context Assembly
            (Gemini LLM + Rules)                     ↓
                         ↓                    Answer Generation
                   SQL Validation                 (Gemini LLM)
                         ↓                           ↓
                  Execute Query                      │
                         ↓                           │
                         └───────────┬───────────────┘
                                     ↓
                              Format Response
                                     ↓
                              Query Logging
                                     ↓
                            Return to User

```

### Key Components

[](#key-components)

1. **Schema Embeddings** - Vector representations of your database tables
2. **Semantic Search** - Finds relevant tables using AI similarity matching
3. **Relationship Discovery** - Automatically includes related tables via foreign keys
4. **Column-Aware Matching** - Matches query terms to specific columns
5. **SQL Generation** - Gemini LLM generates optimized SQL queries
6. **SQL Validation** - Multi-layer security checks before execution

📊 Query Logging
---------------

[](#-query-logging)

All queries are logged to `query_logs` table:

```
DB::table('query_logs')
    ->where('user_id', auth()->id())
    ->orderBy('created_at', 'desc')
    ->get();
```

Fields: `query`, `intent`, `generated_sql`, `retrieved_tables`, `response_time_ms`, `success`, `error_message`

🔧 Maintenance
-------------

[](#-maintenance)

### Re-embed Schema After Changes

[](#re-embed-schema-after-changes)

Run this after migrations or schema changes:

```
php artisan schema:embed
```

**Tip:** You can selectively re-embed only the tables that changed by using the interactive selection.

### Update Documentation

[](#update-documentation)

After updating docs:

```
php artisan docs:embed
```

🐛 Troubleshooting
-----------------

[](#-troubleshooting)

### "403 Forbidden" from Gemini API

[](#403-forbidden-from-gemini-api)

**Solution:** Remove API key restrictions in [Google AI Studio](https://aistudio.google.com/).

### "429 Too Many Requests"

[](#429-too-many-requests)

**Solution:** Hitting free tier quota limit. Wait or upgrade plan.

### "Table X is not in allowed list"

[](#table-x-is-not-in-allowed-list)

**Solution:** Schema not embedded. Run `php artisan schema:embed` and select the tables you need to embed. You can use `all` to embed all tables or select specific ones.

### SQL Validation Errors

[](#sql-validation-errors)

**Solution:** Generated SQL contains dangerous operations or syntax errors. Check query logs.

📚 Documentation
---------------

[](#-documentation)

- [Installation Guide](INSTALLATION_GUIDE.md) - Step-by-step setup
- [Authentication Guide](AUTHENTICATION.md) - Secure your bot routes
- [Package Summary](PACKAGE_SUMMARY.md) - Technical architecture
- [HTML Visualizations](HTML_VISUALIZATION_FEATURE.md) - Complete guide to visualizations (v1.2.0+)
- [Visualization Examples](HTML_VISUALIZATION_EXAMPLES.md) - Real-world examples
- [What's New in v1.2.0](WHATS_NEW_HTML_VISUALIZATIONS.md) - Latest features

🤝 Contributing
--------------

[](#-contributing)

Contributions welcome! Please:

1. Fork the repository
2. Create a feature branch
3. Add tests for new features
4. Submit a pull request

📄 License
---------

[](#-license)

MIT License - see [LICENSE](LICENSE) file for details.

🙏 Credits
---------

[](#-credits)

Built with:

- [Laravel](https://laravel.com/)
- [Google Gemini AI](https://deepmind.google/technologies/gemini/)
- [GuzzleHTTP](https://docs.guzzlephp.org/)

💬 Support
---------

[](#-support)

- **Issues:** [GitHub Issues](https://github.com/MdIshtiaque/larabot-ai/issues)
- **Discussions:** [GitHub Discussions](https://github.com/MdIshtiaque/larabot-ai/discussions)

🌟 Star History
--------------

[](#-star-history)

If this package helped you, please star it on GitHub! ⭐

---

**Made with ❤️ for the Laravel community**

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance68

Regular maintenance activity

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

5

Last Release

188d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e572ab1f8c682b386d7643e89b3f959010a26ca1dadeb4757ffbb6dfad6b905c?d=identicon)[MdIshtiaque](/maintainers/MdIshtiaque)

---

Top Contributors

[![MdIshtiaque](https://avatars.githubusercontent.com/u/88388417?v=4)](https://github.com/MdIshtiaque "MdIshtiaque (13 commits)")

---

Tags

laraveldatabaseaisqlquery builderbotGeminichatbotnatural-languageragconversational-aiassistant

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/emon-larabot-ai/health.svg)

```
[![Health](https://phpackages.com/badges/emon-larabot-ai/health.svg)](https://phpackages.com/packages/emon-larabot-ai)
```

###  Alternatives

[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[torchlight/torchlight-laravel

A Laravel Client for Torchlight, the syntax highlighting API.

120452.8k11](/packages/torchlight-torchlight-laravel)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[toponepercent/baum

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

3154.7k](/packages/toponepercent-baum)[ntanduy/cloudflare-d1-database

Easy configuration and setup for D1 Database connections in Laravel.

215.4k](/packages/ntanduy-cloudflare-d1-database)[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)
