MBS Mohammed Baobaid
All projects
Project
Public release Open Source Software Created 20 May 2026

ModelMind AI Chat Package

An academic-style case study of a Laravel package that embeds model-aware, secure, and extensible AI assistance into data-rich web applications.

ModelMind is a reusable Laravel package published as mbs047/model-mind. The project studies a practical software engineering problem: how can a Laravel application provide an AI assistant that understands approved application data, speaks with users in natural language, produces safe application links, preserves useful memory, and remains configurable enough to install across unrelated systems?

Laravel 11-13 PHP 8.3+ Blade Tailwind CSS Eloquent Laravel Queues OpenAI Responses API Anthropic / Gemini / Ollama Drivers Composer Package Orchestra Testbench PHPUnit GitHub Actions Packagist
Narrated walkthrough

This audio is not a word-for-word copy of the case below. You can read the written case while listening to me explain the project in more detail.

0:00 / 0:00
Speed
ModelMind AI Chat Package project preview
mbs047/model-mind Package
v1.0.15 Latest release
11-13 Laravel support

Role

Package author, Laravel systems designer, AI product engineer, documentation writer, and open-source maintainer

Outcome

The work produced a Composer-installable package with Laravel auto-discovery, Blade and public asset rendering, a headless API, model-aware context retrieval, route actions, source citations, multilingual behavior, provider drivers, learning memory, queueable background processing, analytics, tests, documentation, Packagist metadata, GitHub release workflow, and a Market Lane Store demo for applied validation.

The Challenge

The technical challenge was to design an AI assistant that is more advanced than a chat popup but safer than a free-form database agent. The package needed to balance competing requirements: developer ergonomics, model governance, prompt size, response latency, route safety, UI customization, multilingual usage, session continuity, package portability, and the security expectations of admin panels, SaaS products, storefronts, support portals, and documentation sites.

The Approach

I treated ModelMind as a package architecture problem rather than a single UI feature. The solution separates the system into explicit layers: installation and publishing, context discovery, retrieval ranking, prompt construction, provider drivers, route-action resolution, source citation extraction, memory and learning, analytics, background jobs, Blade rendering, public assets, and headless API contracts. Each layer has configuration defaults, extension points, and tests so the package can be installed quickly while still supporting advanced Laravel applications.

How it works

Research problem and motivation

The central problem behind ModelMind is a recurring pattern in modern web applications: teams want an AI assistant that can answer questions about application data, but they do not want to expose the database directly, invent unsafe links, lose conversation history, or rebuild the same chat infrastructure for every product.

From an academic software engineering perspective, the project can be framed as a problem of controlled context mediation. The assistant needs access to domain data, but that access must pass through explicit configuration, authorization, retrieval limits, sensitive-field filtering, and prompt policies. ModelMind was built to study that middle layer between a generic language model and a Laravel application's structured data.

ModelMind package cover artwork for a Laravel AI assistant
ModelMind cover artwork showing the package brand and core promise: secure model-aware chat for Laravel applications.

Design objectives and evaluation criteria

The package was evaluated against several practical design objectives. First, installation should feel familiar to Laravel developers: Composer, package auto-discovery, published config, migrations, and Blade directives. Second, the assistant should be safe by default: no automatic access to arbitrary models, no hidden columns, no credentials, no unapproved route generation, and no unrestricted database querying.

Third, the package should support multiple implementation paths. A small app can use the default Blade modal and after_response background work. A larger SaaS product can use the headless API, queue workers, tenant scoping, policies, custom provider drivers, and a fully custom front end. This was an intentional design choice: the package should be simple at the surface and academically interesting beneath it.

Technology alternatives considered

There were several possible ways to implement the idea. One option was an app-specific controller and Blade component. That would be fast to build but difficult to reuse. Another option was a hosted AI service that connects to application data through external APIs. That could scale as a SaaS product but would reduce developer control and introduce data governance concerns. A third option was a package that runs inside the Laravel application and uses Laravel's own models, routes, policies, queues, and views.

ModelMind follows the third approach. It stays close to Laravel's native abstractions: service providers, routes, middleware, Eloquent, named routes, policies, queues, events, Blade, public assets, Artisan commands, and configuration files. This makes the assistant feel like part of the host application rather than a separate black box.

Package architecture

The architecture separates responsibilities into small package services. The service provider registers configuration, routes, views, migrations, commands, rate limiters, Blade directives, and the provider manager. The controller handles request validation, session resolution, provider calls, action extraction, citation extraction, and response payloads. Background jobs process non-critical work after the response.

The support layer then handles specialized concerns: context discovery, sensitive-column filtering, model context building, authorization, retrieval normalization, route-action resolution, source citation extraction, prompt construction, provider drivers, learning memory, analytics, view rendering, page-context sanitization, and database table naming. This modular shape makes the package easier to reason about and easier to extend.

Data governance and model-aware context

The most important safety decision is that ModelMind does not read the entire application. Developers must explicitly enable models in config/model-mind.php. Each model can define a label, description, columns, include and exclude lists, relations, limits, sorting, source labels, authorization rules, and route actions.

For deeper domain control, the HasModelMindContext trait lets an Eloquent model define its own AI-facing representation. This keeps domain-specific decisions near the model itself. For example, a product can expose storefront fields and a public product route, while an order can scope records to the current user or tenant. The package therefore treats context as governed data, not as a raw export.

Retrieval and multilingual matching

A naive assistant would place every enabled row into the prompt. That approach quickly becomes slow, expensive, and noisy. ModelMind instead combines static context with question-aware retrieval. It can weight columns such as SKU, name, title, category, and description; normalize multilingual text; tolerate fuzzy spelling differences; optionally use Laravel Scout; and optionally delegate to a vector searcher.

This design allows the assistant to answer questions about records outside the small static context window. It is especially useful for storefronts and admin panels where the relevant record may not be among the most recently updated rows. Multilingual normalization also supports users who ask in one language while the database stores names and descriptions in another.

Prompt policy, citations, and answer trust

The prompt design separates instructions from data. ModelMind tells the provider to answer only from enabled application context and optional page context, to treat model text as data rather than instructions, and to use the configured fallback when context is insufficient. This reduces the chance that stored content, product descriptions, or comments behave like hidden prompts.

Source citations add a trust layer. When an answer uses enabled model records, the assistant can emit internal citation tokens. The package converts those tokens into source cards showing the model label, record label, source key, cited columns, and optional route button. This makes answers easier to audit and easier to debug when a developer wants to know why a response was generated.

Route actions as safe application affordances

ModelMind treats links as application affordances, not arbitrary AI output. Developers register approved named routes and parameter mappings, such as products.show with ['product' => 'id']. The assistant may request a route action, but the package resolves it only if the key, model, route, parameters, and authorization checks are valid.

This method gives the user a useful next step, such as View Samsung Galaxy S24 Ultra, without allowing the model to invent URLs. The action label can be static, read from a configured column, or built from a label template. That small design detail makes the assistant feel integrated into the application while preserving route safety.

User interface and integration surfaces

The default interface is a Blade and Tailwind-friendly modal with configurable brand mark, title, subtitle, placeholder, default questions, light and dark themes, launcher position, width, offset, and z-index. The JavaScript and CSS are public assets, so teams can publish and customize them through a familiar asset workflow.

The UI is intentionally not the only integration path. A Laravel app can render @modelMind for the full widget, split styles, modal, and scripts across a layout, publish the modal view, replace the public assets, or skip Blade entirely and use the headless JSON API. This supports a range of clients: Blade apps, Livewire-heavy apps, Inertia apps, React/Vue clients, admin panels, and mobile front ends.

Memory, learning, and lifecycle control

ModelMind stores sessions and messages so the assistant can preserve conversational continuity. Developers can configure recent prompt messages, browser message restoration, message character limits, summary character limits, and MODEL_MIND_SESSION_LIFETIME_MINUTES so stale conversations reset after a chosen period.

The learning layer records useful assistant answers, liked answers, and manually fed texts, while blocking common secrets such as API keys, tokens, passwords, and private keys. In the latest architecture, learning and conversation compaction are dispatched through background jobs. This keeps the user-facing chat response faster while still letting the assistant improve its future context.

Performance, streaming, and queues

Performance is handled at several levels. Prompt size is controlled through context limits, field limits, row limits, output-token limits, cached context, and retrieval. Streaming responses improve perceived latency by sending deltas while the provider is still generating. Provider timeouts and connection timeouts prevent the UI from waiting indefinitely.

Queueable background work addresses a different part of the performance problem. Analytics writes, memory learning, liked-answer learning, feedback analytics, action-click analytics, and summary compaction do not need to block the HTTP response. ModelMind supports sync, after_response, and queue modes so small projects can stay simple while larger applications can run real queue workers.

Provider abstraction and extensibility

OpenAI is the default provider, but ModelMind does not lock the architecture to one AI backend. The provider manager can resolve OpenAI, Anthropic, Gemini, Ollama, or a custom provider class. A streaming provider contract supports live response deltas when the backend supports them.

This abstraction matters because AI infrastructure changes quickly. A package should not force a Laravel application to rewrite its controller, modal, session logic, route actions, citations, and analytics just because the preferred model provider changes. ModelMind keeps the provider as a replaceable component behind a stable request and response data contract.

Authorization and multi-tenant readiness

AI assistants become risky when they ignore the current user. ModelMind includes user-aware context, guard configuration, role and permission signals, tenant scoping, model-level authorization, Gate and policy checks, and callbacks for custom access rules. These features are important for admin panels, SaaS platforms, customer portals, and support tools.

The package also applies authorization to route actions. Even if a response mentions a record, the action button should not appear unless the current user is allowed to access that route target. This keeps generated links aligned with Laravel's own security model.

Testing, documentation, and release engineering

The package includes Orchestra Testbench and PHPUnit coverage for the package surface: Blade rendering, public assets, model configuration, context filtering, route actions, citations, retrieval, sessions, feedback, learning memory, analytics, events, page context, streaming, provider drivers, presets, headless API, and queued background dispatch.

The documentation is split into focused guides rather than one long README. There are docs for installation, examples, models, security, authorization, retrieval, route actions, citations, learning memory, feedback, sessions, multilingual answers, streaming, providers, analytics, background queues, public assets, modal customization, testing, and package development. GitHub templates, CI, Dependabot, funding metadata, changelog entries, and release tags make the package easier to maintain as an open-source project.

Academic reflection and future work

The project demonstrates that adding AI to an application is less about placing a model behind a text box and more about designing a controlled sociotechnical interface: what data is visible, who is asking, which records are authorized, how context is selected, how answers are traced, which actions are allowed, and which work can happen asynchronously.

Future work could evaluate retrieval quality across larger datasets, compare provider outputs across equivalent prompts, benchmark queue modes under load, measure citation accuracy, and study how different default questions affect user behavior. Those directions would turn ModelMind from an engineering package into a stronger empirical study of AI-assisted Laravel application design.

Results

  • Published `mbs047/model-mind` as a Composer and Packagist package with MIT license metadata, Laravel auto-discovery, install commands, and a documented first-run workflow
  • Released the package through `v1.0.15`, expanding from a chat modal into a model-aware assistant platform with retrieval, citations, route actions, providers, streaming, analytics, events, page context, and queueable background work
  • Built a governance layer where the assistant can only read explicitly enabled models, filtered columns, authorized rows, and approved context providers
  • Introduced `HasModelMindContext` so application models can own their AI representation and avoid scattering domain logic across package config only
  • Implemented ranked retrieval so relevant records can be selected from larger data sets without placing every row into the base prompt
  • Designed route actions as a safe application affordance: the assistant can suggest useful links only through pre-approved named routes and parameter mappings
  • Added source citations so generated answers can be traced back to model records, cited fields, and optional record-level route buttons
  • Added multilingual behavior so visitors can ask in Arabic or other languages while application data remains stored in one primary database language
  • Moved heavier summarization, learning, and analytics work into queueable jobs so the chat response path stays fast
  • Provided multiple integration surfaces: Blade modal, publishable public assets, custom modal views, headless JSON API, and provider-driver contracts
  • Validated the package through Orchestra Testbench and PHPUnit coverage for rendering, configuration, retrieval, actions, citations, sessions, analytics, events, and queue dispatch
  • Used Market Lane Store as a live applied setting where product catalog questions, product route buttons, multilingual prompts, and widget positioning could be tested in context

Key features

01 Composer-ready Laravel package with auto-discovery, install commands, config publishing, migrations, and release documentation
02 Drop-in Blade directives: `@modelMind`, `@modelMindModal`, `@modelMindStyles`, and `@modelMindScripts`
03 Public `.css` and `.js` assets for the default widget, with a publish command for custom front-end pipelines
04 Headless JSON API mode for React, Vue, Inertia, mobile, or custom clients that do not want the Blade modal
05 Explicit model registry where only approved Eloquent models and columns enter the assistant context
06 `HasModelMindContext` trait for model-owned labels, descriptions, columns, relations, query scopes, and route actions
07 Question-aware retrieval with weighted columns, fuzzy matching, multilingual normalization, optional Scout search, and optional vector search extension
08 Current page context so users can ask about the visible product, page, selected text, or page summary
09 Authorization and user-aware context for guards, roles, permissions, tenants, Gate checks, and per-model policies
10 Safe named-route action buttons with approved route names, mapped parameters, `label_column`, and `label_template`
11 Source citations that identify supporting records, models, fields, and optional route buttons
12 Provider abstraction with OpenAI as the default and additional Anthropic, Gemini, Ollama, and custom drivers
13 Streaming responses for faster perceived latency and provider-compatible live deltas
14 Persistent sessions, configurable session expiry, browser history restore, feedback, learned knowledge, and fed texts
15 Queueable background processing for conversation compaction, learning, analytics, feedback analytics, and route-action click analytics
16 Usage analytics for latency, token usage, provider model, failures, feedback rate, and action clicks
17 Events and hooks for sent messages, generated answers, submitted feedback, resolved actions, learned memory, and analytics rows
18 Real package presets for store, admin, support, docs, and CRM application contexts

Tech stack

Laravel 11-13 PHP 8.3+ Blade Tailwind CSS Eloquent Laravel Queues OpenAI Responses API Anthropic / Gemini / Ollama Drivers Composer Package Orchestra Testbench PHPUnit GitHub Actions Packagist
Project links

Interested in similar work?

I build systems like this for teams that need reliable engineering, clean interfaces, and measurable outcomes.