|
9 | 9 |
|
10 | 10 | namespace WordPress\AI; |
11 | 11 |
|
| 12 | +use Throwable; |
| 13 | +use WordPress\AI_Client\AI_Client; |
| 14 | + |
12 | 15 | /** |
13 | 16 | * Normalizes the content by cleaning it and removing unwanted HTML tags. |
14 | 17 | * |
@@ -155,3 +158,66 @@ function get_preferred_models(): array { |
155 | 158 | */ |
156 | 159 | return (array) apply_filters( 'ai_preferred_models', $preferred_models ); |
157 | 160 | } |
| 161 | + |
| 162 | +/** |
| 163 | + * Checks if we have AI credentials set. |
| 164 | + * |
| 165 | + * @since 0.1.0 |
| 166 | + * |
| 167 | + * @return bool True if we have AI credentials, false otherwise. |
| 168 | + */ |
| 169 | +function has_ai_credentials(): bool { |
| 170 | + $credentials = get_option( 'wp_ai_client_provider_credentials', array() ); |
| 171 | + |
| 172 | + // If there are no credentials, return false. |
| 173 | + if ( ! is_array( $credentials ) || empty( $credentials ) ) { |
| 174 | + return false; |
| 175 | + } |
| 176 | + |
| 177 | + // If all of the AI keys are empty, return false; otherwise, return true. |
| 178 | + return ! empty( |
| 179 | + array_filter( |
| 180 | + $credentials, |
| 181 | + static function ( $api_key ): bool { |
| 182 | + return is_string( $api_key ) && '' !== $api_key; |
| 183 | + } |
| 184 | + ) |
| 185 | + ); |
| 186 | +} |
| 187 | + |
| 188 | +/** |
| 189 | + * Checks if we have valid AI credentials. |
| 190 | + * |
| 191 | + * @since 0.1.0 |
| 192 | + * |
| 193 | + * @return bool True if we have valid AI credentials, false otherwise. |
| 194 | + */ |
| 195 | +function has_valid_ai_credentials(): bool { |
| 196 | + // If we have no AI credentials, return false. |
| 197 | + if ( ! has_ai_credentials() ) { |
| 198 | + return false; |
| 199 | + } |
| 200 | + |
| 201 | + /** |
| 202 | + * Filters whether valid AI credentials are available. |
| 203 | + * |
| 204 | + * Allows overriding the credentials check, useful for testing. |
| 205 | + * |
| 206 | + * @since 0.1.0 |
| 207 | + * @hook ai_pre_has_valid_credentials_check |
| 208 | + * |
| 209 | + * @param bool|null $has_valid_credentials Whether valid credentials are available. Return null to use default check. |
| 210 | + * @return bool|null True if valid credentials are available, false otherwise, or null to use default check. |
| 211 | + */ |
| 212 | + $valid = apply_filters( 'ai_pre_has_valid_credentials_check', null ); |
| 213 | + if ( null !== $valid ) { |
| 214 | + return (bool) $valid; |
| 215 | + } |
| 216 | + |
| 217 | + // See if we have credentials that give us access to generate text. |
| 218 | + try { |
| 219 | + return AI_Client::prompt( 'Test' )->is_supported_for_text_generation(); |
| 220 | + } catch ( Throwable $t ) { |
| 221 | + return false; |
| 222 | + } |
| 223 | +} |
0 commit comments