AiWire

AI integration for ProcessWire. Supports Anthropic, OpenAI, Google, xAI, and OpenRouter.

AiWire — AI Integration Module for ProcessWire

Connect your ProcessWire site to AI providers: Anthropic (Claude), OpenAI (GPT), Google (Gemini), xAI (Grok), and OpenRouter (400+ models).

Manage multiple API keys per provider, test connections from admin, and use AI in your templates with a clean PHP API.

Full documentation with 25 real-world examples → DOCUMENTATION.md


Features


  • 5 providers — Anthropic, OpenAI, Google, xAI, OpenRouter
  • Multiple API keys per provider with enable/disable toggle
  • Automatic fallback — if one key/provider fails, the next one takes over
  • Connection testing — verify each key with one click in admin
  • Test Chat — interactive chat with parameter controls (temperature, tokens, model)
  • File cache — TTL-based caching (day/week/month/year) with page context
  • Field storage — save AI content to page fields for permanent, editable storage
  • Content blocksgenerate() method for multi-block pages (overview, FAQ, pairings…)
  • Conversation history — multi-turn chat support
  • Cost optimization — route tasks to different providers/models by complexity
  • Logging — standard + debug logging via ProcessWire log system

Requirements


  • PHP 8.1+
  • ProcessWire 3.0.210+
  • cURL extension enabled

Installation


  1. Download or clone into site/modules/AiWire/
  2. Admin → Modules → Refresh → Install AiWire
  3. Configure → add API keys → click test button
  4. Use $modules->get('AiWire') in your templates
site/modules/AiWire/
├── AiWire.module.php       # Main module
├── AiWireProvider.php       # API client for all providers
├── AiWireCache.php          # File-based cache system
├── models.json              # Editable provider model list
├── README.md                # This file
├── DOCUMENTATION.md         # Full API reference + 25 examples
└── LICENSE

Updating Models

Provider model IDs and labels are loaded from models.json. Edit that file when a provider adds, renames, or retires a model:

{
  "openai": {
    "defaultModel": "gpt-5.4",
    "models": {
      "gpt-5.4": "GPT-5.4",
      "gpt-5.4-mini": "GPT-5.4 Mini"
    }
  }
}

If models.json is missing or invalid, AiWire falls back to the built-in model list.

OpenAI and OpenRouter also support model refresh from the module settings. Refreshed models are stored in module config separately from models.json and are used first; if no refreshed list exists, AiWire falls back to models.json, then to built-in defaults.

Each API key can also define a custom model. The custom model value is optional, but when present it overrides the selected model for that key. This is useful for private, preview, account-gated, proxy, or newly released model IDs.

API Key Storage

Keys can be stored directly in the module settings, or as environment references such as env:OPENAI_API_KEY. Environment references avoid saving the real secret in ProcessWire module config.

Getting API Keys


Quick Start


$ai = $modules->get('AiWire');

// Simple — returns text only
echo $ai->chat('What is ProcessWire CMS?');

// Full response with metadata
$result = $ai->ask('Explain quantum computing in simple terms');
if ($result['success']) {
    echo $result['content'];              // AI response text
    echo $result['usage']['total_tokens']; // tokens used
}

// Fallback — tries Anthropic → OpenAI → Google
$result = $ai->askWithFallback('Summarize this article...', [
    'provider'          => 'anthropic',
    'fallbackProviders' => ['openai', 'google'],
]);

// Generate multiple AI blocks for a product page
$results = $ai->generate($page, [
    ['field' => 'ai_overview',    'prompt' => "Write overview of {$page->title}..."],
    ['field' => 'ai_food_pairing','prompt' => "Suggest pairings for {$page->title}..."],
    ['field' => 'ai_brand_story', 'prompt' => "Share 3 facts about {$page->brand->title}..."],
], ['cache' => 'M', 'temperature' => 0.7]);

API Methods


MethodReturnsDescription
chat($msg, $opts)stringSimple text response, empty on error
ask($msg, $opts)arrayFull response with success, content, usage, raw
askWithFallback($msg, $opts)arrayTries all keys/providers until success
askMultiple($msg, $providers)arraySame prompt to multiple providers
askAndSave($page, $fields, $msg)arrayAsk AI + save to page field (skip if exists)
generate($page, $blocks, $opts)arrayMulti-block generation with per-block settings
saveTo($page, $field, $content)boolSave content to page field
loadFrom($page, $field)?stringLoad content from page field
getProvider($key, $specific, $idx)?ProviderGet raw provider instance
getProvidersStatus()arrayStatus of all providers and keys
clearCache($page)intClear cache for a page
clearAllCache()intClear entire cache
cacheStats()arrayCache files count, size, etc.

→ Full API reference: DOCUMENTATION.md


Result Format


// Successful response from ask(), askWithFallback(), askAndSave(), generate()
[
    'success' => true,
    'content' => 'The AI response text...',
    'message' => 'OK',
    'usage'   => ['input_tokens' => 25, 'output_tokens' => 148, 'total_tokens' => 173],
    'raw'     => [ /* full API response */ ],
    'cached'  => false,       // true if served from file cache
    'source'  => 'ai',        // askAndSave/generate only: 'ai', 'field', or 'error'
]

Options


OptionTypeDefaultDescription
providerstringModule defaultanthropic, openai, google, xai, openrouter
modelstringKey's modelOverride model for this call
systemPromptstringModule defaultSystem instructions for the AI
maxTokensint1024Max tokens in response
temperaturefloat0.70.0 = precise, 1.0+ = creative
historyarray[]Previous messages for multi-turn chat
keyIndexintUse a specific key by index (0-based)
fallbackProvidersarrayFallback providers for askWithFallback
cachestring|boolfalseTTL: 'D', 'W', 'M', 'Y', '2W', '3M'
pageIdint|Page0Page context for cache scoping
timeoutint30Request timeout in seconds
overwriteboolfalseaskAndSave: always call AI even if field has content
quietbooltrueaskAndSave: save without triggering PW hooks

Supported Models


The default editable list in models.json currently includes:

ProviderModels
Anthropicclaude-opus-4-7, claude-opus-4-6, claude-sonnet-4-6-20260217, claude-haiku-4-5-20251001
OpenAIgpt-5.4, gpt-5.4-mini, gpt-5.4-nano, gpt-5.2, gpt-4.1
Googlegemini-3.1-pro-preview, gemini-3-flash, gemini-3.1-flash-lite, gemini-2.5-flash
xAIgrok-4.20, grok-4-1-fast-reasoning, grok-4-1-fast-non-reasoning, grok-code-fast-1
OpenRouterdeepseek/deepseek-v3.2, qwen/qwen3-max-thinking, meta-llama/llama-4-maverick, amazon/nova-2-lite-v1, z-ai/glm-5, xiaomi/mimo-v2-flash, bytedance-seed/seed-1.6, and 400+ more

Documentation & Examples


Full documentation with detailed API reference, 25 real-world examples (with ProcessWire setup, code, and expected output), cache strategies, field storage, multi-provider pipelines, and best practices:

DOCUMENTATION.md

Content generation — product pages, brand enrichment, category descriptions, cocktail recipes, region guides, tasting notes, review summaries

SEO & translations — auto-generate meta descriptions, OG titles, multi-language content

Chatbots & APIs — AI sommelier, gift recommendations, product comparison, form routing

Infrastructure — multi-provider cost optimization, fallback chains, key rotation, cache strategies, provider monitoring, team key separation, bulk LazyCron generation


License


MIT — free for personal and commercial use.

Author


Maxim Alexsmnv.orgmaxim@smnv.org

Built for the ProcessWire community.

More modules by Maxim Semenov

  • Context

    Export ProcessWire site context for AI development (JSON + TOON formats)
  • WireWall

    Advanced traffic firewall with VPN/Proxy/Tor detection, rate limiting, and JS challenge
  • Page Markdown

    Export any page to a clean Markdown file. Adds an export button to the page editor.
  • Subscribe

    Newsletter subscription handler with lists, double opt-in, honeypot, rate limiting and unsubscribe link.
  • AiWire

    AI integration for ProcessWire. Supports Anthropic, OpenAI, Google, xAI, and OpenRouter.
  • Plausible Analytics

    Plausible Analytics dashboard using Stats API v2 with page-edit widget, traffic trends chart, and geo/device tabs.
  • WirePDF

    Convert ProcessWire pages to PDF documents with advanced typography support
  • Ichiban

    Comprehensive SEO module: meta/OG/schema, audit, redirects, revisions, email reports.
  • Legal Docs

    AI-powered legal document generator. Generates Privacy Policy, Terms of Use, Cookie Policy and more for 93 jurisdictions.

All modules by Maxim Semenov

Install and use modules at your own risk. Always have a site and database backup before installing new modules.