### OpenAI (GPT) Provider Example Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/providers-reference.md Example of using the OpenAI provider with a specific model and temperature setting. Also demonstrates how to refresh provider models. ```php $result = $ai->ask('Your prompt...', [ 'provider' => 'openai', 'model' => 'gpt-5.4-mini', 'temperature' => 0.5, ]); // Refresh models from API (requires active key) $ai->refreshProviderModels('openai', null, 0); ``` -------------------------------- ### Install AiWire Module Source: https://github.com/mxmsmnv/aiwire/blob/main/README.md Steps to install the AiWire module into your ProcessWire site. This involves downloading or cloning the module and then installing it via the ProcessWire admin interface. ```bash site/modules/AiWire/ ``` -------------------------------- ### Google (Gemini) Provider Example Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/providers-reference.md Example of how to integrate with the Google Gemini provider using a specified model. This uses an OpenAI-compatible API format. ```php $result = $ai->ask('Your prompt...', [ 'provider' => 'google', 'model' => 'gemini-3.1-pro-preview', ]); ``` -------------------------------- ### Example Tasting Notes Output Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md An example of the professional tasting notes generated by AiWire for a product. ```text tasting_notes: "Deep amber with golden highlights. The nose opens with rich caramel, dried apricot, and a whisper of peat smoke over toasted oak. On the palate, layers of dark chocolate, orange marmalade, and warm baking spices unfold with a velvety texture. The finish is long and warming, with lingering notes of espresso and sea salt." ``` -------------------------------- ### Generate Region Guide with AiWire Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md Generates an educational guide for a wine/spirits region, including an overview and personalized product recommendations. Requires a 'region' template and 'product' template with a 'region' field. ```php // site/templates/region.php $ai = $modules->get('AiWire'); $products = $pages->find("template=product, region={$page->id}, limit=30"); $productList = $products->implode("\n", function($p) { return "- {$p->title} by {$p->brand->title} ({$p->parent->title})"; }); $results = $ai->generate($page, [ [ 'field' => 'ai_region_overview', 'prompt' => "Write a guide to {$page->title} as a wine/spirits region. " . "Country: {$page->parent->title}. " . "Cover: geography, climate, key grape varieties or distillation traditions, " . "and what makes products from this region distinctive. 3 paragraphs.", 'options' => ['maxTokens' => 600, 'temperature' => 0.5], ], [ 'field' => 'ai_region_recommendations', 'prompt' => "From this product list, pick 5 standout products and explain " . "why each one is worth trying. Be specific about flavors and occasions.\n\n" . $productList, 'options' => ['maxTokens' => 500, 'temperature' => 0.6], ], ], ['cache' => 'M']); ``` -------------------------------- ### xAI (Grok) Provider Example Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/providers-reference.md Example demonstrating the use of the xAI Grok provider with a specific model. This provider offers OpenAI-compatible API and real-time information access. ```php $result = $ai->ask('Your prompt...', [ 'provider' => 'xai', 'model' => 'grok-4.20', ]); ``` -------------------------------- ### Example Saved SEO Fields Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md These are example values for the 'seo_description' and 'og_title' fields after being automatically generated by the AiWire module upon saving a product page. ```text $page->seo_description = "Discover the 2015 Louis Roederer Cristal — a prestige champagne with six years of aging, delivering citrus and brioche elegance." $page->og_title = "2015 Cristal: Six Years of Champagne Perfection" ``` -------------------------------- ### Anthropic (Claude) Provider Example Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/providers-reference.md Example of how to use the Anthropic provider with a specific model. Ensure you have set up the 'anthropic' provider key and have a valid API key. ```php $result = $ai->ask('Your prompt...', [ 'provider' => 'anthropic', 'model' => 'claude-opus-4-7', ]); ``` -------------------------------- ### Example Gift Recommendation API Response Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md This is an example of the JSON response returned by the gift recommendation API endpoint, providing product suggestions and reasons. ```json { "success": true, "recommendations": [ { "product": "Lagavulin 16 Year Old", "reason": "A legendary Islay single malt — perfect for a father who appreciates smoky, complex whiskey. The iconic square bottle makes an impressive gift." }, { "product": "Balvenie DoubleWood 12", "reason": "Approachable yet sophisticated, aged in two types of cask. Great for someone exploring single malts. Well within budget at $65." }, { "product": "Redbreast 12 Year Old", "reason": "Ireland's finest pot still whiskey — smooth, fruity, and universally loved. If your dad enjoys smooth sipping whiskey, this is a safe bet." } ] } ``` -------------------------------- ### Cache File Structure Example Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-cache.md Illustrates the JSON structure of a cached entry, including metadata like creation time, expiration, TTL, and the actual result content. ```json { "created_at": 1718025600, "expires_at": 1718630400, "ttl": "W", "ttl_seconds": 604800, "message": "Hello world", "provider": "anthropic", "model": "claude-sonnet-4-6-20260217", "page_id": 1042, "result": { "success": true, "content": "Hello! How can I help you?", "message": "OK", "usage": { "input_tokens": 12, "output_tokens": 8, "total_tokens": 20 }, "raw": { ... } } } ``` -------------------------------- ### Provider Caching Example Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/architecture.md Illustrates how provider instances are cached using a key derived from provider, API key, and model. This avoids redundant object creation for identical configurations. ```text anthropic:abc123def456:xyz789 → AiWireProvider instance (reused) openai:fed123cba456:xyz789 → AiWireProvider instance (reused) ``` -------------------------------- ### ask() Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-aiwire.md Send a message to AI and get a full response with metadata, including caching support. ```APIDOC ## ask() ### Description Send a message to AI and get a full response with metadata. Supports caching based on global settings and code-level options. ### Method `public function ask(string $message, array $options = []): array` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **$message** (string) - Required - The user message - **$options** (array) - Optional - Configuration for this request **Options:** - **provider** (string) - Optional - `anthropic`, `openai`, `google`, `xai`, `openrouter`. Defaults to module default. - **model** (string) - Optional - Override the model for this call. - **systemPrompt** (string) - Optional - System instructions. Defaults to module default. - **maxTokens** (int) - Optional - Maximum tokens in response. Defaults to `1024`. - **temperature** (float) - Optional - Creativity (0.0 = precise, 1.0+ = creative). Defaults to `0.7`. - **history** (array) - Optional - Previous messages for multi-turn chat. Defaults to `[]`. - **key** (string) - Optional - Use a specific API key string directly. - **keyIndex** (int) - Optional - Use a specific key by index (0-based). - **cache** (bool|string) - Optional - `'D'`, `'W'`, `'M'`, `'Y'`, `'2W'`, `'3M'`, or seconds (int). `true` uses default TTL, `false` disables cache. Defaults to global setting. - **pageId** (int|Page) - Optional - Page context for cache scoping. Defaults to `0`. - **timeout** (int) - Optional - Request timeout in seconds. Defaults to module timeout. ### Request Example ```php $result = $ai->ask('Explain quantum computing in simple terms', [ 'provider' => 'anthropic', 'temperature' => 0.5, 'cache' => 'W', ]); if ($result['success']) { echo $result['content']; echo "Tokens: " . $result['usage']['total_tokens']; } ``` ### Response #### Success Response (200) Returns an array with the following keys: - **success** (bool) - Whether the request succeeded - **content** (string) - The AI response text - **message** (string) - Status message (`'OK'` on success) - **usage** (array) - Token usage: `input_tokens`, `output_tokens`, `total_tokens` - **raw** (array) - Full API response from provider - **cached** (bool) - Whether result came from cache ### Response Example ```json { "success": true, "content": "Quantum computing is a type of computation that harnesses the collective properties of quantum states...", "message": "OK", "usage": { "input_tokens": 50, "output_tokens": 100, "total_tokens": 150 }, "raw": { ... }, "cached": false } ``` ``` -------------------------------- ### Get a Basic Result Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/README.md This snippet shows how to get a basic result from the AiWire module. It demonstrates checking for success and displaying the content or error message. ```php $ai = $modules->get('AiWire'); $result = $ai->ask('Your question here'); if ($result['success']) { echo $result['content']; echo "Tokens: " . $result['usage']['total_tokens']; } else { echo "Error: " . $result['message']; } ``` -------------------------------- ### Get All Providers Status Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md Use `getProvidersStatus` to obtain an overview of all configured AI providers, including their labels, active status, and the number of keys available for each. ```php $status = $ai->getProvidersStatus(); // ['anthropic' => ['label' => 'Anthropic (Claude)', 'active' => true, 'keyCount' => 2], ...] ``` -------------------------------- ### Get Available Models for an AiWire Provider Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/configuration.md Fetch a list of available models for a specific AI provider and iterate through them. ```php // Provider models $models = $ai->getProviderModels('anthropic'); foreach ($models as $id => $label) { echo "$label ($id)\n"; } ``` -------------------------------- ### Bulk Generation with LazyCron Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md Schedule bulk AI content generation for multiple pages using LazyCron. This example generates descriptions and keywords for products that lack them. ```php // site/ready.php $wire->addHook('LazyCron::everyHour', function() { $ai = wire('modules')->get('AiWire'); $pages = wire('pages')->find("template=product, ai_description=''"); foreach ($pages as $p) { $ai->askAndSave($p, [ 'ai_description' => "Write a product description for: {$p->title} Features: {$p->features}", 'ai_keywords' => "Extract 5 keywords for: {$p->title}", ], null, ['maxTokens' => 300, 'temperature' => 0.7]); } }); ``` -------------------------------- ### Response Structure Example Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/INDEX.md Illustrates the typical structure of a response object from AIWire methods, including success status, content, usage statistics, and raw API data. ```json { "success": true, "content": "AI generated response.", "message": "OK", "usage": { "input_tokens": 100, "output_tokens": 200, "total_tokens": 300 }, "raw": { ... }, "cached": false, "source": "ai" } ``` -------------------------------- ### Use Specific Key Index for Team/Environment Separation Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md Assign specific API keys to different teams or environments by using the 'keyIndex' option. This allows for separate billing, rate limits, and access control. The example demonstrates using keys for marketing, SEO batch jobs, and a default production key. ```php $ai = $modules->get('AiWire'); // ── Marketing team: use key #1 for promotional content ── $promo = $ai->ask( "Write a promotional banner text for {$page->title}...", [ 'provider' => 'anthropic', 'keyIndex' => 1, // "Marketing team" key — billed separately 'maxTokens' => 200, ] ); // ── SEO batch jobs: use key #2 with higher rate limits ── $products = $pages->find("template=product, seo_description='', limit=50"); foreach ($products as $p) { $ai->askAndSave($p, 'seo_description', "Write SEO description for {$p->title}...", [ 'provider' => 'anthropic', 'keyIndex' => 2, // "SEO batch jobs" key — dedicated quota 'maxTokens' => 100, 'temperature' => 0.3, ] ); } // ── Frontend chatbot: use default key (key #0, "Production") ── $result = $ai->askWithFallback($userMessage, [ 'provider' => 'anthropic', // uses key #0 by default 'fallbackProviders' => ['openai'], 'maxTokens' => 500, ]); // ── Check which key was used ── if ($result['success']) { wire('log')->save('ai-keys', sprintf( "Task: chatbot | Provider: %s | Key: %s (#%d) | Tokens: %d", $result['usedProvider'], $result['usedKeyLabel'], $result['usedKeyIndex'], $result['usage']['total_tokens'] ?? 0 )); } ``` -------------------------------- ### Get Raw Provider Instance Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md Retrieve a specific AI provider instance using `getProvider` for advanced operations. You can then use methods like `testConnection` on the obtained provider object. ```php $provider = $ai->getProvider('anthropic'); $testResult = $provider->testConnection(); ``` -------------------------------- ### Get a Result with Caching Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/README.md This snippet demonstrates how to use AiWire's caching mechanism. It shows how to specify a cache duration and a page ID, and how to check if the result was served from the cache. ```php $result = $ai->ask('Your question here', [ 'cache' => 'W', // Cache for 1 week 'pageId' => $page->id, ]); echo $result['cached'] ? 'From cache' : 'From API'; ``` -------------------------------- ### Get Page Cache Directory Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-cache.md Determines the specific directory path for cache entries associated with a given page ID. Example path format: site/assets/cache/AiWire/1042/. ```php protected function getPageDir(int $pageId): string ``` -------------------------------- ### Instantiate AiWireProvider Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-provider.md Create a provider instance with configuration details. Ensure you provide the correct provider key, configuration array, API key, and model ID. ```php $config = [ 'url' => 'https://api.anthropic.com/v1/messages', 'defaultModel' => 'claude-sonnet-4-6-20260217', ]; $provider = new AiWireProvider('anthropic', $config, $apiKey, 'claude-sonnet-4-6-20260217', [ 'timeout' => 30, ]); ``` -------------------------------- ### Get Cache File Path Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-cache.md Constructs the full file path for a specific cache entry using the page ID and cache key. Example path format: site/assets/cache/AiWire/1042/a1b2c3.json. ```php protected function getFilePath(int $pageId, string $key): string ``` -------------------------------- ### Execute cURL GET Request Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-provider.md Executes a cURL GET request to a provider API. Returns an array containing HTTP response data. ```php protected function curlGetRequest(string $url, array $headers): array ``` -------------------------------- ### Instantiate AiWireCache Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-cache.md Create a new instance of the AiWireCache. You can specify a custom base path for the cache directory and enable debug logging. ```php $cache = new AiWireCache(); // Or with custom path and debug: $cache = new AiWireCache('/custom/cache/path/', true); ``` -------------------------------- ### Fallback to Alternative Providers Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/providers-reference.md Demonstrates how to use the `askWithFallback` method to automatically switch to alternative providers if the primary provider encounters issues or rate limits. This ensures request completion by trying a sequence of providers. ```php $result = $ai->askWithFallback('Your prompt...', [ 'provider' => 'anthropic', 'fallbackProviders' => ['openai', 'google'], ]); ``` -------------------------------- ### Compare AI Providers with askMultiple Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md This PHP snippet demonstrates how to use the `askMultiple` method to send the same prompt to various AI providers and compare their responses. It displays the results in an HTML table, including the response content and token usage. ```php $ai = $modules->get('AiWire'); $prompt = 'Describe the flavor profile of a 12-year-old single malt Scotch in 3 sentences.'; $results = $ai->askMultiple($prompt, ['anthropic', 'openai', 'google', 'xai']); echo ""; foreach ($results as $provider => $result) { $content = $result['success'] ? htmlspecialchars($result['content']) : 'Error: ' . $result['message']; $tokens = $result['usage']['total_tokens'] ?? '—'; echo ""; } echo "
ProviderResponseTokens
{$provider}{$content}{$tokens}
"; ``` -------------------------------- ### askWithFallback() Flow Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/architecture.md Outlines the logic for 'askWithFallback()', including trying multiple API keys for a primary provider before attempting fallback providers. ```text User Code ↓ $ai->askWithFallback($message, $options) ↓ [Try each key for primary provider] ├─ Key 1 → ask() → success? YES → return with usedProvider/usedKeyIndex ├─ Key 1 → ask() → success? NO → continue ├─ Key 2 → ask() → success? YES → return └─ Key N → ask() → success? NO → continue ↓ [Try fallback providers] ├─ Provider 1 keys → try each → success? YES → return ├─ Provider 2 keys → try each → success? YES → return └─ Provider N keys → try each → success? NO → error ↓ Return error (all providers exhausted) ``` -------------------------------- ### Using Environment Variables for API Keys Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/configuration.md Demonstrates how to reference environment variables for API keys in the ProcessWire admin configuration. AiWire resolves these references at runtime for enhanced security and easier deployment. ```php // In admin: enter this in the API key field env:ANTHROPIC_API_KEY ``` ```dotenv // .env or system environment ANTHROPIC_API_KEY=sk-ant-... OPENAI_API_KEY=sk-... ``` -------------------------------- ### Generate Product Comparison with AI Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md This PHP snippet demonstrates how to fetch product data in ProcessWire and use the AiWire module to generate a natural-language comparison. It's useful for creating dynamic comparison pages that offer context and recommendations. ```php // site/templates/compare.php $ai = $modules->get('AiWire'); $ids = $input->get->intArray('products'); // ?products=1042,1043,1044 $products = $pages->getById($ids); $productData = ''; foreach ($products as $p) { $productData .= "### {$p->title}\n" . "Category: {$p->parent->title}\n" . "Brand: {$p->brand->title}\n" . "Region: {$p->region->title}\n" . "ABV: {$p->abv}%\n" . "Price: \" . "Tasting: {$p->tasting_notes}\n\n"; } $result = $ai->ask( "Compare these {$products->count()} products for a customer who wants to make an informed choice:\n\n" . $productData . "Write a comparison covering: flavor profiles, value for money, best occasions, " . "and a clear recommendation for different preferences (e.g. 'If you prefer bold flavors, go with X').", [ 'maxTokens' => 800, 'temperature' => 0.5, 'cache' => 'W', 'pageId' => $products->first()->id, ] ); ``` -------------------------------- ### cache Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md Gets the cache instance for direct access. ```APIDOC ## cache() ### Description Get the cache instance for direct access. ### Method `cache` ### Parameters None ``` -------------------------------- ### getProvidersStatus Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md Gets a status overview of all providers and their key counts. ```APIDOC ## getProvidersStatus() ### Description Get status overview of all providers and their key counts. ### Method `getProvidersStatus` ### Parameters None ``` -------------------------------- ### ask() Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md Returns the full structured response including metadata like usage statistics and raw API output. ```APIDOC ## ask() ### Description Returns the full structured response with metadata. This includes success status, content, messages, usage statistics, and the raw API response. ### Method Not applicable (SDK method) ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $ai = $modules->get('AiWire'); $result = $ai->ask('Translate "hello" to 10 languages'); ``` ### Response #### Success Response - **success** (bool) - Indicates if the operation was successful. - **content** (string) - The AI-generated response text. - **message** (string) - A status message or error description. - **usage** (object) - Token usage statistics. - **input_tokens** (int) - Tokens used in the prompt. - **output_tokens** (int) - Tokens generated in the response. - **total_tokens** (int) - Total tokens consumed. - **raw** (object) - The full raw API response from the provider. #### Response Example ```json { "success": true, "content": "Bonjour, Hola, Hallo, Ciao, ...", "message": "OK", "usage": { "input_tokens": 15, "output_tokens": 230, "total_tokens": 245 }, "raw": { ... } } ``` ``` -------------------------------- ### chat() Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-aiwire.md A quick method to get a plain text AI response. ```APIDOC ## chat() ### Description Quick shortcut to get AI response as plain text only. Returns empty string on error. ### Method `public function chat(string $message, array $options = []): string` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **$message** (string) - Required - The user message to send to AI - **$options** (array) - Optional - Override options (same as `ask()`) ### Request Example ```php $ai = $modules->get('AiWire'); $response = $ai->chat('What is ProcessWire?'); echo $response; ``` ### Response #### Success Response (200) - **content** (string) - The AI response text, or empty string if failed. ### Response Example ``` AiWire is a module for ProcessWire that integrates AI capabilities... ``` ``` -------------------------------- ### Generate Multiple AI Blocks for a Product Page Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md Use the `generate()` method to create multiple AI-driven content blocks for a single page, each with its own prompt, system prompt, and options. This is ideal for product pages requiring distinct content sections like overviews, brand facts, reviews, and food pairings. Each block can be configured with specific AI models, temperatures, and token limits, and can optionally override global settings. The module checks if content already exists in the specified field before making an AI call. ```php // site/templates/product.php — e.g. "2015 Louis Roederer Cristal" $ai = $modules->get('AiWire'); $results = $ai->generate($page, [ [ 'field' => 'ai_overview', 'prompt' => "Write a detailed overview of {$page->title}. " . "Include flavor profile, food pairings, and ideal serving temperature. " . "Vintage: {$page->vintage}. Region: {$page->regionקס}.", 'options' => ['maxTokens' => 600, 'temperature' => 0.6], ], [ 'field' => 'ai_brand_facts', 'prompt' => "Share 3 interesting facts about {$page->brand->title} " . "that most people don't know. Be engaging and surprising.", 'systemPrompt' => 'You are a wine historian. Write in a friendly, conversational tone.', 'options' => ['maxTokens' => 400], ], [ 'field' => 'ai_review_summary', 'prompt' => "Summarize these customer reviews in 3 sentences. " . "Mention common praise and any complaints:\n\n" . $page->reviews->implode("\n---\n", 'body'), 'options' => ['temperature' => 0.3, 'maxTokens' => 300], ], [ 'field' => 'ai_food_pairing', 'prompt' => "Suggest 5 specific food pairings for {$page->title}. " . "Format as a simple list.", 'options' => ['provider' => 'google', 'model' => 'gemini-3.1-flash-lite'], ], ], [ // Global options — apply to all blocks unless overridden 'cache' => 'M', 'temperature' => 0.7, ]); // Use in template if ($results['ai_overview']['success']) { echo "
{$results['ai_overview']['content']}
"; } if ($results['ai_brand_facts']['success']) { echo ""; } ``` -------------------------------- ### Get AiWire Cache Statistics Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/configuration.md Retrieve statistics about the AiWire cache, such as the total size in MB. ```php // Get cache stats $stats = $ai->cacheStats(); echo "Cache size: " . ($stats['total_size'] / 1024 / 1024) . " MB"; ``` -------------------------------- ### Configuration Settings Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/INDEX.md Overview of available configuration settings for AI parameters, defaults, caching, and logging. ```APIDOC ## Configuration Settings ### AI Parameters - `systemPrompt`: Default system instructions for AI models. - `maxTokens`: Maximum response length (1-128000). - `temperature`: Controls creativity of the response (0.0-2.0). - `timeout`: Request timeout duration in seconds (5-300). ### Defaults - `defaultProvider`: The provider to use when none is specified. - `defaultKeyIndex`: The index of the specific API key to use by default. ### Caching - `enableCache`: Boolean flag to enable caching by default. - `defaultCacheTtl`: Default Time-To-Live for cache entries (e.g., D, W, M, Y). ### Logging - `enableLogging`: Boolean flag to enable event logging. - `enableDebugLogging`: Boolean flag to enable verbose debug logging. ``` -------------------------------- ### Get Current Model ID Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-provider.md Retrieve the model ID that is currently configured for the provider instance. ```php echo $provider->getModel(); // claude-sonnet-4-6-20260217 ``` -------------------------------- ### Using OpenRouter with Specific Models Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/providers-reference.md Demonstrates how to specify a particular model when using the OpenRouter provider. This allows for fine-grained control over which AI model processes the request. ```php $result = $ai->ask('Your prompt...', [ 'provider' => 'openrouter', 'model' => 'anthropic/claude-sonnet-4.6', ]); ``` -------------------------------- ### AiWireProvider constructor Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-provider.md Creates an instance of the AiWireProvider class, initializing the connection to a specific AI provider with the provided API key and model configuration. ```APIDOC ## constructor() ### Description Create a provider instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method constructor ### Endpoint None ### Parameters * **providerKey** (string) - Required - Provider key: `anthropic`, `openai`, `google`, `xai`, `openrouter` * **config** (array) - Required - Provider configuration from `AiWire::PROVIDERS` * **apiKey** (string) - Required - API key for the provider * **model** (string) - Required - Model ID to use for requests * **options** (array) - Optional - Options: `timeout` (seconds) ### Request Example ```php $config = [ 'url' => 'https://api.anthropic.com/v1/messages', 'defaultModel' => 'claude-sonnet-4-6-20260217', ]; $provider = new AiWireProvider('anthropic', $config, $apiKey, 'claude-sonnet-4-6-20260217', [ 'timeout' => 30, ]); ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Get Default Provider Key Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-aiwire.md Retrieves the name of the default AI provider key configured in the system. ```php public function getDefaultProviderKey(): string ``` -------------------------------- ### Get Provider Models Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-aiwire.md Retrieves a list of known models for a specific provider, prioritizing updated models. ```php public function getProviderModels(string $providerKey): array ``` -------------------------------- ### generate() Global Options Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/types.md Sets default options for all AI generation blocks, including temperature, caching, token limits, and provider settings. ```php [ 'temperature' => 0.7, // Default temperature for all blocks 'cache' => 'W', // Default cache setting 'maxTokens' => 1024, // Default max tokens 'provider' => 'anthropic', // Default provider 'model' => 'claude-sonnet-4-6-20260217', // Default model 'systemPrompt' => '...', // Default system prompt 'overwrite' => false, // Skip field if has content? 'quiet' => true, // Save without triggering hooks? ] ``` -------------------------------- ### curlGetRequest() Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-provider.md Execute a cURL GET request to the provider API. Returns an array with HTTP response data. ```APIDOC ## curlGetRequest() ### Description Execute a cURL GET request to the provider API. ### Method GET ### Endpoint Not specified (internal method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (string) - Required - The URL to send the request to. - **headers** (array) - Required - The request headers. ### Request Example None ### Response #### Success Response (200) - **array** - HTTP response data. #### Response Example None ``` -------------------------------- ### askWithFallback($msg, $opts) Source: https://github.com/mxmsmnv/aiwire/blob/main/README.md Attempts to get a response from all configured keys and providers until a successful response is received. ```APIDOC ## askWithFallback($msg, $opts) ### Description Tries all keys/providers until success. ### Method Signature `askWithFallback(string $msg, array $opts = [])` ### Parameters #### Message - **$msg** (string) - Required - The message to send to the AI. #### Options - **$opts** (array) - Optional - An array of options to configure the AI call. This can include `fallbackProviders`. See the 'Options' section for available parameters. ### Returns - **array** - A detailed response array containing `success`, `content`, `usage`, and `raw` fields. The response will be from the first successful provider. ``` -------------------------------- ### Using OpenRouter with Different Provider Models Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/providers-reference.md Shows how to leverage OpenRouter to access models from other providers, such as DeepSeek, through a unified interface. This highlights OpenRouter's capability to aggregate diverse models. ```php $result = $ai->ask('Your prompt...', [ 'provider' => 'openrouter', 'model' => 'deepseek/deepseek-v3.2', ]); ``` -------------------------------- ### cacheStats Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md Gets cache statistics including total files, total size, pages count, and expired count. ```APIDOC ## cacheStats() ### Description Get cache statistics: total files, total size, pages count, expired count. ### Method `cacheStats` ### Parameters None ``` -------------------------------- ### Get Cache Statistics Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-cache.md Retrieves statistics about the cache. Use this to monitor cache usage and identify expired entries. ```php public function getStats(): array ``` ```php $stats = $cache->getStats(); echo "Total files: " . $stats['total_files']; echo "Cache size: " . number_format($stats['total_size'] / 1024, 2) . " KB"; echo "Pages with cache: " . $stats['pages']; echo "Expired (cleanup pending): " . $stats['expired']; ``` -------------------------------- ### ask() Request Options Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/types.md This structure defines the parameters for an AI request using the ask() function. It includes AI parameters like system prompt and temperature, key selection options, caching settings, and connection timeouts. ```php [ // AI parameters 'provider' => 'anthropic', // Provider key 'model' => 'claude-sonnet-4-6-20260217', // Model ID 'systemPrompt' => 'You are helpful...', // System instructions 'maxTokens' => 1024, // Max response length 'temperature' => 0.7, // Creativity (0-2) 'history' => [ // Previous messages ['role' => 'user', 'content' => '...'], ['role' => 'assistant', 'content' => '...'], ], // Key selection 'key' => 'sk-ant-...', // Specific API key 'keyIndex' => 0, // Key by index (0-based) // Caching 'cache' => 'W', // TTL: false|'D'|'W'|'M'|'Y'|seconds 'pageId' => 1042, // Page context for cache // Connection 'timeout' => 30, // Seconds ] ``` -------------------------------- ### Simple ask() Flow Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/architecture.md Details the sequence of operations for a simple 'ask()' call, from user code to cache check, provider interaction, and response handling. ```text User Code ↓ $ai->ask($message, $options) ↓ [Check cache] ├─ Cache HIT → return cached result └─ Cache MISS → continue ↓ [Get provider instance] ├─ Check $providerInstances cache └─ Create new AiWireProvider if needed ↓ [$provider->sendMessage()] ├─ Format request per provider type ├─ Execute cURL POST request ├─ Parse JSON response └─ Extract content + usage ↓ [Save to cache] ├─ Build cache key ├─ Write JSON file to disk └─ Return with cached=false ↓ Return result to user ``` -------------------------------- ### askWithFallback() Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md Attempts to use the primary provider and specified keys, then falls back to other enabled providers if necessary. Returns additional fields indicating which provider and key were used. ```APIDOC ## askWithFallback() ### Description Tries all enabled keys for the primary provider, then falls back to other providers. Returns extra fields: `usedProvider`, `usedKeyIndex`, `usedKeyLabel`. ### Method Not applicable (SDK method) ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $ai = $modules->get('AiWire'); $result = $ai->askWithFallback('Summarize this article...', [ 'provider' => 'anthropic', 'fallbackProviders' => ['openai', 'google'], ]); // $result['usedProvider'] tells you which provider actually responded ``` ### Response #### Success Response - **success** (bool) - Indicates if the operation was successful. - **content** (string) - The AI-generated response text. - **message** (string) - A status message or error description. - **usage** (object) - Token usage statistics. - **raw** (object) - The full raw API response from the provider. - **usedProvider** (string) - The key of the provider that was ultimately used. - **usedKeyIndex** (int) - The index of the key used within the provider's configuration. - **usedKeyLabel** (string) - The label of the key used. #### Response Example ```json { "success": true, "content": "This article discusses...", "message": "OK", "usage": { "input_tokens": 50, "output_tokens": 150, "total_tokens": 200 }, "raw": { ... }, "usedProvider": "anthropic", "usedKeyIndex": 0, "usedKeyLabel": "Primary Key" } ``` ``` -------------------------------- ### Cache Methods Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/INDEX.md Methods for interacting with the caching system, including getting cache instances, clearing caches, and viewing statistics. ```APIDOC ## Cache Methods ### Description Methods for interacting with the caching system, including getting cache instances, clearing caches, and viewing statistics. ### Methods - `cache()`: Returns an instance of the cache manager. - `clearCache()`: Clears the cache for a specific page. - `clearAllCache()`: Clears all cached data. - `cacheStats()`: Displays statistics about the cache usage. ``` -------------------------------- ### Bulletproof AI Content Delivery with Fallback Chain Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md This PHP snippet demonstrates how to use AiWire's `askWithFallback` method to deliver AI-generated content. It first checks for existing content, then attempts to generate new content using a fallback chain of providers (Anthropic, OpenAI, Google). The result is saved for future requests and logged for analysis. ```php // site/templates/product.php — bulletproof AI content delivery $ai = $modules->get('AiWire'); // Check if content already exists $existing = $ai->loadFrom($page, 'ai_overview'); if ($existing) { echo $existing; return; } // Fallback chain: Anthropic key #0 → key #1 → OpenAI → Google $result = $ai->askWithFallback( "Write an overview of {$page->title}...", [ 'provider' => 'anthropic', 'fallbackProviders' => ['openai', 'google'], 'maxTokens' => 500, 'temperature' => 0.6, 'timeout' => 15, 'cache' => 'W', ] ); if ($result['success']) { // Save to field for future requests $ai->saveTo($page, 'ai_overview', $result); echo $result['content']; // Log which provider/key actually answered wire('log')->save('ai-provider-usage', "Page {$page->id}: provider={$result['usedProvider']}, " . "key={$result['usedKeyLabel']} (#{$result['usedKeyIndex']}), " . "tokens={$result['usage']['total_tokens']}" ); } else { echo "

Content being prepared...

"; } ``` -------------------------------- ### Example AI-Generated Brand Content Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md Illustrative content for 'ai_brand_history', 'ai_brand_highlights', and 'ai_brand_faq' fields, as populated by the AiWire module for a brand page. ```text ai_brand_history: "Founded in 1776 in Reims, France, Louis Roederer remains one of the last major family-owned champagne houses. Under the direction of Frédéric Rouzaud, the seventh generation, the house cultivates 240 hectares of Grand and Premier Cru vineyards — an unusual commitment to estate-grown fruit..." ai_brand_highlights: "1. Cristal 2015 stands as the flagship — a prestige cuvée with six years of lees aging 2. The Brut Premier NV offers exceptional value as an everyday champagne 3. Unlike most houses, 70% of their grapes are estate-grown..." ai_brand_faq: "**Q: Where is Louis Roederer from?** A: Reims, Champagne, France — founded in 1776. **Q: What is their flagship product?** A: Cristal, originally created in 1876 for Tsar Alexander II..." ``` -------------------------------- ### Chat Response Example Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md The `chat` method returns only the text content of the AI's response or an empty string if an error occurs. ```php $text = $ai->chat('Summarize this'); // "Here is a summary..." ``` -------------------------------- ### Handling No Active Key Configuration Error Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/errors.md This error indicates that a provider was selected, but no API keys are currently enabled for it. Enable at least one API key for the specified provider. ```php [ 'success' => false, 'message' => "No active provider found for 'openai'", ] ``` -------------------------------- ### Handling Rate Limits with Fallback Providers Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/errors.md Use `askWithFallback()` to automatically retry requests with alternative providers when rate limits or other errors occur. This improves request reliability. ```php $result = $ai->askWithFallback('Your prompt...', [ 'provider' => 'anthropic', 'fallbackProviders' => ['openai', 'google'], ]); if (!$result['success']) { echo "All providers failed"; } else { echo "Used: " . $result['usedProvider']; } ``` -------------------------------- ### Get AiWire Module Info Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-aiwire.md Retrieves metadata about the AiWire module, such as its version, requirements, and capabilities. This is typically used for module introspection. ```php public static function getModuleInfo(): array ``` -------------------------------- ### Ask AI and Save to Multiple Fields (Batch Prompts) Source: https://github.com/mxmsmnv/aiwire/blob/main/DOCUMENTATION.md For distinct prompts per field, use `askAndSave` with an associative array mapping field names to their specific prompts. This allows for tailored AI generation for each field. ```php $ai->askAndSave($page, [ 'seo_desc' => 'Write SEO description for: ...', 'ai_summary' => 'Summarize: ...', 'ai_keywords' => 'Extract 5 keywords from: ...', ]); ``` -------------------------------- ### Get Configured Provider Keys Source: https://github.com/mxmsmnv/aiwire/blob/main/_autodocs/api-reference-aiwire.md Retrieves all API keys configured for a specific AI provider. This is useful for managing and iterating through available keys. ```php public function getProviderKeys(string $providerKey): array $keys = $ai->getProviderKeys('anthropic'); foreach ($keys as $i => $keyData) { if ($keyData['enabled']) { echo "Key #$i: " . $keyData['label'] . "\n"; } } ``` -------------------------------- ### Simple Chat Request Source: https://github.com/mxmsmnv/aiwire/blob/main/README.md Perform a simple chat request to an AI provider and get text-only output. This is the most basic way to interact with the AiWire module. ```php $ai = $modules->get('AiWire'); // Simple — returns text only echo $ai->chat('What is ProcessWire CMS?'); ```