Skip to main content
Version: v1 (Current)

AI Model Moderation System

Entity Relationship Diagram​

Moderation Process Flow​

This diagram summarizes the job path. Eligible provider failures can retry before the merge; terminal queue failure can create a separate failed log. Manual approval recording is described below and is not a general editable-log transition system.

Overview​

The moderation system provides AI-powered content moderation for user-generated content using Google's Gemini AI. It operates asynchronously through Laravel queues to prevent blocking user interactions while providing comprehensive error handling and admin oversight capabilities.

Interpreting moderation state​

Enabling AI moderation schedules analysis; disabling it skips analysis and does not independently approve or publish content. Configure the stream's approval workflow separately. The job intersects configured text/image columns with its supplied changed-column list, and skips empty values or missing prompts. A dispatched job is therefore not proof that every field was analyzed.

At reviewed develop revision 98dfe0fa8d92ca382c4a460c84b347637c141768, the moderator returns no log when no requested column is configured, or when it produced no responses/errors and the model currently expects no moderation columns at all (its expected-column list is empty). This is not the same as all entries in a nonempty expected-column list having completed. It applies no approval/flag verdict in that empty path. An empty photo or missing prompt can reach this path; a run with expected columns still outstanding is different and may remain pending. Absence of a new log is therefore not automatically approval or provider failure.

The attendee Flag Images with AI Moderator operation maps a null moderation result to Skipped. Approved and flagged logs both count as a successfully completed operation; pending/failed results map to operation failure. A success count does not mean every photo was approved. These are operation outcomes; verify the saved run counters, current photo and approval state separately, especially when a photo was removed after the run selected it. The isolated source check does not execute the bulk job or increment real counters.

The job combines new responses with responses from the latest AI moderation log for the same model, preserving previous responses for columns absent from the current run and deduplicating by column. It compares completed columns with the model's expected moderation columns. An otherwise approved result is logged as pending until all expected columns have responses. With automatic flagging enabled, a flagged result can be applied before all phases finish; approval waits for completion. With automatic flagging disabled, inspect the log and application approval state separately.

A failed provider call, pending phase, failed queue job and flagged content are different outcomes. The terminal failure handler can create a separate failed log; applying approval/flagging can itself fail and be logged without changing the stored content state. Reconcile both moderation logs and the post's current approval state before treating moderation as complete. Existing-response accumulation is not an immutable per-edit history.

Configure a social stream​

  1. Open the project's social-stream detail settings and enable AI Content Review. Confirm the setting was saved.
  2. Configure the relevant prompts: caption, poster name, image and, for video/audio, transcription. The post model selects a separate prompt ID for each field and applies the stream's substitutions. A missing or unresolved prompt skips that field; enabling review alone does not supply a fallback prompt.
  3. Choose Auto-Hide Flagged Posts deliberately. Despite the UI name, it controls automatic application of both flagged and completed-approved results; with it disabled, inspect results and manage visibility through the social-post workflow.
  4. Have a platform maintainer verify server-side Google Cloud configuration and the system-gemini-moderator system AI model. The current job selects GeminiModerator explicitly; adding another factory-compatible moderator does not switch this job's provider. Keep credentials server-side.
  5. Verify a synthetic text case, an image case and any configured transcription phase before relying on automatic publication decisions. Check both logs and the stored post state.

Stream settings and social-post operations have separate permissions. Configured dashboard mappings use manage_social_streams for stream changes and update_social_stream_posts for post updates, with corresponding view permissions. Authentication, project scoping and shared policy checks still apply. The system moderation-log index is in the system-admin route group; project permissions alone do not grant system-log access. Confirm the deployed role and route behavior before assigning reviewers.

Review and recover​

The system moderation-log page lists paginated results and expandable response/error details. The inspected controller registers a listing operation, not a general log-editing or export API. Review the affected post through the project's social-post management workflow rather than changing log fields directly.

When a post becomes approved from a previously unapproved state, its observer can record reviewer ID, approved override and review time on the latest log if that log was flagged or failed and reviewer context is available. The inspected branch does not record a symmetric flagged override for every manual hide, nor does approving an already approved post necessarily create a new review record. Check the post's actual visibility and relevant log after saving; a mutable log is not an immutable history of every review action.

SymptomCheck
No analyzed fieldsEnabled stream setting, supplied changed columns, non-empty field value and resolved field-specific prompt.
Log stays pendingExpected versus completed columns, especially transcription availability for video/audio.
Flagged result but post remains visibleAuto-hide setting and errors applying the content status; inspect actual approval state.
Initialization failureAsk a maintainer to verify server Google configuration and the required system AI model; do not expose credentials in a browser or support export.
No new runJob preconditions, deleted model, overlap/worker behavior and the 100 existing AI-log guard. Avoid blind repeated dispatch.
Manual approval lacks a reviewer entryCheck prior approval state, latest log result and whether the supported update supplied reviewer context.

Restricted system moderation-log inspection​

System Moderation Logs at /system/moderation-logs spans recorded moderation across the platform. It inherits system-host super-admin, two-factor, authenticated/verified account, team-context and password-confirmation gates. The index controller does not add a project action policy or a project filter; project review permissions alone do not grant this global view. Deployed ordinary-account and record-scope refusal remains acceptance work.

Find the log and affected content​

The table shows Experience, Poster Name, Result, Severity and Created At, with the log ID available as a hidden column. Default ordering is Created descending and 25 rows. Retain the log ID, moderated model type/ID and owning post/stream/project rather than matching only a poster name. Search matches result/severity and selected related social-post caption/poster/attendee-name fields; it is not a general search of every error, provider response or project name. This index specializes related context for social posts; an unfamiliar model type or missing/deleted relation may not display the same experience/poster detail.

Read decisions and expanded diagnostics​

Expand for Moderated Type, Result, Severity and the available response/error cards. Read the actual result/severity values rather than treating badge color as a complete policy: the UI has explicit colors for approved/flagged and selected severity values, with fallback colors for others. Pending, Failed and Flagged remain different outcomes described above. Neither a response card nor a color proves publication, completed phases or a successful automatic status change.

The response card's Original Message is read from the currently related post caption or file path. It is not a guaranteed saved copy of the content analyzed for that log. A later post edit can change what this label or related-field search shows. Correlate stored responses/column, log/error timestamps, source/reviewer fields and current post state through authorized evidence; do not call this table an immutable per-edit history or proof of human review.

Error cards can expose status, attempts, timestamps, exception/model/column data, endpoints, raw bodies, full response objects and traces where recorded. Escaped JSON display is not privacy redaction; apply the diagnostic boundaries below before sharing. The page expands the fetched list data rather than fetching a fresh log on expansion. Reload/refetch for a new observation, and preserve the exact IDs and observation time when comparing results.

Follow the owning review and recover observations​

This system route exposes listing only; the page supplies no general log edit, export, retry, approve or publish control. Follow the affected project's supported social-post review workflow and its authorization, then verify actual post visibility and any reviewer attribution independently. Do not edit log fields, repeatedly dispatch moderation or create a replacement post merely to change the displayed result.

For missing logs, check search/pagination, exact moderated identity and related-record availability. For an apparent mismatch, compare current content/approval with stored response/error phases and the documented accumulated-response behavior before retrying. Keep private content, identities, URLs, credentials and raw diagnostics out of public screenshots/issues; private operator/provider recovery remains separate. No private moderation record, provider call, publication, approval or retry was performed for this source review.

Architecture​

Core Components​

Moderator Services

  • ModeratorInterface - Contract for all moderation services
  • GeminiModerator - Google Gemini AI implementation
  • ModeratorFactory - Factory pattern for service instantiation
  • ModerationResponse - Standardized response format
  • ModerationApiException - Custom exception with data sanitization

Model Integration

  • AiModeratable trait - Provides moderation capabilities to models
  • ModerationLog model - Stores merged results and selected failure/reviewer metadata; not every attempt as an immutable record
  • SocialStreamPost - Primary model implementing moderation
  • SocialStream - Configuration for moderation settings

Processing Pipeline

  • ModerateEntityJob - Asynchronous job handling moderation
  • SocialStreamPostObserver - Triggers moderation on model changes
  • Queue-based processing with retry logic and backoff

Workflow​

  1. Content Creation/Update - User creates or updates content
  2. Observer Triggers - Model observer detects changes in moderated columns
  3. Job Dispatch - Moderation job queued for background processing
  4. AI Processing - Content sent to Gemini AI for analysis
  5. Response Handling - AI response parsed and validated
  6. Error Handling - Eligible API errors can retry within the job attempt limit
  7. Result Application - Content approved/flagged based on final AI decision
  8. Logging - The job merges responses into the latest AI log for the model; terminal job failure can create a separate failed log

Key Features​

Multi-Modal Support​

  • Text Moderation - Captions, descriptions, user input
  • Image Moderation - Photos, avatars, uploaded media
  • Video/Audio Handling - Direct media moderation skips video/audio; transcription is a separate moderation phase. A skipped media call is not proof that transcription or all expected columns completed.

Configuration Options​

  • Per-stream moderation enable/disable
  • Custom AI prompts for different content types
  • Auto-flagging vs manual review workflows
  • Recorded severity levels; no generic configurable rejection threshold is established by the reviewed job

Error Handling & Debugging​

  • Structured error logging with limited payload/response sanitization; see diagnostic boundaries
  • Automatic retry for API errors (rate limits, timeouts, server errors)
  • Job configuration: four attempts, 120-second timeout, failure on timeout, and 3/5/20-second backoff intervals. Actual scheduling also depends on queue/worker behavior.
  • Latest AI log is updated with merged column responses; there is no universal one-log-per-attempt guarantee.
  • Loop prevention mechanisms
  • Detailed admin interface for troubleshooting

Admin Interface​

  • Moderation logs with expandable error details
  • Review post visibility through the authorized social-post workflow
  • Conditional approval-review metadata; not an immutable review history
  • Paginated log listing; no export operation was found in the inspected log controller

File Structure​

Backend Core​

  • app/Services/Moderators/ - Moderation service implementations
  • app/Traits/AiModeratable.php - Model integration trait
  • app/Jobs/ModerateEntityJob.php - Background processing
  • app/Models/ModerationLog.php - Audit trail model
  • app/Observers/SocialStreamPostObserver.php - Change detection

Frontend Interface​

  • resources/js/Dashboard/Pages/Admin/System/ModerationLogs/Index.vue - Admin logs interface
  • resources/js/Composables/useSocialStreams.js - Frontend moderation utilities

Configuration & Testing​

  • database/migrations/ - Moderation table structures
  • tests/Unit/Services/Moderators/ - Unit tests
  • tests/Feature/Jobs/ModerateEntityJobTest.php - Integration tests
  • app/Console/Commands/TestAiModeration.php - CLI testing tool

Response and diagnostic boundaries​

Gemini's response parser reads the first candidate's first text part as JSON and requires approval_state, message and severity_level. It does not combine multiple candidates or text parts. The normalized response then validates approval as approved or flagged, severity as low, medium, high or critical, and a non-empty column name supplied by the caller. pending and failed are job/log states, not valid provider approval decisions. Invalid or missing response content raises an exception; it does not establish an approved decision.

Severity scores are 1–4 for low through critical. The job records the highest observed severity; a severity score is not itself a configurable automatic rejection threshold. Automatic visibility follows the approval decision and completion logic described above. Evaluate prompts and representative content separately from schema validity: a well-formed response is not proof of moderation quality.

Diagnostic sanitization is limited. Payload sanitization removes base64 bytes only at the first inline-data part; text, system prompts, file URLs and other parts can remain. JSON response sanitization redacts selected top-level credential-like fields, without recursively redacting nested objects. Some parser error records include raw/decoded response data. Pattern-based stack sanitization also does not establish that every message, failure record or log is free of personal data or credentials.

Keep provider credentials server-side, restrict moderation diagnostics to authorized staff, and inspect/redact diagnostic records before sharing them. Do not treat the system log view or an error export as a sanitized public artifact.

Performance Features​

  • Asynchronous processing prevents UI blocking
  • Model-specific WithoutOverlapping middleware limits overlapping execution; it does not prevent duplicate dispatch or guarantee exactly-once effects.
  • Smart retry mechanism for temporary API failures (429 rate limits, server errors, URL timeouts)
  • Current job timeout is 120 seconds with four attempts and 3/5/20-second backoff; it is marked failed on timeout.
  • Same-instance moderation guard and a 100-existing-AI-log precondition; these are limited safeguards, not proof that every loop or duplicate run is prevented
  • Accumulated moderation responses in the latest AI log, with separate failure records possible.

How To Implement AI Moderation Into a New Model​

These are extension fragments for a platform developer, not a complete replacement model. Supply the model namespace/imports, table, casts, mass-assignment rules, prompt storage and permission-protected review UI. The current built-in integration is SocialStreamPost; another model needs its own integration and acceptance tests.

Step 1: Add the AiModeratable Trait​

Add the AiModeratable trait to your model class:

use App\Traits\AiModeratable;

class YourModel extends Model
{
use AiModeratable;

// ... existing model code
}

Step 2: Implement Required Abstract Methods​

The trait requires you to implement several methods that define how moderation works for your model:

2.1 Define Moderated Content Columns​

/**
* Define which columns contain text content to moderate
*/
public function getAiModeratedTextColumns(): array
{
return ['title', 'description', 'content']; // Your text columns
}

/**
* Define which columns contain image content to moderate
*/
public function getAiModeratedImageColumns(): array
{
return ['image_path', 'avatar_url']; // Your image columns
}

2.2 Configure AI System Prompts​

/**
* Get the AI system prompt for a specific column
*/
public function getCustomSystemPrompt(string $columnName): ?string
{
// Fetch prompts from your configuration system
// Apply any variable substitutions needed
// Return null to skip this column; the job has no default-prompt fallback

return $this->getPromptFromConfiguration($columnName);
}

2.3 Implement Status Management​

/**
* Mark content as approved after moderation
*/
public function setApproved(): void
{
$this->update([
'is_moderated' => true,
'is_approved' => true,
'moderated_at' => now(),
]);
}

/**
* Mark content as flagged after moderation
*/
public function setFlagged(): void
{
$this->update([
'is_moderated' => true,
'is_approved' => false,
'moderated_at' => now(),
]);
}

2.4 Configure Moderation Settings​

/**
* Check if AI moderation is enabled for this model instance
*/
public function getAiModerationEnabled(): bool
{
// Return true/false based on your configuration
return config('your_model.moderation_enabled', false);
}

/**
* Check if automatic approval/flagging is enabled
*/
public function getAiModerationAutoFlaggingEnabled(): bool
{
// Return true/false based on your configuration
return config('your_model.auto_flagging_enabled', false);
}

2.5 Declare expected completion columns​

The trait also requires getExpectedModerationColumns(). For a text-only extension, include only non-empty text fields with configured prompts:

public function getExpectedModerationColumns(): array
{
return array_values(array_filter(
$this->getAiModeratedTextColumns(),
fn (string $column) => !empty(data_get($this, $column))
&& !empty($this->getCustomSystemPrompt($column))
));
}

This example is text-only. An image/media integration must include its expected image and deferred transcription columns deliberately, and implement the media helpers used by Gemini (mime, plus getBase64 locally or signedUrl outside the local environment). Merely listing a file-path column does not provide those methods or a transcription pipeline.

Step 3: Add Database Columns​

Ensure your model's table has the necessary columns to track moderation status:

// In your migration
$table->boolean('is_moderated')->default(false);
$table->boolean('is_approved')->default(false);
$table->timestamp('moderated_at')->nullable();

Step 4: Set Up Polymorphic Relationship to ModerationLog​

Add this relationship to your model:

/**
* Get all moderation logs for this model
*/
public function moderationLogs(): MorphMany
{
return $this->morphMany(ModerationLog::class, 'moderated');
}

Step 5: Create Model Observer (Optional)​

If you want automatic moderation on model changes, create an observer:

Create and register an observer for your model. Import App\Jobs\ModerateEntityJob in that observer. These methods pass the actual columns to the job and defer dispatch until commit:

public function created(YourModel $model): void
{
if ($model->getAiModerationEnabled() && !$model->wasJustModerated) {
$columns = array_merge(
$model->getAiModeratedTextColumns(),
$model->getAiModeratedImageColumns()
);
ModerateEntityJob::dispatch($model, $columns)->afterCommit();
}
}

public function updated(YourModel $model): void
{
$columns = array_values(array_intersect(
array_merge($model->getAiModeratedTextColumns(), $model->getAiModeratedImageColumns()),
array_keys($model->getChanges())
));
if ($columns && $model->getAiModerationEnabled() && !$model->wasJustModerated) {
ModerateEntityJob::dispatch($model, $columns)->afterCommit();
}
}

Register the observer in a service provider:

// In AppServiceProvider or dedicated observer service provider
YourModel::observe(YourModelObserver::class);

Step 6: Manual Moderation Trigger​

You can also trigger moderation manually:

use App\Jobs\ModerateEntityJob;

// Choose the fields to analyze explicitly; an empty list makes the job skip.
$columns = array_merge(
$yourModel->getAiModeratedTextColumns(),
$yourModel->getAiModeratedImageColumns()
);
ModerateEntityJob::dispatch($yourModel, $columns)->afterCommit();

Step 7: Admin Interface Integration​

To display moderation logs in your admin interface:

// In your controller
$model = YourModel::with('moderationLogs')->find($id);

// Access moderation data
$logs = $model->moderationLogs()
->orderBy('created_at', 'desc')
->get();

Step 8: Configuration Examples​

Here are common patterns for implementing the configuration methods:

public function getAiModerationEnabled(): bool
{
return $this->parentModel->ai_moderation_enabled ?? false;
}

Configuration via Database Settings​

public function getCustomSystemPrompt(string $columnName): ?string
{
$setting = Setting::where('key', "moderation_prompt_{$columnName}")
->first();
return $setting?->value;
}

Configuration via Config Files​

public function getAiModerationEnabled(): bool
{
return config("moderation.models.{$this->getTable()}.enabled", false);
}

Common Implementation Patterns​

  1. Content Management Systems: Moderate user posts, comments, descriptions
  2. User-Generated Media: Moderate uploaded images, profile pictures
  3. E-commerce: Moderate product descriptions, reviews, seller content
  4. Social Features: Moderate status updates, bios, messages

Testing Your Implementation​

Test dispatch and execution separately. With a queue fake, create/update a synthetic model and assert that ModerateEntityJob is queued with the intended model and changed columns. A queue assertion does not establish that an AI response or moderation log exists. When testing after-commit dispatch, make sure the test actually commits the transaction or explicitly exercises the observer in the intended transaction context.

For execution tests, replace the moderator/provider transport with deterministic responses, run the job, and assert the log plus the model's stored approval state. Cover missing prompts, empty columns, partial/deferred responses, a flagged column, provider failure and a failed status update. Use isolated synthetic records; do not call a live provider merely to assert queue wiring. Separately verify the configured provider, worker, media availability, permissions and manual-review workflow in deployment.

The examples above illustrate extension contracts. They do not install a review UI, implement file/transcription processing or establish an immutable audit history.

Verification scope​

The documented setup, model/job integration, decision/log state, response parsing, diagnostic limits and manual-review boundaries completed source and fresh-reader review on 2026-10-15. Offline checks cover job configuration (nine cases/13 assertions), synthetic response/redaction boundaries (two/10), and syntax of the 15 PHP fragments before the final prose-only clarity repairs. These scopes do not prove provider quality, deployed credentials/permissions, observer/queue timing, media/transcription completion, concurrent processing or end-to-end publication/review behavior. Validate those workflows in the target deployment before enabling automatic decisions.

The system moderation-log index/display supplement was source-reviewed on 2026-10-15 at platform 3b48eb675f7c8e3c4f0b87d0cd613fa7fb371093; existing parser/job evidence was not rerun or extended into deployed log, content-history, review or publication acceptance.