Search by

ankitkaran99 / ai-query

ankitkaran99

A small, safe, natural-language query layer for Laravel — powered by Prism. Returns structured query specs, never executes generated code.

Package info

github.com/ankitkaran99/ai-query

pkg:composer/ankitkaran99/ai-query

Statistics

Installs: 6

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.0.2 2026-08-27 12:23 UTC

This package is auto-updated.

Last update: 2026-12-01 09:35:55 UTC


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 Queryable classes into app/AiQuery/ and they are registered automatically via Laravel's container.
  • Always-On Scoping: Every Queryable supports a scope(Builder $query) hook applied after all AI filters—ideal for tenant isolation, soft-delete rules, or role restrictions.
  • Explicit Display Formatting (prettyName): Each Queryable defines prettyName(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 into instructions.

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:

  1. Calls the target Queryable's prettyName($row) and inserts 'name' right after 'id' (if 'name' is not already a column).
  2. Replaces each loaded relation object with AiQuery::prettyNameFor($related) (using that related model's registered Queryable::prettyName()).
  3. Removes the corresponding *_id / BelongsTo foreign-key column when the relation's prettyName is present.
  4. 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