ankitkaran99 / ai-query
A small, safe, natural-language query layer for Laravel — powered by Prism. Returns structured query specs, never executes generated code.
Requires
- php: ^8.2
- illuminate/console: ^11.0|^12.0|^13.0
- illuminate/database: ^11.0|^12.0|^13.0
- illuminate/support: ^11.0|^12.0|^13.0
- prism-php/prism: ^0.100.0
Requires (Dev)
- orchestra/testbench: ^9.0|^10.0
- pestphp/pest: ^2.0|^3.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A small, safe, natural-language query layer for Laravel powered by Prism.
Instead of asking an LLM to write SQL or PHP and executing it, AI Query asks the model for a structured JSON query specification constrained to the models, columns, relations, and operators you explicitly allow. It then validates the spec and builds a standard Eloquent query.
Key Features
- Zero Generated SQL or Code Execution: The LLM only outputs a structured JSON spec (
target,filters,relation_filters,aggregate,aggregate_field), validated against your allowlists before Eloquent runs. - Auto-Discovered Queryables: Drop
Queryableclasses intoapp/AiQuery/and they are registered automatically via Laravel's container. - Always-On Scoping: Every
Queryablesupports ascope(Builder $query)hook applied after all AI filters—ideal for tenant isolation, soft-delete rules, or role restrictions. - Explicit Display Formatting (
prettyName): EachQueryabledefinesprettyName(Model $row)so result tables and AI summaries show human-readable names/titles instead of raw foreign-key IDs, without guessing or leaking unapproved columns. - Built-in Spec Caching & Token Tracking: Identical prompts (under the same schema fingerprint and instructions) hit the spec cache with zero LLM tokens spent for query planning.
- Provider-Agnostic via Prism: Switch between Anthropic, OpenAI, Gemini, etc. through config without changing application code.
Requirements
- PHP
^8.2 - Laravel
^11.0 | ^12.0 | ^13.0 prism-php/prism ^0.100.0
Installation
composer require ankitkaran99/ai-query
Publish the configuration file:
php artisan vendor:publish --tag=ai-query-config
Configure your Prism provider credentials and config/ai-query.php environment variables in .env:
AI_QUERY_PROVIDER=anthropic AI_QUERY_MODEL=claude-sonnet-4-6 AI_QUERY_MAX_ROWS=500 AI_QUERY_SUMMARIZE=true AI_QUERY_CACHE_ENABLED=true AI_QUERY_CACHE_TTL=3600 # AI_QUERY_CACHE_STORE=redis AI_QUERY_DISCOVERY_ENABLED=true
Defining Queryables
Create one class per askable model in app/AiQuery/ extending Scholar\AiQuery\Queryable:
<?php namespace App\AiQuery; use App\Models\FeeRoll; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Scholar\AiQuery\Queryable; class FeeRollQueryable extends Queryable { public function model(): string { return FeeRoll::class; } public function description(): string { return 'Student fee invoices, monthly dues, paid/balance amounts, and payment status.'; } public function columns(): ?array { return [ 'id', 'student_id', 'fee_type_id', 'billing_month', 'billing_year', 'amount', 'paid_amount', 'balance_amount', 'status', ]; } public function relations(): array { return [ 'student' => ['id', 'first_name', 'last_name'], 'feeType' => ['id', 'name', 'code'], ]; } public function scope(Builder $query): void { $query->where('school_id', tenant('id')); } public function prettyName(Model $row): ?string { $fee = ($row->relationLoaded('feeType') && $row->feeType) ? $row->feeType->name : 'Fee'; return "{$fee} ({$row->billing_month}/{$row->billing_year})"; } }
Queryable Methods
| Method | Purpose |
|---|---|
model(): string |
Required. Eloquent model class. |
key(): string |
Target key used in specs (defaults to snake_case plural of class name, e.g. FeeRollQueryable → fee_rolls). |
description(): string |
Short description folded into the LLM system prompt to help target selection. |
columns(): ?array |
Allowlisted columns for SELECT and filtering (null auto-resolves from $fillable / $visible). |
relations(): array |
Allowlisted relations mapped to allowed columns (null auto-resolves). Eager-loaded automatically on list queries. |
scope(Builder $query): void |
Mandatory query constraint applied last (cannot be overridden by AI output). |
prettyName(Model $row): ?string |
Explicit display label for this model when returned as a row or as a loaded relation. |
Fluent Registration (Alternative)
You can also register queryables manually (for example in AppServiceProvider::boot()):
use Scholar\AiQuery\Facades\AiQuery; AiQuery::register('students', Student::class) ->description('Enrolled students') ->columns(['id', 'first_name', 'last_name', 'status']) ->relation('class', ['id', 'name']) ->prettyName(fn ($row) => "{$row->first_name} {$row->last_name}") ->scope(fn ($query) => $query->where('status', 'active'));
Asking Questions
Call AiQuery::ask() with the user's natural-language prompt and optional trusted application-level instructions:
use Scholar\AiQuery\Facades\AiQuery; use Scholar\AiQuery\Exceptions\InvalidQuerySpecException; try { $result = AiQuery::ask( prompt: 'Which students have unpaid tuition fees this month?', instructions: 'Prefer the current academic session. Never expose other schools.', ); } catch (InvalidQuerySpecException $e) { // Handle malformed or disallowed query spec }
Security Note: Only pass developer-controlled text to
instructions. Never pass raw end-user input intoinstructions.
Working with AiQueryResult
$result->prompt; // Original prompt string $result->spec; // Validated query spec array $result->summary; // Natural-language summary (when summarize = true) $result->fromCachedSpec; // bool: true if spec came from cache $result->tokenUsage; // TokenUsage (promptTokens, completionTokens, totalTokens) // Aggregate queries (count, sum, avg) if ($result->isAggregate()) { $type = $result->aggregateType; // 'count' | 'sum' | 'avg' $value = $result->aggregateValue; // int|float|null } // List queries $rows = $result->results; // Illuminate\Support\Collection of Eloquent models
Formatting Results with prettyName()
On list queries, QueryBuilder eager-loads all allowlisted relations() (scoped strictly to their allowed columns). Use AiQuery::formatResults() to convert Eloquent models into display-ready arrays:
$formatted = AiQuery::formatResults( $result->results, $result->spec['target'] ?? null, );
What formatResults() does:
- Calls the target
Queryable'sprettyName($row)and inserts'name'right after'id'(if'name'is not already a column). - Replaces each loaded relation object with
AiQuery::prettyNameFor($related)(using that related model's registeredQueryable::prettyName()). - Removes the corresponding
*_id/BelongsToforeign-key column when the relation'sprettyNameis present. - Leaves any relation without an explicit
prettyName()untouched—never guessing or exposing unapproved columns.
Caching
Specs are cached using a SHA-1 fingerprint of your registered queryables (key, columns, relations), prompt, and instructions. Changing a Queryable's columns or relations automatically invalidates old cached specs.
To flush the AI Query cache manually (requires a taggable cache store such as redis, memcached, or array):
php artisan ai-query:clear-cache
Running Tests
composer test # or vendor/bin/pest
License
MIT