Search by

hassan-razhei / entity-ai

Hassan-Razhei

Framework-agnostic Laravel AI infrastructure SDK: agents, RAG, streaming, failover, cost, audit and conversations via injectable contracts.

Package info

github.com/Hassan-Razhei/entity-ai

pkg:composer/hassan-razhei/entity-ai

Statistics

Installs: 4

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-11-27 23:32 UTC

This package is auto-updated.

Last update: 2026-11-27 23:37:18 UTC


README

hassan-razhei/entity-ai is a standalone Laravel AI infrastructure package. It supplies the generic parts of an AI product — streaming chat, approvals, conversation persistence, hybrid RAG, Arabic text handling, failover, cost/usage tracking, health checks and metrics — without knowing anything about your domain models, roles, entity types or database relations.

The package was extracted from the EntityAISDK branch of EntityPostgre at commit 2f40a1d. All Entity/archive-specific agents, tools, policies, observers and jobs stay in the host application and are connected through the contracts below.

Requires PHP ^8.3, Laravel/Illuminate ^12|^13 and laravel/ai ^1.4.

Installation

Install from Packagist (once published):

composer require hassan-razhei/entity-ai:^1.0

For local development or during the EntityPostgre migration, use a path repository in the host composer.json:

{
  "repositories": [
    {
      "type": "path",
      "url": "../entity-ai",
      "options": { "symlink": true }
    }
  ],
  "require": {
    "hassan-razhei/entity-ai": "@dev",
    "laravel/ai": "^1.4"
  }
}

Then run:

composer update hassan-razhei/entity-ai laravel/ai
php artisan vendor:publish --tag=entity-ai-config
php artisan vendor:publish --tag=entity-ai-migrations
php artisan vendor:publish --tag=entity-ai-routes
php artisan vendor:publish --tag=entity-ai-assets
php artisan migrate
php artisan entity-ai:doctor

Publishing tags never overwrite a host file unless you ask Composer to do so. The package also supports auto-discovery; the provider is EntityAi\EntityAiServiceProvider and the facade alias is EntityAi.

What the package owns

  • config/entity-ai.php
  • package migrations with generic table names
  • package routes under api/ai (opt-in or published)
  • resources/js/useAiStream.js
  • framework events for audit and telemetry

What the host still owns

  • config/ai.php provider credentials, defaults and conversation storage (laravel/ai)
  • actors, roles, gates and policies
  • entity models, slugs, morph maps and relations
  • domain agents, tools, prompts and approval rules
  • authentication middleware and queue workers

Do not publish package config over config/ai.php. There is deliberately no package-owned provider default.

Publishables

Tag Destination
entity-ai-config config/entity-ai.php
entity-ai-migrations database/migrations/
entity-ai-routes routes/entity-ai.php
entity-ai-assets resources/js/Composables/useAiStream.js

Routes can also be loaded directly by setting ENTITY_AI_ROUTES_ENABLED=true; the host remains responsible for routes.middleware.

Contracts

Every host-specific boundary is injectable through entity-ai.contracts.*, a container instance, or a runtime app()->instance() binding.

Contract Default Host responsibility
EntityAi\Contracts\AuthorizesAi AllowAllAuthorizer (development only) Chat/studio/curation permissions, entity visibility, edit/publish, metrics, budgets.
ResolvesAiEntity GenericEntityResolver Translate opaque {type, identifier} pairs into host models and back.
ProvidesIndexableContent NullContentProvider Produce IndexableDocument values from host entities.
ChunkStore DatabaseChunkStore Store chunks and perform vector/lexical search; override for another vector backend.
EmbeddingProvider LaravelAiEmbeddingProvider Pin embeddings to the provider whose vector space matches the index.
ConversationStore DatabaseConversationStore Usually unchanged; context_key_column handles legacy column names.
AiAuditRecorder EventAiAuditRecorder Map package events to Activity, notifications or webhooks.
AiUsageRecorder DatabaseUsageRecorder Persist usage and enforce idempotency by invocation/operation.
AgentRegistry AgentRegistry Register host agents by name/mode.
ToolRegistry ToolRegistry Register host tools.
StreamResponder DefaultStreamResponder Override only to change SSE framing or headers.

Bind implementations in AppServiceProvider::register() or in config/entity-ai.php:

use EntityAi\Contracts\AuthorizesAi;
use EntityAi\Contracts\ProvidesIndexableContent;
use EntityAi\Contracts\ResolvesAiEntity;
use App\Ai\Adapters\EntityAuthorizer;
use App\Ai\Adapters\EntityContentProvider;
use App\Ai\Adapters\EntityResolver;

$this->app->singleton(AuthorizesAi::class, EntityAuthorizer::class);
$this->app->singleton(ResolvesAiEntity::class, EntityResolver::class);
$this->app->singleton(ProvidesIndexableContent::class, EntityContentProvider::class);

Or as configuration:

'contracts' => [
    'authorizer' => \App\Ai\Adapters\EntityAuthorizer::class,
    'entity_resolver' => \App\Ai\Adapters\EntityResolver::class,
    'content_provider' => \App\Ai\Adapters\EntityContentProvider::class,
    'audit_recorder' => \App\Ai\Adapters\ActivityAuditRecorder::class,
],

Registering agents and tools

At boot time:

use EntityAi\Facades\EntityAi;

EntityAi::agents()->register('research', \App\Ai\Agents\ArchiveResearchAgent::class);
EntityAi::agents()->register('studio', \App\Ai\Agents\StudioEditorAgent::class);
EntityAi::agents()->register('curate', \App\Ai\Agents\EntityCatalogingAgent::class);

EntityAi::tools()->register('search_archive', \App\Ai\Tools\SearchArchiveEntitiesTool::class);

Or declaratively:

'agents' => [
    'default_mode' => 'research',
    'studio_mode' => 'studio',
    'modes' => [
        'research' => \App\Ai\Agents\ArchiveResearchAgent::class,
        'studio' => \App\Ai\Agents\StudioEditorAgent::class,
    ],
],
'tools' => [
    'registry' => [
        'search_archive' => \App\Ai\Tools\SearchArchiveEntitiesTool::class,
    ],
],

Unknown agent names throw EntityAi\Exceptions\InvalidAgentException; forMode() falls back to default_mode.

HTTP API

Routes are prefixed by entity-ai.routes.prefix (api/ai by default):

Method Path Purpose
POST /stream Stream an agent response as SSE.
POST /approvals/resume Resume an owned conversation after tool approvals.
GET /conversations List conversations visible to the actor.
GET /conversations/{conversationId}/messages Read owned messages.
GET /admin/metrics Usage/cost dashboard data.
GET /health Configuration and pgvector/HNSW health.

/stream accepts prompt, conversation_id, entity_type, entity_identifier, agent_mode, studio_mode, context_key and the legacy aliases entity_slug/node_slug. The resolver decides which entity types are supported; the package does not hardcode book|manuscript|audio|video.

SSE protocol

The stream response preserves the original wire format:

data: {"type":"stream_start", ...}

data: {"type":"text_delta", ...}

data: {"type":"stream_end", ...}

data: {"type":"conversation_meta","conversation_id":"..."}

data: [DONE]

Headers are Cache-Control: no-cache, no-transform, Content-Type: text/event-stream; charset=UTF-8 and X-Accel-Buffering: no. conversation_meta and [DONE] can be switched off under entity-ai.stream. stream_end is the authoritative completion event; [DONE] is only a client sentinel.

For Nginx, disable buffering/gzip for the stream path and run the configured entity-ai.rag.queue worker. Stream then() callbacks — including usage recording and entity-context attachment — run only after the stream is fully consumed; early client aborts may skip them.

RAG and Arabic text

EntityAi::indexer()->indexDocument($document) accepts an IndexableDocument produced by your ProvidesIndexableContent adapter. It chunks text (1200 chars/180 overlap by default), keeps diacritics in the original content, and writes search-only text to normalized_content. Embeddings are generated once per chunk through EmbeddingProvider; chunk metadata records the embedding model.

EntityAi::search()->search($query, $filters) fuses vector and lexical hits with reciprocal rank fusion (RRF_K = 60). PostgreSQL uses vector(dimensions) plus tsvector; other drivers store JSON embeddings and use PHP cosine similarity, which keeps local tests portable.

ENTITY_AI_EMBEDDINGS_DIMENSIONS must match the vector column. Changing it after indexing requires a reindex. A provider switch also requires a reindex because vector spaces differ; failover is therefore chat-only.

Environment translation

Reference host variables map as follows:

Old variable New variable
AI_FAILOVER_* ENTITY_AI_FAILOVER_*
AI_AUTO_INDEX ENTITY_AI_AUTO_INDEX
AI_INDEX_QUEUE ENTITY_AI_QUEUE
AI_INDEX_DELAY_SECONDS ENTITY_AI_INDEX_DELAY_SECONDS
AI_EMBEDDINGS_DIMENSIONS ENTITY_AI_EMBEDDINGS_DIMENSIONS
AI_EMBEDDINGS_PROVIDER ENTITY_AI_EMBEDDINGS_PROVIDER
AI_EMBEDDINGS_MODEL ENTITY_AI_EMBEDDINGS_MODEL
AI_DAILY_LIMIT_* ENTITY_AI_DAILY_LIMIT_*
AI_ENFORCE_DAILY_LIMITS ENTITY_AI_ENFORCE_DAILY_LIMITS

Provider API keys (GEMINI_API_KEY, OPENAI_API_KEY, …), AI_DEFAULT_PROVIDER and other laravel/ai keys remain unchanged and host-owned.

Health, metrics and events

php artisan entity-ai:doctor reports bindings, migrations, configured provider and vector readiness.

The provider registers RecordAiUsageListener for AgentPrompted, AgentStreamed and EmbeddingsGenerated, and LogAiFailoverListener for ProviderFailedOver/AgentFailedOver. These registrations were missing in the reference implementation. Disable them with ENTITY_AI_RECORD_USAGE=false / ENTITY_AI_LOG_FAILOVER=false when the host provides its own telemetry.

AiAuditRecorder implementations receive tool execution, approval decisions and entity mutations as framework events by default. EntityPostgre adapters map those events to Activity.

Testing

composer install
composer dump-autoload
composer test
composer test:unit
composer test:feature

The package suite uses Orchestra Testbench with in-memory SQLite and fake contracts. Entity-specific assertions belong in EntityPostgre under tests/Feature/Ai.

Migration notes

See docs/EXTRACTION_MAP.md for the complete transfer/redesign/adapter map and docs/adr/ for architecture decisions. The first recommended tag is v1.0.0, after both the package suite and the EntityPostgre adapter suite are green.

Known constraints:

  • Approval-resume turns do not fail over in laravel/ai v1.4.2.
  • Middleware authorization is checked on the first stream step only; write tools must re-check permissions.
  • PDF ingestion is delegated to host-provided OCR.
  • phpoffice/phpword and PDO drivers are suggest, not hard dependencies.