### 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 "
| Provider | Response | Tokens |
|---|---|---|
| {$provider} | {$content} | {$tokens} |
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?'); ```