If you have multiple API keys for the same service and would like to rotate between them (round robin), there is an addon specifically designed for that: Dynamic Keys.
If you want your user to use their own API keys you will need to write the code to allow them to write their own API Key somewhere. For example, you could let them add it directly into their WordPress Profile.
As for AI Engine, you can inject this API Key in many different ways. In the Filters, pay attention to the mwai_ai_query filter; it’s the one used right before the request is sent to the AI. Here is a simple example:
add_filter( 'mwai_ai_query', function ( $query ) {
$apiKey = get_user_meta( get_current_user_id(), 'apiKey', true );
$query->setApiKey( $apiKey );
return $query;
}, 10, 2 );
You can also have your API keys defined outside of the plugin settings and load them dynamically at request time.
For example, the key could be stored in a PHP constant, but it could also be fetched from a third-party server if your keys are generated dynamically on the fly.
<?php
define( 'MWAI_OPENAI_API_KEY', 'sk-your-key' );
define( 'MWAI_ANTHROPIC_API_KEY', 'your-anthropic-key' );
define( 'MWAI_GOOGLE_API_KEY', 'your-google-key' );
add_filter( 'mwai_ai_query', function( $query ) {
global $mwai_core;
// Get the environment to check its type
$envs = $mwai_core->get_option( 'ai_envs', [] );
$env = null;
foreach ( $envs as $e ) {
if ( $e['id'] === $query->envId ) {
$env = $e;
break;
}
}
if ( $env ) {
switch ( $env['type'] ) {
case 'openai':
$query->apiKey = MWAI_OPENAI_API_KEY ?? null;
break;
case 'anthropic':
$query->apiKey = MWAI_ANTHROPIC_API_KEY ?? null;
break;
case 'google':
$query->apiKey = MWAI_GOOGLE_API_KEY ?? null;
break;
}
}
return $query;
}, 10, 1 );
add_filter( 'mwai_ai_embeddings_query', function( $query ) {
// Same logic for embeddings
return $query;
}, 10, 1 );