PHPackages                             btx/sql-ai-query - 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. btx/sql-ai-query

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

btx/sql-ai-query
================

PHP package to generate SQL queries using AI based on database schema with conversation context.

1.0.1(1mo ago)00MITPHPPHP ^8.1

Since Mar 28Pushed 1mo agoCompare

[ Source](https://github.com/bachtiarpanjaitan/SqlAiQuery)[ Packagist](https://packagist.org/packages/btx/sql-ai-query)[ RSS](/packages/btx-sql-ai-query/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (3)Versions (3)Used By (0)

sql-ai-query
============

[](#sql-ai-query)

 [![Total Downloads](https://camo.githubusercontent.com/dc9a08ffc9f67550fde81f0806a1cc1bcaef8489f58aef10b26940d1a9c282e2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6274782f73716c2d61692d71756572793f7374796c653d666c61742d737175617265)](https://packagist.org/packages/btx/sql-ai-query?) [![Latest Stable Version](https://camo.githubusercontent.com/007b918ac2cd5155671dec644b19ef93272eabc28b13203ddb3550c5dc7b8b53/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6274782f73716c2d61692d71756572793f7374796c653d666c61742d737175617265)](https://packagist.org/packages/btx/sql-ai-query) [![License](https://camo.githubusercontent.com/f06f035dfd4801133bd8274aedcaddd93a3883047e3b7b27857d8ab89d5cdc30/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6274782f73716c2d61692d71756572793f7374796c653d666c61742d737175617265)](https://packagist.org/packages/btx/sql-ai-query)

&gt; Generate SQL queries from natural language using \*\*ChatGPT\*\* or \*\*Grok\*\*, with full conversation context support. ---

Features
--------

[](#features)

- 🤖 **Multi-provider** — OpenAI (GPT-4o, GPT-4, GPT-3.5-turbo), xAI Grok (grok-3) **and** Custom Provider via the same `openai-php/client` package
- 📝 **Conversation context** — every exchange is saved so the AI understands follow-up questions
- 🗄️ **Auto schema extraction** — introspect MySQL, PostgreSQL, or SQLite via PDO, or supply a PHP array / raw DDL
- 🧱 **Fluent builder API** — compose your generator in one readable chain
- 📦 **PSR-4 autoloaded**, PHP 8.1+

---

Installation
------------

[](#installation)

```
composer require btx/sql-ai-query
```

---

Quick Start
-----------

[](#quick-start)

```
use Btx\SqlAiQuery\SqlAiQuery;

$result = SqlAiQuery::make()
    ->useOpenAI(apiKey: 'sk-...')          // or ->useGrok('xai-...')
    ->withSchemaFromPdo($pdo)              // auto-introspect live DB
    ->generate('Show me the 10 most recent orders with the customer name');

echo $result->getSql();
// SELECT o.id, c.name AS customer_name, o.total_amount, o.created_at
// FROM orders o
// JOIN customers c ON c.id = o.customer_id
// ORDER BY o.created_at DESC
// LIMIT 10;
```

---

Configuration
-------------

[](#configuration)

### Choosing a Provider

[](#choosing-a-provider)

```
// ChatGPT (default model: gpt-4o)
->useOpenAI(apiKey: 'sk-...', model: 'gpt-4o', temperature: 0.2, maxTokens: 2048)

// Grok (default model: grok-3)
->useGrok(apiKey: 'xai-...', model: 'grok-3', temperature: 0.2, maxTokens: 2048)

// Another AI Provider
->useCustomAi(apiKey: '...', model: 'gpt-4o', temperature: 0.2, maxTokens: 2048)

// Custom provider (implement AIProviderInterface)
->useProvider(new MyCustomProvider(...))
```

### Providing the Schema

[](#providing-the-schema)

```
// Option A — Auto-introspect from a live PDO connection
->withSchemaFromPdo($pdo)
->withSchemaFromPdo($pdo, 'my_database')  // specify database name

// Option B — PHP array
->withSchemaFromArray([
    'users' => [
        'id'    => ['type' => 'BIGINT', 'nullable' => false, 'key' => 'PRI'],
        'email' => ['type' => 'VARCHAR(255)', 'nullable' => false],
    ],
])

// Option C — Raw DDL string
->withSchemaFromDdl('CREATE TABLE users (id INT PRIMARY KEY, ...)')

// Option D — Pre-formatted description string
->withSchema('TABLE users: id (BIGINT PRI), email (VARCHAR 255) ...')
```

---

Multi-turn Conversations
------------------------

[](#multi-turn-conversations)

Every `generate()` call returns a `QueryResult` that carries a `contextId`.
Pass it back to continue the same conversation:

```
$generator = SqlAiQuery::make()
    ->useOpenAI('sk-...')
    ->withSchemaFromPdo($pdo)
    ->withStoragePath('/var/app/contexts')  // where to persist contexts
    ->build();

// First turn
$r1 = $generator->generate('Get all customers registered in the last 30 days');
$contextId = $r1->getContextId();

// Follow-up — AI remembers the previous query
$r2 = $generator->followUp('Now add the total number of orders for each', $contextId);

// Refine further
$r3 = $generator->followUp('Only keep those with more than 3 orders', $contextId);
```

Contexts are persisted as JSON files so they survive between requests / CLI runs.

---

API Reference
-------------

[](#api-reference)

### `SqlAiQuery` (Builder)

[](#sqlaiquery-builder)

MethodDescription`::make()`Create a new builder instance`->useOpenAI($key, $model?, $temp?, $maxTokens?)`Configure ChatGPT provider`->useGrok($key, $model?, $temp?, $maxTokens?)`Configure Grok provider`->useProvider($provider)`Inject a custom `AIProviderInterface``->withSchemaFromPdo($pdo, $db?)`Auto-introspect schema via PDO`->withSchemaFromArray($array)`Schema from PHP array`->withSchemaFromDdl($ddl)`Schema from DDL string`->withSchema($string)`Schema from formatted string`->withStoragePath($path)`Directory for context JSON files`->withMaxContextMessages($n)`Max messages to keep per context (default 20)`->build()`Return a `QueryGenerator` instance`->generate($request, $contextId?)`Build + generate in one call### `QueryGenerator`

[](#querygenerator)

MethodDescription`generate($request, $contextId?)`Generate SQL; starts fresh if `$contextId` is null`followUp($request, $contextId)`Continue an existing conversation`fresh($request)`Force a brand-new conversation`getContextStore()`Access the `ContextStore``deleteContext($contextId)`Delete a stored context### `QueryResult`

[](#queryresult)

MethodDescription`getSql()`Extracted SQL query (strips Markdown fences)`getRawResponse()`Full unprocessed AI response`getContextId()`Context ID for continuing the conversation### `ConversationContext`

[](#conversationcontext)

MethodDescription`addSystem($content)`Set the system prompt`addUser($content)`Add a user message`addAssistant($content)`Add an assistant message`getMessages()`All messages as array`trimToLastN($n)`Keep only the N most recent non-system messages`toJson()` / `fromJson()`Serialize / deserialize### `ContextStore`

[](#contextstore)

MethodDescription`save($context)`Persist a context to disk`load($contextId)`Load a context from disk`exists($contextId)`Check if a context exists`delete($contextId)`Remove a context`list()`List all stored context IDs---

Supported PDO Drivers
---------------------

[](#supported-pdo-drivers)

DriverNotes`mysql`Full column metadata + foreign keys via `information_schema``pgsql`Tables and columns from `information_schema``sqlite`Tables and columns via `PRAGMA table_info`---

Project Structure
-----------------

[](#project-structure)

```
src/
├── Contracts/
│   └── AIProviderInterface.php   # Provider contract
├── Context/
│   ├── ConversationContext.php   # Manages message history
│   └── ContextStore.php          # File-based persistence
├── Exceptions/
│   ├── SqlAiQueryException.php
│   └── ProviderException.php
├── Providers/
│   ├── OpenAIProvider.php        # ChatGPT adapter
│   └── GrokProvider.php          # Grok adapter (OpenAI-compatible)
├── Schema/
│   └── SchemaExtractor.php       # PDO / array / DDL → formatted schema
├── QueryGenerator.php            # Core engine
├── QueryResult.php               # Response wrapper + SQL extractor
└── SqlAiQuery.php                # Fluent builder (main entry-point)

```

---

License
-------

[](#license)

MIT

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance90

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

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

2

Last Release

46d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4de1cf09f9258a3cce8f395da97e83234bcf33ae3cd051ca8cde8a890bbb17e0?d=identicon)[bachtiarpanjaitan](/maintainers/bachtiarpanjaitan)

---

Top Contributors

[![bachtiarpanjaitan](https://avatars.githubusercontent.com/u/20755907?v=4)](https://github.com/bachtiarpanjaitan "bachtiarpanjaitan (2 commits)")

---

Tags

databaseaisqlqueryopenaiChatGptgrok

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/btx-sql-ai-query/health.svg)

```
[![Health](https://phpackages.com/badges/btx-sql-ai-query/health.svg)](https://phpackages.com/packages/btx-sql-ai-query)
```

###  Alternatives

[illuminated/db-profiler

Database Profiler for Laravel Web and Console Applications.

168237.4k](/packages/illuminated-db-profiler)[opis/database

A database abstraction layer over PDO, that provides a powerful and intuitive query builder, bundled with an easy to use schema builder

10184.2k3](/packages/opis-database)

PHPackages © 2026

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