Skip to content

PHP API, Hooks & CLI

AI exposes $this->wire()->ai (or ProcessWire\Ai::requireInstance($wire)), 21 ProcessWire hooks, 8 processwire-console CLI commands, 4 queue jobs, and 1 scheduled maintenance task.

Method Purpose
generate(string $prompt, array $options = []) Synchronous text or JSON-schema generation using a ModelTier or explicit connection::model route.
stream(string $prompt, callable $onChunk, array $options = []) Streaming token generation invoking $onChunk as deltas arrive.
compose(Page|EntryItem $target, array $options = []) Generates structured field or Blocks tree proposals grounded in target context and schemas.
translate(string $text, string $targetLocale, array $options = []) Translates standalone text with optional glossary enforcement.
localize(Page|EntryItem $target, string $targetLocale, array $options = []) Localizes translatable multi-language fields on a page or entry with diff preview or direct apply.
enqueueLocalization(array $targetIds, string $targetLocale, array $options = []) Dispatches a background BulkTranslateQueue localization batch.
analyzeImage(Pageimage|string $image, array $options = []) Vision-tier analysis returning alt text, caption, tags, and focal point metadata.
generateImage(string $prompt, array $options = []) Image-tier generation returning saved media/artifact data.
audit(Page|EntryItem $target, array $options = []) Runs deterministic + AI editorial quality audit and returns structured findings.
runAgent(string $assistantHandle, string $message, array $options = []) Executes a multi-step tool-calling agent via AgentRunner.
renderChatWidget(array $options = []) Renders the self-contained ChatWidgetRenderer frontend widget (/_ai/chat).
Ai::fake(array $responses = []) Swaps live provider calls for deterministic canned responses and activates InMemoryVectorStore for tests.
Hook Arguments & Return Timing What It Does
Ai::generate (string $prompt, array $options = []): ChatResponse Before / After Intercepts or inspects synchronous text/JSON generation calls and responses.
Ai::compose (Page|EntryItem $target, string $brief, array $fields = [], array $options = []): array Before / After Intercepts or customizes structured page or block composition runs.
Ai::translate (array|string $input, string $targetLocale, string $sourceLocale = 'auto', array $options = []): TranslationResult|string Before / After Intercepts or customizes standalone text translation and glossary handling.
Ai::localize (Page|EntryItem $target, array $targetLocales, array $options = []): array Before / After Intercepts or customizes multi-language page or entry localization batches.
Ai::analyzeImage (Pageimage|string $image, array $locales = [], string $contextHint = '', bool $apply = false): VisionResult Before / After Intercepts or enriches multimodal vision analysis results (alt text, caption, focal point).
Ai::generateImage (string $prompt, string $aspectRatio = '16:9', string $stylePreset = 'editorial-photo', Page|EntryItem|null $attachToPage = null, string $imageField = ''): ImageResult Before / After Intercepts or post-processes AI-generated images.
Ai::audit (Page|EntryItem $target, ?Language $language = null, string $routeOverride = ''): AuditReport Before / After Intercepts or customizes full editorial quality audit runs.
Ai::collectAuditSignals (Page|EntryItem $target, ?Language $language = null): array After Contributes extra grounded signals before audit evaluation runs.
Ai::collectAuditIssues (Page|EntryItem $target, ?Language $language = null): array After Appends custom deterministic or domain-specific audit findings to an AuditReport.
Ai::collectTargetContext (Page|EntryItem $target, ?Language $language = null, array $options = []): array After Enriches grounded context payloads passed to editorial prompts.
Ai::collectTargetProviders (): array After Registers custom target entity resolvers beyond ProcessWire Pages and Entries.
Ai::collectAssistants (): array After Registers programmatic AbstractAssistant classes.
Ai::collectArtifactRenderers (): array After Registers custom ArtifactRendererInterface renderers for AI Studio previews.
Ai::collectRules (array $context = []): array After Registers code-defined editorial rules alongside MainRuleCatalog and ai-rules.
Ai::collectMcpTransports (): array After Registers or filters custom MCP transport definitions.
Ai::resolveBlockSchemas (array $blockTypes = []): array After Supplies or customizes block schemas for structured compose() runs.
Ai::localizeMenu (string $menuHandle, array $targetLocales): int Before / After Customizes Navigation menu localization behavior.
Ai::classifySubmission (array $payload): array After Customizes Forms submission classification and routing.
Ai::taskCompleted (array $event): void After Fires after any AI generation, audit, localization, or agent task completes.
Ai::registerCapabilities (CapabilityRegistry $registry): void After Registers custom AiCapabilityProviderInterface tool providers into CapabilityRegistry.
Ai::collectFieldAdapters (): array After Registers custom field read/write adapters for specialized ProcessWire Fieldtype modules.
ProcessAi::translations (): array After Returns localized UI strings for the Setup -> AI React workspace.
site/ready.php
<?php
declare(strict_types=1);
namespace ProcessWire;
// 1. Enrich grounded prompt context for yacht pages
$wire->addHookAfter('Ai::collectTargetContext', function (HookEvent $event): void {
$target = $event->arguments(0);
if (!$target instanceof Page || $target->template->name !== 'yacht') {
return;
}
$ctx = (array) $event->return;
$ctx['brandVoice'] = 'Aegean Voyages luxury maritime concierge';
$event->return = $ctx;
});
// 2. Append a custom deterministic audit check for missing yacht cabin counts
$wire->addHookAfter('Ai::collectAuditIssues', function (HookEvent $event): void {
$target = $event->arguments(0);
if (!$target instanceof Page || $target->template->name !== 'yacht') {
return;
}
$issues = (array) $event->return;
if ((int) $target->get('cabins') < 1) {
$issues[] = [
'code' => 'aegean.missing_cabins',
'severity' => 'error',
'message' => 'Yacht pages must define at least 1 guest cabin before publishing.',
];
$event->return = $issues;
}
});
// 3. Log completed AI tasks for cost and latency observability
$wire->addHookAfter('Ai::taskCompleted', function (HookEvent $event): void {
$task = (array) $event->arguments(0);
$type = (string) ($task['task'] ?? 'unknown');
$tokens = (int) ($task['totalTokens'] ?? 0);
$event->wire()->log->save('ai-tasks', "Completed {$type} ({$tokens} tokens)");
});

All 8 CLI Commands & Flags (vendor/bin/wire)

Section titled “All 8 CLI Commands & Flags (vendor/bin/wire)”

Checks blueprints, telemetry tables, permissions, cache paths, active connections, and vector store health:

Terminal window
php vendor/bin/wire ai:doctor --fix --dry-run --force --json

Flags: --fix, --dry-run, --force, --json.

Evaluates model routes, assistants, latency, and grounding assertions:

Terminal window
php vendor/bin/wire ai:eval --route=open-router::google/gemini-4-hydrogen --dry-run --json

Flags: --route, --dry-run, --json.

Exports database rules, voices, glossaries, or assistants as portable files for version control:

Terminal window
php vendor/bin/wire ai:export --type=assistants --handle=aegean-concierge --dry-run --force --json

Flags: --type, --handle, --dry-run, --force, --json.

Scaffolds a new AbstractAssistant PHP class under site/ai/assistants/:

Terminal window
php vendor/bin/wire make:assistant AegeanConcierge --task=writing --tier=balanced --title="Aegean Concierge" --dry-run --force --json

Flags: --task, --tier, --title, --dry-run, --force, --json.

Translates one or more pages/entries into a target locale using an optional glossary and queue:

Terminal window
php vendor/bin/wire ai:translate 1042 --to=tr --glossary=maritime-terms --queue --dry-run --force --json

Flags: --to, --glossary, --queue, --dry-run, --force, --json.

Runs deterministic or AI-assisted pre-publish audits (CI-ready exit code gating):

Terminal window
php vendor/bin/wire ai:audit --locale=en --deterministic-only --template=yacht --blueprint=charter-routes --limit=50 --glossary=maritime-terms --format=table --fail-on-issues --max-issues=0 --json

Flags: --locale, --deterministic-only, --template, --blueprint, --limit, --glossary, --format, --fail-on-issues, --max-issues, --json.

Indexes or clears semantic RAG vectors in the active vector store:

Terminal window
php vendor/bin/wire ai:index --type=pages --template=yacht --blueprint=charter-routes --limit=200 --queue --clear --dry-run --force --json

Flags: --type, --template, --blueprint, --limit, --queue, --clear, --dry-run, --force, --json.

Starts the local stdio JSON-RPC 2.0 (2024-11-05) MCP server:

Terminal window
php vendor/bin/wire ai:mcp --user=editor --scopes=pages.read,knowledge.search --modules=pages,entries --read-only --write-mode=propose

Flags: --user, --scopes, --modules, --read-only, --write-mode, --allow-destructive.

Class Schedule / Trigger Purpose
ArtifactGenerationQueue Dispatched via ArtifactService Renders heavy HTML brochures, image overlays, and QR artifacts asynchronously.
BulkEditorialQueue Dispatched via BulkEditorialService::dispatchBulk() Generates and tracks multi-page editorial proposals in background workers.
BulkTranslateQueue Dispatched via enqueueLocalization() / ai:translate --queue Runs multi-language glossary-protected localization batches asynchronously.
VectorIndexQueue Dispatched via ai:index --queue Chunks, embeds, and upserts page/entry vectors without blocking HTTP requests.
PruneAiUsageLogsTask Scheduled daily (dailyAt('03:35')) Prunes expired rows from ai_usage_logs and ai_mcp_logs according to retention settings.

Run the background queue worker and system cron so queued bulk translations, vector indexing, artifacts, and nightly log pruning execute automatically:

Terminal window
php vendor/bin/wire queue:work --tries=3 --sleep=3
# Crontab entry (runs PruneAiUsageLogsTask daily at 03:35)
* * * * * cd /var/www/aegeanvoyages.example && /usr/bin/php vendor/bin/wire schedule:run >> /var/log/pw-schedule.log 2>&1

Frontend Chat Widget Styling & Quality Logs

Section titled “Frontend Chat Widget Styling & Quality Logs”
  • Chat Widget CSS Custom Properties: Override :root tokens on your storefront to theme ChatWidgetRenderer cleanly: --ai-fc-bg, --ai-fc-fg, --ai-fc-card, --ai-fc-card-fg, --ai-fc-muted, --ai-fc-border, --ai-fc-primary, --ai-fc-primary-fg, --ai-fc-radius, --ai-fc-shadow, --ai-fc-font. Exclude /_ai/* from full-page caches.
  • Quality & Evaluation Log Channel (ai-quality): Inspect Setup -> Logs -> ai-quality for audit rule diagnostics and evaluation findings alongside Setup -> Logs -> ai-audit.

Provider Shows Key Required or Fails With 401

Section titled “Provider Shows Key Required or Fails With 401”

Symptom: Connection badge displays Key Required in Setup -> AI -> Providers.

Fix: Confirm the API key is saved in the connection’s key pool, or if using $env:VAR_NAME, verify the environment variable is exported to both PHP-FPM and your CLI worker shell.

Symptom: Overview displays a notice that the semantic vector index is empty and visitor chat lacks grounded answers.

Fix: Assign an embedding model in Routing & Governance, then run php vendor/bin/wire ai:index --type=pages --limit=100 --json (and ensure your queue worker is running if you passed --queue).

Symptom: EndpointUrlValidator rejects a custom openai-compatible or Qdrant URL.

Fix: Use a public HTTPS domain or, for local development models, select the ollama driver (which permits loopback 127.0.0.1 / localhost endpoints).

Next steps