From 83489346bac47b1fb0dfb7e8418b83d2031ae1d5 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Mon, 16 Nov 2026 13:49:52 +0000 Subject: [PATCH 01/16] Build/Test Tools: Add live AI provider tests for the core abilities. Adds `Tests_AI_Client_LiveProviders`, which asks the Anthropic, Google and OpenAI providers questions they can only answer by calling the core abilities through the AI Client. Every provider is tested with each core ability on its own and with all of them together. The tests send real requests, so they are in the `external-http` group, and the tests of a provider are skipped unless its API key is in the `ANTHROPIC_API_KEY`, `GOOGLE_API_KEY` or `OPENAI_API_KEY` environment variable. A `WP_TESTS_AI_{PROVIDER}_MODEL` variable selects a model other than the default one of the provider. The provider packages become Composer development dependencies, and the local Docker environment passes the variables to the PHP container when they are set. --- .env.example | 15 + composer.json | 5 +- docker-compose.yml | 7 + .../ai-client/wpAiClientLiveProviders.php | 274 ++++++++++++++++++ 4 files changed, 300 insertions(+), 1 deletion(-) create mode 100644 tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php diff --git a/.env.example b/.env.example index bdd47dedb82d5..110f8a07dfd71 100644 --- a/.env.example +++ b/.env.example @@ -84,6 +84,21 @@ LOCAL_WP_ENVIRONMENT_TYPE=local LOCAL_WP_DEVELOPMENT_MODE=core LOCAL_WP_TESTS_DOMAIN=example.org +## +# API keys for the live AI provider tests, which send real requests: +# +# npm run test:php -- --group external-http --filter Tests_AI_Client_LiveProviders +# +# The tests of a provider are skipped while its key is not set. A provider uses its +# default model unless its `WP_TESTS_AI_*_MODEL` variable names another one. +## +# ANTHROPIC_API_KEY= +# GOOGLE_API_KEY= +# OPENAI_API_KEY= +# WP_TESTS_AI_ANTHROPIC_MODEL= +# WP_TESTS_AI_GOOGLE_MODEL= +# WP_TESTS_AI_OPENAI_MODEL= + ## # This silences the tips output by the dotenv package. ## diff --git a/composer.json b/composer.json index 77226897cee1c..baae88dd5defa 100644 --- a/composer.json +++ b/composer.json @@ -55,7 +55,10 @@ "phpstan/phpstan": "2.3.7", "phpstan/phpstan-phpunit": "2.1.2", "phpstan/phpstan-strict-rules": "2.1.2", - "yoast/phpunit-polyfills": "^1.1.0" + "yoast/phpunit-polyfills": "^1.1.0", + "wordpress/ai-provider-for-anthropic": "^1.0.5", + "wordpress/ai-provider-for-google": "^1.2.1", + "wordpress/ai-provider-for-openai": "^1.2.0" }, "config": { "audit": { "ignore": [ "GHSA-hmqg-cxww-wqhq", "PKSA-rdkp-vv9z-mjkg" ] }, diff --git a/docker-compose.yml b/docker-compose.yml index 62bce43174293..3d9ba07726e04 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -49,6 +49,13 @@ services: GITHUB_REF: ${GITHUB_REF-false} GITHUB_EVENT_NAME: ${GITHUB_EVENT_NAME-false} HOST_PATH: ${PWD-}/${LOCAL_DIR-src} + # Passed through for the live AI provider tests, and only when they are set. + ANTHROPIC_API_KEY: + GOOGLE_API_KEY: + OPENAI_API_KEY: + WP_TESTS_AI_ANTHROPIC_MODEL: + WP_TESTS_AI_GOOGLE_MODEL: + WP_TESTS_AI_OPENAI_MODEL: volumes: - ./tools/local-env/php-config.ini:/usr/local/etc/php/conf.d/php-config.ini diff --git a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php new file mode 100644 index 0000000000000..70943ae1b2734 --- /dev/null +++ b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php @@ -0,0 +1,274 @@ + 'WordPress\AnthropicAiProvider\Provider\AnthropicProvider', + 'google' => 'WordPress\GoogleAiProvider\Provider\GoogleProvider', + 'openai' => 'WordPress\OpenAiAiProvider\Provider\OpenAiProvider', + ); + + /** + * For each core ability, a question no other ability answers and the value the answer must contain. + */ + private const QUESTIONS = array( + 'core/get-site-info' => array( 'What is the character encoding of this site?', 'UTF-8' ), + 'core/get-user-info' => array( 'What is my display name?', 'Barnaby Quillfeather' ), + 'core/get-environment-info' => array( 'Which PHP version does this site run?', PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION ), + 'core/settings-get' => array( 'What is the timezone setting of this site?', 'Pacific/Chatham' ), + 'core/users-query' => array( 'What is the display name of the user with the username "live_provider_editor"?', 'Marigold Featherstone' ), + 'core/content-query' => array( 'What is the title of the post with the slug "live-provider-post"?', 'Quokka Lighthouse Notes' ), + ); + + /** + * ID of the administrator who asks the questions. + * + * @var int + */ + private static $admin_id; + + /** + * Creates the content the questions are about and registers the core abilities. + * + * @param WP_UnitTest_Factory $factory Factory instance. + */ + public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void { + self::$admin_id = $factory->user->create( + array( + 'role' => 'administrator', + 'display_name' => 'Barnaby Quillfeather', + ) + ); + + // On multisite, only a super admin may read the environment information. + if ( is_multisite() ) { + grant_super_admin( self::$admin_id ); + } + + $factory->user->create( + array( + 'role' => 'editor', + 'user_login' => 'live_provider_editor', + 'display_name' => 'Marigold Featherstone', + ) + ); + $factory->post->create( + array( + 'post_author' => self::$admin_id, + 'post_name' => 'live-provider-post', + 'post_title' => 'Quokka Lighthouse Notes', + ) + ); + + foreach ( wp_get_abilities() as $ability ) { + wp_unregister_ability( $ability->get_name() ); + } + foreach ( wp_get_ability_categories() as $ability_category ) { + wp_unregister_ability_category( $ability_category->get_slug() ); + } + + remove_action( 'wp_abilities_api_categories_init', '_unhook_core_ability_categories_registration', 1 ); + remove_action( 'wp_abilities_api_init', '_unhook_core_abilities_registration', 1 ); + + add_action( 'wp_abilities_api_categories_init', 'wp_register_core_ability_categories' ); + add_action( 'wp_abilities_api_init', 'wp_register_core_abilities' ); + do_action( 'wp_abilities_api_categories_init' ); + do_action( 'wp_abilities_api_init' ); + + /* + * Restore the hooks right away instead of after the class. The first test of a run + * snapshots the hooks and every test resets them to that snapshot, so changes left + * here would leak into every later test whenever this class runs first. + */ + remove_action( 'wp_abilities_api_categories_init', 'wp_register_core_ability_categories' ); + remove_action( 'wp_abilities_api_init', 'wp_register_core_abilities' ); + add_action( 'wp_abilities_api_categories_init', '_unhook_core_ability_categories_registration', 1 ); + add_action( 'wp_abilities_api_init', '_unhook_core_abilities_registration', 1 ); + } + + /** + * Revokes the super admin status and cleans up the registered abilities and categories. + */ + public static function wpTearDownAfterClass(): void { + if ( is_multisite() ) { + revoke_super_admin( self::$admin_id ); + } + + foreach ( wp_get_abilities() as $ability ) { + wp_unregister_ability( $ability->get_name() ); + } + foreach ( wp_get_ability_categories() as $ability_category ) { + wp_unregister_ability_category( $ability_category->get_slug() ); + } + } + + /** + * Signs in the administrator, sets the option one of the questions is about and allows slow responses. + */ + public function set_up(): void { + parent::set_up(); + + wp_set_current_user( self::$admin_id ); + update_option( 'timezone_string', 'Pacific/Chatham' ); + + // The request that lists the models of a provider has no timeout of its own. + add_filter( 'http_request_timeout', static fn () => 30 ); + add_filter( 'wp_ai_client_default_request_timeout', static fn () => 120.0 ); + } + + /** + * Tests that a provider answers questions by calling the core abilities it is given. + * + * @dataProvider data_providers_and_abilities + * + * @param string $provider Provider ID. + * @param string[] $abilities Names of the abilities given to the model. + */ + public function test_provider_answers_with_core_abilities( string $provider, array $abilities ): void { + $questions = array_intersect_key( self::QUESTIONS, array_flip( $abilities ) ); + $called = array(); + $answer = $this->ask( $provider, $abilities, implode( ' ', array_column( $questions, 0 ) ), $called ); + + // A model may quote a value as it is in the JSON it received, where slashes are escaped. + $answer = str_replace( '\/', '/', $answer ); + $missing = array_filter( array_column( $questions, 1 ), static fn ( $value ) => false === stripos( $answer, $value ) ); + + $this->assertSameSets( $abilities, array_unique( $called ), 'The model should call every ability it is given.' ); + $this->assertSame( array(), array_values( $missing ), "The answer should contain every expected value. Answer: $answer" ); + } + + /** + * Data provider. + * + * For every provider, each core ability on its own and then all of them together. + * + * @return array + */ + public static function data_providers_and_abilities(): array { + $data = array(); + + foreach ( array_keys( self::PROVIDERS ) as $provider ) { + foreach ( array_keys( self::QUESTIONS ) as $ability ) { + $data[ "$provider, $ability" ] = array( $provider, array( $ability ) ); + } + $data[ "$provider, all abilities" ] = array( $provider, array_keys( self::QUESTIONS ) ); + } + + return $data; + } + + /** + * Asks a provider a question and runs the abilities the model calls until it answers. + * + * The test is skipped when the provider has no API key or is temporarily unavailable, + * and fails when the provider rejects the key. + * + * @param string $provider Provider ID. + * @param string[] $abilities Names of the abilities given to the model. + * @param string $question The question. + * @param string[] $called Receives the name of the ability of each call. + * @return string The answer. + */ + private function ask( string $provider, array $abilities, string $question, array &$called ): string { + $key_name = strtoupper( $provider ) . '_API_KEY'; + if ( ! getenv( $key_name ) ) { + $this->markTestSkipped( "The $key_name environment variable is not set." ); + } + if ( ! class_exists( self::PROVIDERS[ $provider ] ) ) { + $this->markTestSkipped( 'The AI provider packages are not installed. Run `composer update`.' ); + } + + // A registry of its own keeps the provider out of the default registry other tests use. + $registry = new ProviderRegistry(); + $registry->registerProvider( self::PROVIDERS[ $provider ] ); + + /* + * The AI Client reports a provider whose models cannot be listed as one without models, + * so list them here to get the reason. A successful list is cached for the requests below. + */ + try { + self::PROVIDERS[ $provider ]::modelMetadataDirectory()->listModelMetadata(); + } catch ( Exception $e ) { + if ( $e instanceof ClientException && 429 !== $e->getCode() ) { + $this->fail( "The provider rejected the $key_name: " . $e->getMessage() ); + } + $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); + } + + $resolver = new WP_AI_Client_Ability_Function_Resolver( ...$abilities ); + $messages = array( new UserMessage( array( new MessagePart( $question ) ) ) ); + + for ( $round = 0; $round < 6; $round++ ) { + $builder = ( new WP_AI_Client_Prompt_Builder( $registry, $messages ) ) + ->using_provider( $provider ) + ->using_system_instruction( 'Answer every question with the abilities. Quote the values they return unchanged.' ) + ->using_abilities( ...$abilities ); + + $model = getenv( 'WP_TESTS_AI_' . strtoupper( $provider ) . '_MODEL' ); + if ( $model ) { + $builder->using_model_preference( $model ); + } + + $result = $builder->generate_text_result(); + + if ( is_wp_error( $result ) ) { + $status = $result->get_error_data()['status'] ?? 0; + if ( 429 === $status || $status >= 500 ) { + $this->markTestSkipped( "The provider is unavailable ($status): " . $result->get_error_message() ); + } + $this->fail( "The request failed ($status): " . $result->get_error_message() ); + } + + // OpenAI returns each function call as its own candidate, so keep them all, not just toMessage(). + $has_calls = false; + foreach ( $result->getCandidates() as $candidate ) { + $message = $candidate->getMessage(); + $messages[] = $message; + + if ( ! $resolver->has_ability_calls( $message ) ) { + continue; + } + + foreach ( $message->getParts() as $part ) { + if ( $part->getFunctionCall() ) { + $called[] = WP_AI_Client_Ability_Function_Resolver::function_name_to_ability_name( $part->getFunctionCall()->getName() ); + } + } + $messages[] = $resolver->execute_abilities( $message ); + $has_calls = true; + } + + if ( ! $has_calls ) { + return implode( "\n", $result->toTexts() ); + } + } + + $this->fail( 'The model kept calling abilities without answering.' ); + } +} From fdcfa19ea4df2412a4420bb62eaa5836c3f3f105 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Mon, 16 Nov 2026 15:26:21 +0000 Subject: [PATCH 02/16] Build/Test Tools: Add the ticket number to the live AI provider tests. See #66707. --- tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php index 70943ae1b2734..c1226630a6717 100644 --- a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php +++ b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php @@ -145,6 +145,8 @@ public function set_up(): void { /** * Tests that a provider answers questions by calling the core abilities it is given. * + * @ticket 66707 + * * @dataProvider data_providers_and_abilities * * @param string $provider Provider ID. From a396057971cf5ce949a36574475d5b76dbee8a81 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Mon, 16 Nov 2026 19:23:57 +0000 Subject: [PATCH 03/16] Build/Test Tools: Skip the live AI provider tests only when the provider is unavailable. The tests are now skipped only on a rate limit, a server error of the provider or a network error. Any other error fails them, including a response the provider changed and a disabled AI Client. See #66707. --- .../ai-client/wpAiClientLiveProviders.php | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php index c1226630a6717..bc52bf6667b71 100644 --- a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php +++ b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php @@ -21,6 +21,8 @@ use WordPress\AiClient\Messages\DTO\MessagePart; use WordPress\AiClient\Messages\DTO\UserMessage; use WordPress\AiClient\Providers\Http\Exception\ClientException; +use WordPress\AiClient\Providers\Http\Exception\NetworkException; +use WordPress\AiClient\Providers\Http\Exception\ServerException; use WordPress\AiClient\Providers\ProviderRegistry; class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { @@ -188,8 +190,8 @@ public static function data_providers_and_abilities(): array { /** * Asks a provider a question and runs the abilities the model calls until it answers. * - * The test is skipped when the provider has no API key or is temporarily unavailable, - * and fails when the provider rejects the key. + * The test is skipped when the provider has no API key or is unavailable: it limits the + * requests, has a server error or cannot be reached. Every other error fails the test. * * @param string $provider Provider ID. * @param string[] $abilities Names of the abilities given to the model. @@ -213,14 +215,17 @@ private function ask( string $provider, array $abilities, string $question, arra /* * The AI Client reports a provider whose models cannot be listed as one without models, * so list them here to get the reason. A successful list is cached for the requests below. + * Any other exception, such as a response the provider changed, is an error of the test. */ try { self::PROVIDERS[ $provider ]::modelMetadataDirectory()->listModelMetadata(); - } catch ( Exception $e ) { - if ( $e instanceof ClientException && 429 !== $e->getCode() ) { - $this->fail( "The provider rejected the $key_name: " . $e->getMessage() ); - } + } catch ( NetworkException | ServerException $e ) { $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); + } catch ( ClientException $e ) { + if ( 429 === $e->getCode() ) { + $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); + } + $this->fail( "The provider rejected the $key_name: " . $e->getMessage() ); } $resolver = new WP_AI_Client_Ability_Function_Resolver( ...$abilities ); @@ -240,11 +245,14 @@ private function ask( string $provider, array $abilities, string $question, arra $result = $builder->generate_text_result(); if ( is_wp_error( $result ) ) { - $status = $result->get_error_data()['status'] ?? 0; - if ( 429 === $status || $status >= 500 ) { - $this->markTestSkipped( "The provider is unavailable ($status): " . $result->get_error_message() ); + $status = $result->get_error_data()['status'] ?? 0; + $message = "($status): " . $result->get_error_message(); + + // Only a rate limit, a server error of the provider and a network error skip the test. + if ( 429 === $status || in_array( $result->get_error_code(), array( 'prompt_network_error', 'prompt_upstream_server_error' ), true ) ) { + $this->markTestSkipped( "The provider is unavailable $message" ); } - $this->fail( "The request failed ($status): " . $result->get_error_message() ); + $this->fail( "The request failed $message" ); } // OpenAI returns each function call as its own candidate, so keep them all, not just toMessage(). From c28ea0bc4641081ea02988fdcd1077ad850df9b1 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Mon, 16 Nov 2026 20:17:27 +0000 Subject: [PATCH 04/16] Build/Test Tools: Use key names of their own in the live AI provider tests. The tests now read the API keys from `WP_TESTS_AI_ANTHROPIC_API_KEY`, `WP_TESTS_AI_GOOGLE_API_KEY` and `WP_TESTS_AI_OPENAI_API_KEY`. A key set for a provider tool or for the Connectors does not start them, and the local site does not use a key set for the tests. A model name the provider does not list now fails the test, and an ability only counts as called when it ran without an error. The provider packages are pinned to the versions the tests ran with. See #66707. --- .env.example | 8 +- composer.json | 6 +- docker-compose.yml | 7 +- .../ai-client/wpAiClientLiveProviders.php | 126 ++++++++++-------- 4 files changed, 84 insertions(+), 63 deletions(-) diff --git a/.env.example b/.env.example index 110f8a07dfd71..be8cc70089eba 100644 --- a/.env.example +++ b/.env.example @@ -91,10 +91,12 @@ LOCAL_WP_TESTS_DOMAIN=example.org # # The tests of a provider are skipped while its key is not set. A provider uses its # default model unless its `WP_TESTS_AI_*_MODEL` variable names another one. +# +# Only the tests read these names, so the keys are not used by the local site. ## -# ANTHROPIC_API_KEY= -# GOOGLE_API_KEY= -# OPENAI_API_KEY= +# WP_TESTS_AI_ANTHROPIC_API_KEY= +# WP_TESTS_AI_GOOGLE_API_KEY= +# WP_TESTS_AI_OPENAI_API_KEY= # WP_TESTS_AI_ANTHROPIC_MODEL= # WP_TESTS_AI_GOOGLE_MODEL= # WP_TESTS_AI_OPENAI_MODEL= diff --git a/composer.json b/composer.json index baae88dd5defa..2ebb708d6ccc7 100644 --- a/composer.json +++ b/composer.json @@ -56,9 +56,9 @@ "phpstan/phpstan-phpunit": "2.1.2", "phpstan/phpstan-strict-rules": "2.1.2", "yoast/phpunit-polyfills": "^1.1.0", - "wordpress/ai-provider-for-anthropic": "^1.0.5", - "wordpress/ai-provider-for-google": "^1.2.1", - "wordpress/ai-provider-for-openai": "^1.2.0" + "wordpress/ai-provider-for-anthropic": "1.0.5", + "wordpress/ai-provider-for-google": "1.2.1", + "wordpress/ai-provider-for-openai": "1.2.0" }, "config": { "audit": { "ignore": [ "GHSA-hmqg-cxww-wqhq", "PKSA-rdkp-vv9z-mjkg" ] }, diff --git a/docker-compose.yml b/docker-compose.yml index 3d9ba07726e04..629a8dd97a046 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -50,9 +50,10 @@ services: GITHUB_EVENT_NAME: ${GITHUB_EVENT_NAME-false} HOST_PATH: ${PWD-}/${LOCAL_DIR-src} # Passed through for the live AI provider tests, and only when they are set. - ANTHROPIC_API_KEY: - GOOGLE_API_KEY: - OPENAI_API_KEY: + # Only the tests read these names, so the keys are not used by the local site. + WP_TESTS_AI_ANTHROPIC_API_KEY: + WP_TESTS_AI_GOOGLE_API_KEY: + WP_TESTS_AI_OPENAI_API_KEY: WP_TESTS_AI_ANTHROPIC_MODEL: WP_TESTS_AI_GOOGLE_MODEL: WP_TESTS_AI_OPENAI_MODEL: diff --git a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php index bc52bf6667b71..523f1b0a28446 100644 --- a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php +++ b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php @@ -2,10 +2,14 @@ /** * Tests that live AI providers can call the core abilities through the AI Client. * - * These tests send real requests. The tests of a provider only run when its API key is in - * the `ANTHROPIC_API_KEY`, `GOOGLE_API_KEY` or `OPENAI_API_KEY` environment variable: + * These tests send real requests. The tests of a provider only run when its API key is in the + * `WP_TESTS_AI_ANTHROPIC_API_KEY`, `WP_TESTS_AI_GOOGLE_API_KEY` or `WP_TESTS_AI_OPENAI_API_KEY` + * environment variable: * - * ANTHROPIC_API_KEY=… vendor/bin/phpunit --group external-http --filter Tests_AI_Client_LiveProviders + * WP_TESTS_AI_ANTHROPIC_API_KEY=… vendor/bin/phpunit --group external-http --filter Tests_AI_Client_LiveProviders + * + * The provider tools and the Connectors read other names, such as `ANTHROPIC_API_KEY`, so a key + * set for them does not start these tests, and a key set for these tests is not used by a site. * * A provider uses its default model, unless a `WP_TESTS_AI_{PROVIDER}_MODEL` environment * variable, such as `WP_TESTS_AI_GOOGLE_MODEL`, names another one. @@ -20,10 +24,14 @@ use WordPress\AiClient\Messages\DTO\MessagePart; use WordPress\AiClient\Messages\DTO\UserMessage; +use WordPress\AiClient\Providers\Http\DTO\ApiKeyRequestAuthentication; use WordPress\AiClient\Providers\Http\Exception\ClientException; use WordPress\AiClient\Providers\Http\Exception\NetworkException; use WordPress\AiClient\Providers\Http\Exception\ServerException; use WordPress\AiClient\Providers\ProviderRegistry; +use WordPress\AnthropicAiProvider\Provider\AnthropicProvider; +use WordPress\GoogleAiProvider\Provider\GoogleProvider; +use WordPress\OpenAiAiProvider\Provider\OpenAiProvider; class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { @@ -31,9 +39,9 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { * Provider classes keyed by provider ID. */ private const PROVIDERS = array( - 'anthropic' => 'WordPress\AnthropicAiProvider\Provider\AnthropicProvider', - 'google' => 'WordPress\GoogleAiProvider\Provider\GoogleProvider', - 'openai' => 'WordPress\OpenAiAiProvider\Provider\OpenAiProvider', + 'anthropic' => AnthropicProvider::class, + 'google' => GoogleProvider::class, + 'openai' => OpenAiProvider::class, ); /** @@ -48,6 +56,11 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { 'core/content-query' => array( 'What is the title of the post with the slug "live-provider-post"?', 'Quokka Lighthouse Notes' ), ); + /** + * How many requests a model may take to answer. + */ + private const MAX_ROUNDS = 6; + /** * ID of the administrator who asks the questions. * @@ -61,6 +74,8 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { * @param WP_UnitTest_Factory $factory Factory instance. */ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void { + global $wp_current_filter; + self::$admin_id = $factory->user->create( array( 'role' => 'administrator', @@ -82,9 +97,8 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void ); $factory->post->create( array( - 'post_author' => self::$admin_id, - 'post_name' => 'live-provider-post', - 'post_title' => 'Quokka Lighthouse Notes', + 'post_name' => 'live-provider-post', + 'post_title' => 'Quokka Lighthouse Notes', ) ); @@ -95,23 +109,14 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void wp_unregister_ability_category( $ability_category->get_slug() ); } - remove_action( 'wp_abilities_api_categories_init', '_unhook_core_ability_categories_registration', 1 ); - remove_action( 'wp_abilities_api_init', '_unhook_core_abilities_registration', 1 ); - - add_action( 'wp_abilities_api_categories_init', 'wp_register_core_ability_categories' ); - add_action( 'wp_abilities_api_init', 'wp_register_core_abilities' ); - do_action( 'wp_abilities_api_categories_init' ); - do_action( 'wp_abilities_api_init' ); + // The core abilities can only be registered while their registration actions run. + $wp_current_filter[] = 'wp_abilities_api_categories_init'; + wp_register_core_ability_categories(); + array_pop( $wp_current_filter ); - /* - * Restore the hooks right away instead of after the class. The first test of a run - * snapshots the hooks and every test resets them to that snapshot, so changes left - * here would leak into every later test whenever this class runs first. - */ - remove_action( 'wp_abilities_api_categories_init', 'wp_register_core_ability_categories' ); - remove_action( 'wp_abilities_api_init', 'wp_register_core_abilities' ); - add_action( 'wp_abilities_api_categories_init', '_unhook_core_ability_categories_registration', 1 ); - add_action( 'wp_abilities_api_init', '_unhook_core_abilities_registration', 1 ); + $wp_current_filter[] = 'wp_abilities_api_init'; + wp_register_core_abilities(); + array_pop( $wp_current_filter ); } /** @@ -156,15 +161,16 @@ public function set_up(): void { */ public function test_provider_answers_with_core_abilities( string $provider, array $abilities ): void { $questions = array_intersect_key( self::QUESTIONS, array_flip( $abilities ) ); - $called = array(); - $answer = $this->ask( $provider, $abilities, implode( ' ', array_column( $questions, 0 ) ), $called ); + + list( $answer, $called, $model ) = $this->ask( $provider, $abilities, implode( ' ', array_column( $questions, 0 ) ) ); // A model may quote a value as it is in the JSON it received, where slashes are escaped. $answer = str_replace( '\/', '/', $answer ); $missing = array_filter( array_column( $questions, 1 ), static fn ( $value ) => false === stripos( $answer, $value ) ); + $context = "Model: $model. Answer: $answer"; - $this->assertSameSets( $abilities, array_unique( $called ), 'The model should call every ability it is given.' ); - $this->assertSame( array(), array_values( $missing ), "The answer should contain every expected value. Answer: $answer" ); + $this->assertSameSets( $abilities, $called, "Every ability given to the model should run without an error. $context" ); + $this->assertSame( array(), $missing, "The answer should contain every expected value. $context" ); } /** @@ -196,21 +202,26 @@ public static function data_providers_and_abilities(): array { * @param string $provider Provider ID. * @param string[] $abilities Names of the abilities given to the model. * @param string $question The question. - * @param string[] $called Receives the name of the ability of each call. - * @return string The answer. + * @return array{0: string, 1: string[], 2: string} The answer, the names of the abilities + * that ran without an error and the model ID. */ - private function ask( string $provider, array $abilities, string $question, array &$called ): string { - $key_name = strtoupper( $provider ) . '_API_KEY'; - if ( ! getenv( $key_name ) ) { + private function ask( string $provider, array $abilities, string $question ): array { + $provider_class = self::PROVIDERS[ $provider ]; + $key_name = 'WP_TESTS_AI_' . strtoupper( $provider ) . '_API_KEY'; + $model_name = 'WP_TESTS_AI_' . strtoupper( $provider ) . '_MODEL'; + $api_key = getenv( $key_name ); + $model = getenv( $model_name ); + + if ( ! $api_key ) { $this->markTestSkipped( "The $key_name environment variable is not set." ); } - if ( ! class_exists( self::PROVIDERS[ $provider ] ) ) { + if ( ! class_exists( $provider_class ) ) { $this->markTestSkipped( 'The AI provider packages are not installed. Run `composer update`.' ); } - // A registry of its own keeps the provider out of the default registry other tests use. $registry = new ProviderRegistry(); - $registry->registerProvider( self::PROVIDERS[ $provider ] ); + $registry->registerProvider( $provider_class ); + $registry->setProviderRequestAuthentication( $provider, new ApiKeyRequestAuthentication( $api_key ) ); /* * The AI Client reports a provider whose models cannot be listed as one without models, @@ -218,26 +229,31 @@ private function ask( string $provider, array $abilities, string $question, arra * Any other exception, such as a response the provider changed, is an error of the test. */ try { - self::PROVIDERS[ $provider ]::modelMetadataDirectory()->listModelMetadata(); + $models = $provider_class::modelMetadataDirectory()->listModelMetadata(); } catch ( NetworkException | ServerException $e ) { $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); } catch ( ClientException $e ) { if ( 429 === $e->getCode() ) { $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); } - $this->fail( "The provider rejected the $key_name: " . $e->getMessage() ); + $this->fail( "The model list request failed, check the $key_name: " . $e->getMessage() ); + } + + // A model preference that matches no model would fall back to another model without an error. + if ( $model && ! in_array( $model, array_map( static fn ( $metadata ) => $metadata->getId(), $models ), true ) ) { + $this->fail( "The provider has no \"$model\" model, check the $model_name." ); } $resolver = new WP_AI_Client_Ability_Function_Resolver( ...$abilities ); $messages = array( new UserMessage( array( new MessagePart( $question ) ) ) ); + $called = array(); - for ( $round = 0; $round < 6; $round++ ) { + for ( $round = 0; $round < self::MAX_ROUNDS; $round++ ) { $builder = ( new WP_AI_Client_Prompt_Builder( $registry, $messages ) ) ->using_provider( $provider ) ->using_system_instruction( 'Answer every question with the abilities. Quote the values they return unchanged.' ) ->using_abilities( ...$abilities ); - $model = getenv( 'WP_TESTS_AI_' . strtoupper( $provider ) . '_MODEL' ); if ( $model ) { $builder->using_model_preference( $model ); } @@ -245,40 +261,42 @@ private function ask( string $provider, array $abilities, string $question, arra $result = $builder->generate_text_result(); if ( is_wp_error( $result ) ) { - $status = $result->get_error_data()['status'] ?? 0; - $message = "($status): " . $result->get_error_message(); + $status = $result->get_error_data()['status'] ?? 0; + $error = "($status): " . $result->get_error_message(); // Only a rate limit, a server error of the provider and a network error skip the test. if ( 429 === $status || in_array( $result->get_error_code(), array( 'prompt_network_error', 'prompt_upstream_server_error' ), true ) ) { - $this->markTestSkipped( "The provider is unavailable $message" ); + $this->markTestSkipped( "The provider is unavailable $error" ); } - $this->fail( "The request failed $message" ); + $this->fail( "The request failed $error" ); } - // OpenAI returns each function call as its own candidate, so keep them all, not just toMessage(). + // OpenAI returns each function call as its own candidate, so keep the message of each one. $has_calls = false; - foreach ( $result->getCandidates() as $candidate ) { - $message = $candidate->getMessage(); + foreach ( $result->toMessages() as $message ) { $messages[] = $message; if ( ! $resolver->has_ability_calls( $message ) ) { continue; } - foreach ( $message->getParts() as $part ) { - if ( $part->getFunctionCall() ) { - $called[] = WP_AI_Client_Ability_Function_Resolver::function_name_to_ability_name( $part->getFunctionCall()->getName() ); + // Only an ability that ran without an error counts as called. + $response = $resolver->execute_abilities( $message ); + foreach ( $response->getParts() as $part ) { + $data = $part->getFunctionResponse()->getResponse(); + if ( ! is_array( $data ) || ! isset( $data['error'] ) ) { + $called[] = WP_AI_Client_Ability_Function_Resolver::function_name_to_ability_name( $part->getFunctionResponse()->getName() ); } } - $messages[] = $resolver->execute_abilities( $message ); + $messages[] = $response; $has_calls = true; } if ( ! $has_calls ) { - return implode( "\n", $result->toTexts() ); + return array( implode( "\n", $result->toTexts() ), array_unique( $called ), $result->getModelMetadata()->getId() ); } } - $this->fail( 'The model kept calling abilities without answering.' ); + $this->fail( 'The model kept calling abilities without answering. Abilities that ran: ' . implode( ', ', array_unique( $called ) ) ); } } From fc8333b500e45368d608c08fe3289698f18de2ca Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Mon, 16 Nov 2026 20:50:30 +0000 Subject: [PATCH 05/16] Build/Test Tools: Fix the request limit, the model check and the answer of the live AI provider tests. The number of requests a model may take now follows the number of abilities, so a model that calls one ability per response can still answer when it is given all six. The model of each result is compared with the requested one, which also catches a listed model that cannot be used for the prompt. Every text part of the answer is read, not only the first one. See #66707. --- docker-compose.yml | 1 - .../ai-client/wpAiClientLiveProviders.php | 87 ++++++++++++------- 2 files changed, 54 insertions(+), 34 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 629a8dd97a046..ecbd1adbdb970 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -50,7 +50,6 @@ services: GITHUB_EVENT_NAME: ${GITHUB_EVENT_NAME-false} HOST_PATH: ${PWD-}/${LOCAL_DIR-src} # Passed through for the live AI provider tests, and only when they are set. - # Only the tests read these names, so the keys are not used by the local site. WP_TESTS_AI_ANTHROPIC_API_KEY: WP_TESTS_AI_GOOGLE_API_KEY: WP_TESTS_AI_OPENAI_API_KEY: diff --git a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php index 523f1b0a28446..7f7e85334fb7e 100644 --- a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php +++ b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php @@ -6,13 +6,13 @@ * `WP_TESTS_AI_ANTHROPIC_API_KEY`, `WP_TESTS_AI_GOOGLE_API_KEY` or `WP_TESTS_AI_OPENAI_API_KEY` * environment variable: * - * WP_TESTS_AI_ANTHROPIC_API_KEY=… vendor/bin/phpunit --group external-http --filter Tests_AI_Client_LiveProviders + * WP_TESTS_AI_ANTHROPIC_API_KEY=your-key vendor/bin/phpunit --group external-http --filter Tests_AI_Client_LiveProviders * * The provider tools and the Connectors read other names, such as `ANTHROPIC_API_KEY`, so a key * set for them does not start these tests, and a key set for these tests is not used by a site. * - * A provider uses its default model, unless a `WP_TESTS_AI_{PROVIDER}_MODEL` environment - * variable, such as `WP_TESTS_AI_GOOGLE_MODEL`, names another one. + * A provider uses its default model, unless its `WP_TESTS_AI_*_MODEL` environment variable, + * such as `WP_TESTS_AI_GOOGLE_MODEL`, names another one. * * @group ai-client * @group abilities-api @@ -48,19 +48,32 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { * For each core ability, a question no other ability answers and the value the answer must contain. */ private const QUESTIONS = array( - 'core/get-site-info' => array( 'What is the character encoding of this site?', 'UTF-8' ), - 'core/get-user-info' => array( 'What is my display name?', 'Barnaby Quillfeather' ), - 'core/get-environment-info' => array( 'Which PHP version does this site run?', PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION ), - 'core/settings-get' => array( 'What is the timezone setting of this site?', 'Pacific/Chatham' ), - 'core/users-query' => array( 'What is the display name of the user with the username "live_provider_editor"?', 'Marigold Featherstone' ), - 'core/content-query' => array( 'What is the title of the post with the slug "live-provider-post"?', 'Quokka Lighthouse Notes' ), + 'core/get-site-info' => array( + 'question' => 'What is the character encoding of this site?', + 'answer' => 'UTF-8', + ), + 'core/get-user-info' => array( + 'question' => 'What is my display name?', + 'answer' => 'Barnaby Quillfeather', + ), + 'core/get-environment-info' => array( + 'question' => 'Which PHP version does this site run?', + 'answer' => PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION, + ), + 'core/settings-get' => array( + 'question' => 'What is the timezone setting of this site?', + 'answer' => 'Pacific/Chatham', + ), + 'core/users-query' => array( + 'question' => 'What is the display name of the user with the username "live_provider_editor"?', + 'answer' => 'Marigold Featherstone', + ), + 'core/content-query' => array( + 'question' => 'What is the title of the post with the slug "live-provider-post"?', + 'answer' => 'Quokka Lighthouse Notes', + ), ); - /** - * How many requests a model may take to answer. - */ - private const MAX_ROUNDS = 6; - /** * ID of the administrator who asks the questions. * @@ -162,11 +175,11 @@ public function set_up(): void { public function test_provider_answers_with_core_abilities( string $provider, array $abilities ): void { $questions = array_intersect_key( self::QUESTIONS, array_flip( $abilities ) ); - list( $answer, $called, $model ) = $this->ask( $provider, $abilities, implode( ' ', array_column( $questions, 0 ) ) ); + list( $answer, $called, $model ) = $this->ask( $provider, $abilities, implode( ' ', array_column( $questions, 'question' ) ) ); // A model may quote a value as it is in the JSON it received, where slashes are escaped. $answer = str_replace( '\/', '/', $answer ); - $missing = array_filter( array_column( $questions, 1 ), static fn ( $value ) => false === stripos( $answer, $value ) ); + $missing = array_filter( array_column( $questions, 'answer' ), static fn ( $value ) => false === stripos( $answer, $value ) ); $context = "Model: $model. Answer: $answer"; $this->assertSameSets( $abilities, $called, "Every ability given to the model should run without an error. $context" ); @@ -229,26 +242,22 @@ private function ask( string $provider, array $abilities, string $question ): ar * Any other exception, such as a response the provider changed, is an error of the test. */ try { - $models = $provider_class::modelMetadataDirectory()->listModelMetadata(); - } catch ( NetworkException | ServerException $e ) { - $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); - } catch ( ClientException $e ) { - if ( 429 === $e->getCode() ) { - $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); + $provider_class::modelMetadataDirectory()->listModelMetadata(); + } catch ( NetworkException | ServerException | ClientException $e ) { + if ( $e instanceof ClientException && 429 !== $e->getCode() ) { + $this->fail( "The model list request failed, check the $key_name: " . $e->getMessage() ); } - $this->fail( "The model list request failed, check the $key_name: " . $e->getMessage() ); - } - - // A model preference that matches no model would fall back to another model without an error. - if ( $model && ! in_array( $model, array_map( static fn ( $metadata ) => $metadata->getId(), $models ), true ) ) { - $this->fail( "The provider has no \"$model\" model, check the $model_name." ); + $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); } $resolver = new WP_AI_Client_Ability_Function_Resolver( ...$abilities ); $messages = array( new UserMessage( array( new MessagePart( $question ) ) ) ); $called = array(); - for ( $round = 0; $round < self::MAX_ROUNDS; $round++ ) { + // A model may call one ability per response: a request for each, one to answer and a spare one. + $max_rounds = count( $abilities ) + 2; + + for ( $round = 0; $round < $max_rounds; $round++ ) { $builder = ( new WP_AI_Client_Prompt_Builder( $registry, $messages ) ) ->using_provider( $provider ) ->using_system_instruction( 'Answer every question with the abilities. Quote the values they return unchanged.' ) @@ -262,20 +271,32 @@ private function ask( string $provider, array $abilities, string $question ): ar if ( is_wp_error( $result ) ) { $status = $result->get_error_data()['status'] ?? 0; - $error = "($status): " . $result->get_error_message(); // Only a rate limit, a server error of the provider and a network error skip the test. if ( 429 === $status || in_array( $result->get_error_code(), array( 'prompt_network_error', 'prompt_upstream_server_error' ), true ) ) { - $this->markTestSkipped( "The provider is unavailable $error" ); + $this->markTestSkipped( 'The provider is unavailable: ' . $result->get_error_message() ); } - $this->fail( "The request failed $error" ); + $this->fail( 'The request failed: ' . $result->get_error_message() ); + } + + // A model preference the provider cannot use for the prompt falls back to another model without an error. + if ( $model && $result->getModelMetadata()->getId() !== $model ) { + $this->fail( "The provider has no \"$model\" model for this prompt, check the $model_name." ); } // OpenAI returns each function call as its own candidate, so keep the message of each one. $has_calls = false; + $answer = ''; foreach ( $result->toMessages() as $message ) { $messages[] = $message; + // An answer may be split into several text parts. + foreach ( $message->getParts() as $part ) { + if ( $part->getChannel()->isContent() && null !== $part->getText() ) { + $answer .= $part->getText(); + } + } + if ( ! $resolver->has_ability_calls( $message ) ) { continue; } @@ -293,7 +314,7 @@ private function ask( string $provider, array $abilities, string $question ): ar } if ( ! $has_calls ) { - return array( implode( "\n", $result->toTexts() ), array_unique( $called ), $result->getModelMetadata()->getId() ); + return array( $answer, array_unique( $called ), $result->getModelMetadata()->getId() ); } } From ddc48612cdbf89a6eb05cb3a98f8c1654da1b367 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Mon, 16 Nov 2026 21:23:38 +0000 Subject: [PATCH 06/16] Build/Test Tools: Simplify the live AI provider tests and read their settings from constants too. An ability now counts as called when the `wp_after_execute_ability` action fires, which only happens after it ran without an error. A model named in `WP_TESTS_AI_*_MODEL` is used directly instead of as a preference, so no request goes to another model, and a model the provider does not list still fails the test. The API keys and models can also be set as constants, for example in `wp-tests-config.php`. The timezone option is set once for the class, and the super admin status is no longer revoked by hand, since the options are restored after each class. See #66707. --- .../ai-client/wpAiClientLiveProviders.php | 79 +++++++++---------- 1 file changed, 37 insertions(+), 42 deletions(-) diff --git a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php index 7f7e85334fb7e..29b36efc4ea5c 100644 --- a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php +++ b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php @@ -4,15 +4,12 @@ * * These tests send real requests. The tests of a provider only run when its API key is in the * `WP_TESTS_AI_ANTHROPIC_API_KEY`, `WP_TESTS_AI_GOOGLE_API_KEY` or `WP_TESTS_AI_OPENAI_API_KEY` - * environment variable: + * environment variable or constant: * * WP_TESTS_AI_ANTHROPIC_API_KEY=your-key vendor/bin/phpunit --group external-http --filter Tests_AI_Client_LiveProviders * - * The provider tools and the Connectors read other names, such as `ANTHROPIC_API_KEY`, so a key - * set for them does not start these tests, and a key set for these tests is not used by a site. - * - * A provider uses its default model, unless its `WP_TESTS_AI_*_MODEL` environment variable, - * such as `WP_TESTS_AI_GOOGLE_MODEL`, names another one. + * A provider uses its default model, unless its `WP_TESTS_AI_*_MODEL` environment variable or + * constant, such as `WP_TESTS_AI_GOOGLE_MODEL`, names another one. * * @group ai-client * @group abilities-api @@ -37,6 +34,8 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { /** * Provider classes keyed by provider ID. + * + * @var array */ private const PROVIDERS = array( 'anthropic' => AnthropicProvider::class, @@ -46,6 +45,8 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { /** * For each core ability, a question no other ability answers and the value the answer must contain. + * + * @var array */ private const QUESTIONS = array( 'core/get-site-info' => array( @@ -58,6 +59,7 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { ), 'core/get-environment-info' => array( 'question' => 'Which PHP version does this site run?', + // Without the suffix some builds add to `phpversion()`, such as `-1ubuntu2`, which a model may leave out. 'answer' => PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION, ), 'core/settings-get' => array( @@ -82,7 +84,7 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { private static $admin_id; /** - * Creates the content the questions are about and registers the core abilities. + * Creates the users, the post and the option the questions are about, and registers the core abilities. * * @param WP_UnitTest_Factory $factory Factory instance. */ @@ -114,6 +116,7 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void 'post_title' => 'Quokka Lighthouse Notes', ) ); + update_option( 'timezone_string', 'Pacific/Chatham' ); foreach ( wp_get_abilities() as $ability ) { wp_unregister_ability( $ability->get_name() ); @@ -133,13 +136,9 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void } /** - * Revokes the super admin status and cleans up the registered abilities and categories. + * Cleans up the registered abilities and categories. */ public static function wpTearDownAfterClass(): void { - if ( is_multisite() ) { - revoke_super_admin( self::$admin_id ); - } - foreach ( wp_get_abilities() as $ability ) { wp_unregister_ability( $ability->get_name() ); } @@ -149,13 +148,12 @@ public static function wpTearDownAfterClass(): void { } /** - * Signs in the administrator, sets the option one of the questions is about and allows slow responses. + * Signs in the administrator and allows slow responses. */ public function set_up(): void { parent::set_up(); wp_set_current_user( self::$admin_id ); - update_option( 'timezone_string', 'Pacific/Chatham' ); // The request that lists the models of a provider has no timeout of its own. add_filter( 'http_request_timeout', static fn () => 30 ); @@ -209,8 +207,9 @@ public static function data_providers_and_abilities(): array { /** * Asks a provider a question and runs the abilities the model calls until it answers. * - * The test is skipped when the provider has no API key or is unavailable: it limits the - * requests, has a server error or cannot be reached. Every other error fails the test. + * The test is skipped when the provider has no API key, its package is not installed or it is + * unavailable: it limits the requests, has a server error or cannot be reached. Every other + * error fails the test. * * @param string $provider Provider ID. * @param string[] $abilities Names of the abilities given to the model. @@ -222,14 +221,14 @@ private function ask( string $provider, array $abilities, string $question ): ar $provider_class = self::PROVIDERS[ $provider ]; $key_name = 'WP_TESTS_AI_' . strtoupper( $provider ) . '_API_KEY'; $model_name = 'WP_TESTS_AI_' . strtoupper( $provider ) . '_MODEL'; - $api_key = getenv( $key_name ); - $model = getenv( $model_name ); + $api_key = defined( $key_name ) ? constant( $key_name ) : getenv( $key_name ); + $model = defined( $model_name ) ? constant( $model_name ) : getenv( $model_name ); if ( ! $api_key ) { - $this->markTestSkipped( "The $key_name environment variable is not set." ); + $this->markTestSkipped( "The $key_name environment variable or constant is not set." ); } if ( ! class_exists( $provider_class ) ) { - $this->markTestSkipped( 'The AI provider packages are not installed. Run `composer update`.' ); + $this->markTestSkipped( 'The AI provider packages are not installed. Run `composer update`, or `npm run env:composer -- update` in the local Docker environment.' ); } $registry = new ProviderRegistry(); @@ -250,21 +249,32 @@ private function ask( string $provider, array $abilities, string $question ): ar $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); } + if ( $model && ! $provider_class::modelMetadataDirectory()->hasModelMetadata( $model ) ) { + $this->fail( "The provider has no \"$model\" model, check the $model_name." ); + } + $resolver = new WP_AI_Client_Ability_Function_Resolver( ...$abilities ); $messages = array( new UserMessage( array( new MessagePart( $question ) ) ) ); $called = array(); + // The action only fires after an ability ran without an error, so only those count as called. + add_action( + 'wp_after_execute_ability', + static function ( string $ability_name ) use ( &$called ) { + $called[ $ability_name ] = true; + } + ); + // A model may call one ability per response: a request for each, one to answer and a spare one. $max_rounds = count( $abilities ) + 2; for ( $round = 0; $round < $max_rounds; $round++ ) { $builder = ( new WP_AI_Client_Prompt_Builder( $registry, $messages ) ) - ->using_provider( $provider ) ->using_system_instruction( 'Answer every question with the abilities. Quote the values they return unchanged.' ) ->using_abilities( ...$abilities ); if ( $model ) { - $builder->using_model_preference( $model ); + $builder->using_model( $registry->getProviderModel( $provider, $model ) ); } $result = $builder->generate_text_result(); @@ -279,11 +289,6 @@ private function ask( string $provider, array $abilities, string $question ): ar $this->fail( 'The request failed: ' . $result->get_error_message() ); } - // A model preference the provider cannot use for the prompt falls back to another model without an error. - if ( $model && $result->getModelMetadata()->getId() !== $model ) { - $this->fail( "The provider has no \"$model\" model for this prompt, check the $model_name." ); - } - // OpenAI returns each function call as its own candidate, so keep the message of each one. $has_calls = false; $answer = ''; @@ -297,27 +302,17 @@ private function ask( string $provider, array $abilities, string $question ): ar } } - if ( ! $resolver->has_ability_calls( $message ) ) { - continue; - } - - // Only an ability that ran without an error counts as called. - $response = $resolver->execute_abilities( $message ); - foreach ( $response->getParts() as $part ) { - $data = $part->getFunctionResponse()->getResponse(); - if ( ! is_array( $data ) || ! isset( $data['error'] ) ) { - $called[] = WP_AI_Client_Ability_Function_Resolver::function_name_to_ability_name( $part->getFunctionResponse()->getName() ); - } + if ( $resolver->has_ability_calls( $message ) ) { + $messages[] = $resolver->execute_abilities( $message ); + $has_calls = true; } - $messages[] = $response; - $has_calls = true; } if ( ! $has_calls ) { - return array( $answer, array_unique( $called ), $result->getModelMetadata()->getId() ); + return array( $answer, array_keys( $called ), $result->getModelMetadata()->getId() ); } } - $this->fail( 'The model kept calling abilities without answering. Abilities that ran: ' . implode( ', ', array_unique( $called ) ) ); + $this->fail( 'The model kept calling abilities without answering. Abilities that ran: ' . implode( ', ', array_keys( $called ) ) ); } } From f94fd86e60fe21e274b32a18dd8efbc58b99815a Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Mon, 16 Nov 2026 21:54:23 +0000 Subject: [PATCH 07/16] Build/Test Tools: Tidy the live AI provider tests and document their constants. Removes the unregister loops that ran before the core abilities are registered, resolves a named model once instead of on every request, and catches client errors apart from network and server errors. Documents the key and model constants in `wp-tests-config-sample.php` and `.env.example`, and says that the keys reach the PHP container that serves the local site. See #66707. --- .env.example | 6 ++++-- .../ai-client/wpAiClientLiveProviders.php | 18 +++++++----------- wp-tests-config-sample.php | 10 ++++++++++ 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/.env.example b/.env.example index be8cc70089eba..271cb5f30e7eb 100644 --- a/.env.example +++ b/.env.example @@ -90,9 +90,11 @@ LOCAL_WP_TESTS_DOMAIN=example.org # npm run test:php -- --group external-http --filter Tests_AI_Client_LiveProviders # # The tests of a provider are skipped while its key is not set. A provider uses its -# default model unless its `WP_TESTS_AI_*_MODEL` variable names another one. +# default model unless its `WP_TESTS_AI_*_MODEL` variable names another one. The same +# names can also be defined as constants in `wp-tests-config.php`. # -# Only the tests read these names, so the keys are not used by the local site. +# The keys are passed to the PHP container, which also serves the local site, but only +# the tests read these names. ## # WP_TESTS_AI_ANTHROPIC_API_KEY= # WP_TESTS_AI_GOOGLE_API_KEY= diff --git a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php index 29b36efc4ea5c..72765ed40995e 100644 --- a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php +++ b/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php @@ -118,13 +118,6 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void ); update_option( 'timezone_string', 'Pacific/Chatham' ); - foreach ( wp_get_abilities() as $ability ) { - wp_unregister_ability( $ability->get_name() ); - } - foreach ( wp_get_ability_categories() as $ability_category ) { - wp_unregister_ability_category( $ability_category->get_slug() ); - } - // The core abilities can only be registered while their registration actions run. $wp_current_filter[] = 'wp_abilities_api_categories_init'; wp_register_core_ability_categories(); @@ -242,16 +235,19 @@ private function ask( string $provider, array $abilities, string $question ): ar */ try { $provider_class::modelMetadataDirectory()->listModelMetadata(); - } catch ( NetworkException | ServerException | ClientException $e ) { - if ( $e instanceof ClientException && 429 !== $e->getCode() ) { + } catch ( ClientException $e ) { + if ( 429 !== $e->getCode() ) { $this->fail( "The model list request failed, check the $key_name: " . $e->getMessage() ); } $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); + } catch ( NetworkException | ServerException $e ) { + $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); } if ( $model && ! $provider_class::modelMetadataDirectory()->hasModelMetadata( $model ) ) { $this->fail( "The provider has no \"$model\" model, check the $model_name." ); } + $model_instance = $model ? $registry->getProviderModel( $provider, $model ) : null; $resolver = new WP_AI_Client_Ability_Function_Resolver( ...$abilities ); $messages = array( new UserMessage( array( new MessagePart( $question ) ) ) ); @@ -273,8 +269,8 @@ static function ( string $ability_name ) use ( &$called ) { ->using_system_instruction( 'Answer every question with the abilities. Quote the values they return unchanged.' ) ->using_abilities( ...$abilities ); - if ( $model ) { - $builder->using_model( $registry->getProviderModel( $provider, $model ) ); + if ( $model_instance ) { + $builder->using_model( $model_instance ); } $result = $builder->generate_text_result(); diff --git a/wp-tests-config-sample.php b/wp-tests-config-sample.php index ed5a7524d837e..9c891ba1ae3e7 100644 --- a/wp-tests-config-sample.php +++ b/wp-tests-config-sample.php @@ -23,6 +23,16 @@ */ // define( 'WP_TESTS_FORCE_KNOWN_BUGS', true ); +/* + * API keys for the live AI provider tests, which send real requests. + * The tests of a provider are skipped while its key is not set, here or in an environment + * variable of the same name. A provider uses its default model unless its + * `WP_TESTS_AI_*_MODEL` constant, such as `WP_TESTS_AI_GOOGLE_MODEL`, names another one. + */ +// define( 'WP_TESTS_AI_ANTHROPIC_API_KEY', '' ); +// define( 'WP_TESTS_AI_GOOGLE_API_KEY', '' ); +// define( 'WP_TESTS_AI_OPENAI_API_KEY', '' ); + // Test with WordPress debug mode (default). define( 'WP_DEBUG', true ); From 4703a4b52699fafd9a17dcc8d80aa38e746912cb Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Thu, 26 Nov 2026 16:18:29 +0000 Subject: [PATCH 08/16] Build/Test Tools: Move the live AI provider tests out of the test suites. The tests now live in `tests/phpunit/manual`, which no test suite includes, so a run of the `external-http` group, such as the one on CI, does not select them. They only run when that directory is named. See #66707. --- .env.example | 5 +++-- .../{tests/ai-client => manual}/wpAiClientLiveProviders.php | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) rename tests/phpunit/{tests/ai-client => manual}/wpAiClientLiveProviders.php (97%) diff --git a/.env.example b/.env.example index 271cb5f30e7eb..ae33e156f2fa9 100644 --- a/.env.example +++ b/.env.example @@ -85,9 +85,10 @@ LOCAL_WP_DEVELOPMENT_MODE=core LOCAL_WP_TESTS_DOMAIN=example.org ## -# API keys for the live AI provider tests, which send real requests: +# API keys for the live AI provider tests in `tests/phpunit/manual`, which send real +# requests and only run when that directory is named: # -# npm run test:php -- --group external-http --filter Tests_AI_Client_LiveProviders +# npm run test:php -- --group external-http --test-suffix .php tests/phpunit/manual # # The tests of a provider are skipped while its key is not set. A provider uses its # default model unless its `WP_TESTS_AI_*_MODEL` variable names another one. The same diff --git a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php b/tests/phpunit/manual/wpAiClientLiveProviders.php similarity index 97% rename from tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php rename to tests/phpunit/manual/wpAiClientLiveProviders.php index 72765ed40995e..fe559746b82ab 100644 --- a/tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php +++ b/tests/phpunit/manual/wpAiClientLiveProviders.php @@ -2,11 +2,12 @@ /** * Tests that live AI providers can call the core abilities through the AI Client. * - * These tests send real requests. The tests of a provider only run when its API key is in the + * These tests send real requests to paid APIs, so they are outside the test suites and only run + * when this directory is named. The tests of a provider only run when its API key is in the * `WP_TESTS_AI_ANTHROPIC_API_KEY`, `WP_TESTS_AI_GOOGLE_API_KEY` or `WP_TESTS_AI_OPENAI_API_KEY` * environment variable or constant: * - * WP_TESTS_AI_ANTHROPIC_API_KEY=your-key vendor/bin/phpunit --group external-http --filter Tests_AI_Client_LiveProviders + * WP_TESTS_AI_ANTHROPIC_API_KEY=your-key vendor/bin/phpunit --group external-http --test-suffix .php tests/phpunit/manual * * A provider uses its default model, unless its `WP_TESTS_AI_*_MODEL` environment variable or * constant, such as `WP_TESTS_AI_GOOGLE_MODEL`, names another one. From 993e6b66090a01ac4e479e5e7cf200a0e00cf131 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 27 Nov 2026 11:21:08 +0000 Subject: [PATCH 09/16] Build/Test Tools: Find the AI provider packages when PHPUnit runs from a PHAR. A PHPUnit PHAR does not load the Composer autoloader of the checkout, so the live AI provider tests skipped as if the provider packages were not installed. The tests now load that autoloader when a provider class is missing. See #66707. --- tests/phpunit/manual/wpAiClientLiveProviders.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/phpunit/manual/wpAiClientLiveProviders.php b/tests/phpunit/manual/wpAiClientLiveProviders.php index fe559746b82ab..aa21f07f3410b 100644 --- a/tests/phpunit/manual/wpAiClientLiveProviders.php +++ b/tests/phpunit/manual/wpAiClientLiveProviders.php @@ -221,6 +221,12 @@ private function ask( string $provider, array $abilities, string $question ): ar if ( ! $api_key ) { $this->markTestSkipped( "The $key_name environment variable or constant is not set." ); } + + // PHPUnit may run from a PHAR, which does not load the Composer autoloader of the checkout. + $autoloader = dirname( __DIR__, 3 ) . '/vendor/autoload.php'; + if ( ! class_exists( $provider_class ) && file_exists( $autoloader ) ) { + require_once $autoloader; + } if ( ! class_exists( $provider_class ) ) { $this->markTestSkipped( 'The AI provider packages are not installed. Run `composer update`, or `npm run env:composer -- update` in the local Docker environment.' ); } From e2fb6f60a2a29204107726a2755eeaac4092d338 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 27 Nov 2026 11:21:24 +0000 Subject: [PATCH 10/16] Build/Test Tools: Fail the live AI provider tests when an ability returns an error. An ability error was sent back to the model without failing the test, so a model that retried and then answered could still pass it. The test now fails on the first error response of the resolver. See #66707. --- tests/phpunit/manual/wpAiClientLiveProviders.php | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/tests/phpunit/manual/wpAiClientLiveProviders.php b/tests/phpunit/manual/wpAiClientLiveProviders.php index aa21f07f3410b..a2075ba88d022 100644 --- a/tests/phpunit/manual/wpAiClientLiveProviders.php +++ b/tests/phpunit/manual/wpAiClientLiveProviders.php @@ -306,7 +306,20 @@ static function ( string $ability_name ) use ( &$called ) { } if ( $resolver->has_ability_calls( $message ) ) { - $messages[] = $resolver->execute_abilities( $message ); + $response_message = $resolver->execute_abilities( $message ); + + // The model could retry after an error and still answer, so an error fails the test. + foreach ( $response_message->getParts() as $part ) { + $function_response = $part->getFunctionResponse(); + $response = $function_response ? $function_response->getResponse() : null; + + if ( is_array( $response ) && isset( $response['error'], $response['code'] ) ) { + $ability_name = WP_AI_Client_Ability_Function_Resolver::function_name_to_ability_name( (string) $function_response->getName() ); + $this->fail( "The $ability_name ability returned an error: {$response['error']} ({$response['code']})" ); + } + } + + $messages[] = $response_message; $has_calls = true; } } From bdf03d7cfe270ad9678095786a3bbc82a56edb60 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 27 Nov 2026 11:33:44 +0000 Subject: [PATCH 11/16] Build/Test Tools: Ask for the name of the queried user in the live AI provider tests. The users-query ability returns the display name as `name`. When the question asked for the display name, a model given every ability could request a `display_name` field, which only the get-user-info ability has. See #66707. --- tests/phpunit/manual/wpAiClientLiveProviders.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/phpunit/manual/wpAiClientLiveProviders.php b/tests/phpunit/manual/wpAiClientLiveProviders.php index a2075ba88d022..86dae11429e8d 100644 --- a/tests/phpunit/manual/wpAiClientLiveProviders.php +++ b/tests/phpunit/manual/wpAiClientLiveProviders.php @@ -68,7 +68,7 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { 'answer' => 'Pacific/Chatham', ), 'core/users-query' => array( - 'question' => 'What is the display name of the user with the username "live_provider_editor"?', + 'question' => 'What is the name of the user with the username "live_provider_editor"?', 'answer' => 'Marigold Featherstone', ), 'core/content-query' => array( From 12fedc737a52bd036d8d68f1c1e7fea69fd6686e Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 27 Nov 2026 12:11:33 +0000 Subject: [PATCH 12/16] Build/Test Tools: Load only the AI provider packages when PHPUnit runs from a PHAR. The Composer autoloader of the checkout goes in front of the autoloader of the PHAR and also maps the PHPUnit classes of the checkout, so a run could mix two PHPUnit versions. The tests now load the classes of the provider package from its own directory. See #66707. --- .../manual/wpAiClientLiveProviders.php | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/tests/phpunit/manual/wpAiClientLiveProviders.php b/tests/phpunit/manual/wpAiClientLiveProviders.php index 86dae11429e8d..8ce2a7bec225b 100644 --- a/tests/phpunit/manual/wpAiClientLiveProviders.php +++ b/tests/phpunit/manual/wpAiClientLiveProviders.php @@ -222,10 +222,22 @@ private function ask( string $provider, array $abilities, string $question ): ar $this->markTestSkipped( "The $key_name environment variable or constant is not set." ); } - // PHPUnit may run from a PHAR, which does not load the Composer autoloader of the checkout. - $autoloader = dirname( __DIR__, 3 ) . '/vendor/autoload.php'; - if ( ! class_exists( $provider_class ) && file_exists( $autoloader ) ) { - require_once $autoloader; + /* + * PHPUnit may run from a PHAR, which does not load the Composer autoloader of the checkout. + * That autoloader would also load the PHPUnit classes of the checkout, so only the classes + * of the provider package are loaded, from its `src` directory. + */ + $namespace = strstr( $provider_class, '\\Provider\\', true ) . '\\'; + $package_dir = dirname( __DIR__, 3 ) . "/vendor/wordpress/ai-provider-for-$provider/src/"; + if ( ! class_exists( $provider_class ) && is_dir( $package_dir ) ) { + spl_autoload_register( + static function ( string $class_name ) use ( $namespace, $package_dir ) { + $file = $package_dir . str_replace( '\\', '/', substr( $class_name, strlen( $namespace ) ) ) . '.php'; + if ( str_starts_with( $class_name, $namespace ) && file_exists( $file ) ) { + require $file; + } + } + ); } if ( ! class_exists( $provider_class ) ) { $this->markTestSkipped( 'The AI provider packages are not installed. Run `composer update`, or `npm run env:composer -- update` in the local Docker environment.' ); From 527ae04f57aa919a6f421256b187351db0b87340 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 27 Nov 2026 12:18:44 +0000 Subject: [PATCH 13/16] Build/Test Tools: Update the Google and OpenAI providers of the live AI provider tests to 1.3.0. See #66707. --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 2ebb708d6ccc7..0a2b1e998c2b1 100644 --- a/composer.json +++ b/composer.json @@ -57,8 +57,8 @@ "phpstan/phpstan-strict-rules": "2.1.2", "yoast/phpunit-polyfills": "^1.1.0", "wordpress/ai-provider-for-anthropic": "1.0.5", - "wordpress/ai-provider-for-google": "1.2.1", - "wordpress/ai-provider-for-openai": "1.2.0" + "wordpress/ai-provider-for-google": "1.3.0", + "wordpress/ai-provider-for-openai": "1.3.0" }, "config": { "audit": { "ignore": [ "GHSA-hmqg-cxww-wqhq", "PKSA-rdkp-vv9z-mjkg" ] }, From d76ee21dc9758fb00d476814b3fa4be8d1fcea5d Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 27 Nov 2026 12:29:03 +0000 Subject: [PATCH 14/16] Build/Test Tools: Simplify the live AI provider tests and read their settings from the environment first. Since an ability error fails the test, the abilities that ran are recorded from the responses of the resolver instead of an action. An error now also shows its data, and the setup pops the simulated actions in finally blocks. An environment variable now takes precedence over the constant, as in the AI Client, so an empty constant in wp-tests-config.php no longer hides a key in the environment. The sample config lists the model constants too. See #66707. --- .../manual/wpAiClientLiveProviders.php | 70 ++++++++++++------- wp-tests-config-sample.php | 11 +-- 2 files changed, 53 insertions(+), 28 deletions(-) diff --git a/tests/phpunit/manual/wpAiClientLiveProviders.php b/tests/phpunit/manual/wpAiClientLiveProviders.php index 8ce2a7bec225b..1640a4d2a8910 100644 --- a/tests/phpunit/manual/wpAiClientLiveProviders.php +++ b/tests/phpunit/manual/wpAiClientLiveProviders.php @@ -120,13 +120,20 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void update_option( 'timezone_string', 'Pacific/Chatham' ); // The core abilities can only be registered while their registration actions run. + // Pop in finally so a setup exception cannot leave the simulated action on the stack. $wp_current_filter[] = 'wp_abilities_api_categories_init'; - wp_register_core_ability_categories(); - array_pop( $wp_current_filter ); + try { + wp_register_core_ability_categories(); + } finally { + array_pop( $wp_current_filter ); + } $wp_current_filter[] = 'wp_abilities_api_init'; - wp_register_core_abilities(); - array_pop( $wp_current_filter ); + try { + wp_register_core_abilities(); + } finally { + array_pop( $wp_current_filter ); + } } /** @@ -174,7 +181,7 @@ public function test_provider_answers_with_core_abilities( string $provider, arr $missing = array_filter( array_column( $questions, 'answer' ), static fn ( $value ) => false === stripos( $answer, $value ) ); $context = "Model: $model. Answer: $answer"; - $this->assertSameSets( $abilities, $called, "Every ability given to the model should run without an error. $context" ); + $this->assertSameSets( $abilities, $called, "Every ability given to the model should be called. $context" ); $this->assertSame( array(), $missing, "The answer should contain every expected value. $context" ); } @@ -209,17 +216,18 @@ public static function data_providers_and_abilities(): array { * @param string[] $abilities Names of the abilities given to the model. * @param string $question The question. * @return array{0: string, 1: string[], 2: string} The answer, the names of the abilities - * that ran without an error and the model ID. + * that ran and the model ID. */ private function ask( string $provider, array $abilities, string $question ): array { $provider_class = self::PROVIDERS[ $provider ]; - $key_name = 'WP_TESTS_AI_' . strtoupper( $provider ) . '_API_KEY'; - $model_name = 'WP_TESTS_AI_' . strtoupper( $provider ) . '_MODEL'; - $api_key = defined( $key_name ) ? constant( $key_name ) : getenv( $key_name ); - $model = defined( $model_name ) ? constant( $model_name ) : getenv( $model_name ); + $prefix = 'WP_TESTS_AI_' . strtoupper( $provider ); + $key_var = "{$prefix}_API_KEY"; + $model_var = "{$prefix}_MODEL"; + $api_key = self::get_setting( $key_var ); + $model = self::get_setting( $model_var ); if ( ! $api_key ) { - $this->markTestSkipped( "The $key_name environment variable or constant is not set." ); + $this->markTestSkipped( "The $key_var environment variable or constant is not set." ); } /* @@ -256,7 +264,7 @@ static function ( string $class_name ) use ( $namespace, $package_dir ) { $provider_class::modelMetadataDirectory()->listModelMetadata(); } catch ( ClientException $e ) { if ( 429 !== $e->getCode() ) { - $this->fail( "The model list request failed, check the $key_name: " . $e->getMessage() ); + $this->fail( "The model list request failed, check the $key_var: " . $e->getMessage() ); } $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); } catch ( NetworkException | ServerException $e ) { @@ -264,7 +272,7 @@ static function ( string $class_name ) use ( $namespace, $package_dir ) { } if ( $model && ! $provider_class::modelMetadataDirectory()->hasModelMetadata( $model ) ) { - $this->fail( "The provider has no \"$model\" model, check the $model_name." ); + $this->fail( "The provider has no \"$model\" model, check the $model_var." ); } $model_instance = $model ? $registry->getProviderModel( $provider, $model ) : null; @@ -272,14 +280,6 @@ static function ( string $class_name ) use ( $namespace, $package_dir ) { $messages = array( new UserMessage( array( new MessagePart( $question ) ) ) ); $called = array(); - // The action only fires after an ability ran without an error, so only those count as called. - add_action( - 'wp_after_execute_ability', - static function ( string $ability_name ) use ( &$called ) { - $called[ $ability_name ] = true; - } - ); - // A model may call one ability per response: a request for each, one to answer and a spare one. $max_rounds = count( $abilities ) + 2; @@ -323,12 +323,15 @@ static function ( string $ability_name ) use ( &$called ) { // The model could retry after an error and still answer, so an error fails the test. foreach ( $response_message->getParts() as $part ) { $function_response = $part->getFunctionResponse(); - $response = $function_response ? $function_response->getResponse() : null; + $response = $function_response->getResponse(); + $ability_name = WP_AI_Client_Ability_Function_Resolver::function_name_to_ability_name( (string) $function_response->getName() ); if ( is_array( $response ) && isset( $response['error'], $response['code'] ) ) { - $ability_name = WP_AI_Client_Ability_Function_Resolver::function_name_to_ability_name( (string) $function_response->getName() ); - $this->fail( "The $ability_name ability returned an error: {$response['error']} ({$response['code']})" ); + $data = isset( $response['data'] ) ? ' ' . wp_json_encode( $response['data'] ) : ''; + $this->fail( "The $ability_name ability returned an error: {$response['error']} ({$response['code']})$data" ); } + + $called[ $ability_name ] = true; } $messages[] = $response_message; @@ -343,4 +346,23 @@ static function ( string $ability_name ) use ( &$called ) { $this->fail( 'The model kept calling abilities without answering. Abilities that ran: ' . implode( ', ', array_keys( $called ) ) ); } + + /** + * Gets a setting from an environment variable or, when that is empty or not set, a constant. + * + * The AI Client reads the environment variable first too, so an empty constant in + * `wp-tests-config.php` does not hide a value in the environment. + * + * @param string $name Name of the environment variable and the constant. + * @return string The value, or an empty string when neither is set. + */ + private static function get_setting( string $name ): string { + $value = getenv( $name ); + + if ( false === $value || '' === $value ) { + $value = defined( $name ) ? constant( $name ) : ''; + } + + return (string) $value; + } } diff --git a/wp-tests-config-sample.php b/wp-tests-config-sample.php index 9c891ba1ae3e7..feaea8dc40826 100644 --- a/wp-tests-config-sample.php +++ b/wp-tests-config-sample.php @@ -24,14 +24,17 @@ // define( 'WP_TESTS_FORCE_KNOWN_BUGS', true ); /* - * API keys for the live AI provider tests, which send real requests. - * The tests of a provider are skipped while its key is not set, here or in an environment - * variable of the same name. A provider uses its default model unless its - * `WP_TESTS_AI_*_MODEL` constant, such as `WP_TESTS_AI_GOOGLE_MODEL`, names another one. + * API keys and models for the live AI provider tests, which send real requests. + * An environment variable of the same name takes precedence over each constant. + * The tests of a provider are skipped while its key is not set, and a provider + * uses its default model while its model is not set. */ // define( 'WP_TESTS_AI_ANTHROPIC_API_KEY', '' ); // define( 'WP_TESTS_AI_GOOGLE_API_KEY', '' ); // define( 'WP_TESTS_AI_OPENAI_API_KEY', '' ); +// define( 'WP_TESTS_AI_ANTHROPIC_MODEL', '' ); +// define( 'WP_TESTS_AI_GOOGLE_MODEL', '' ); +// define( 'WP_TESTS_AI_OPENAI_MODEL', '' ); // Test with WordPress debug mode (default). define( 'WP_DEBUG', true ); From db74ff585fe4a98b99a9b9b35916c37aadcf6b8d Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 27 Nov 2026 12:48:09 +0000 Subject: [PATCH 15/16] Build/Test Tools: Tidy the live AI provider tests and document them in one place. The provider packages get their autoloaders once, before the tests run, and an autoloader returns early for classes outside its namespace. The settings helper is shorter, and two docblocks are corrected. The test file now documents the Docker run command, so `.env.example` points to it instead of repeating the instructions. See #66707. --- .env.example | 13 +--- .../manual/wpAiClientLiveProviders.php | 70 ++++++++++++------- 2 files changed, 45 insertions(+), 38 deletions(-) diff --git a/.env.example b/.env.example index ae33e156f2fa9..e74ab50024476 100644 --- a/.env.example +++ b/.env.example @@ -85,17 +85,8 @@ LOCAL_WP_DEVELOPMENT_MODE=core LOCAL_WP_TESTS_DOMAIN=example.org ## -# API keys for the live AI provider tests in `tests/phpunit/manual`, which send real -# requests and only run when that directory is named: -# -# npm run test:php -- --group external-http --test-suffix .php tests/phpunit/manual -# -# The tests of a provider are skipped while its key is not set. A provider uses its -# default model unless its `WP_TESTS_AI_*_MODEL` variable names another one. The same -# names can also be defined as constants in `wp-tests-config.php`. -# -# The keys are passed to the PHP container, which also serves the local site, but only -# the tests read these names. +# API keys and models for the live AI provider tests, which send real requests. +# See `tests/phpunit/manual/wpAiClientLiveProviders.php`. ## # WP_TESTS_AI_ANTHROPIC_API_KEY= # WP_TESTS_AI_GOOGLE_API_KEY= diff --git a/tests/phpunit/manual/wpAiClientLiveProviders.php b/tests/phpunit/manual/wpAiClientLiveProviders.php index 1640a4d2a8910..15148abeee687 100644 --- a/tests/phpunit/manual/wpAiClientLiveProviders.php +++ b/tests/phpunit/manual/wpAiClientLiveProviders.php @@ -9,6 +9,11 @@ * * WP_TESTS_AI_ANTHROPIC_API_KEY=your-key vendor/bin/phpunit --group external-http --test-suffix .php tests/phpunit/manual * + * In the local Docker environment, set them in the `.env` file and run the command below. They are + * passed to the PHP container, which also serves the local site, but only these tests read them: + * + * npm run test:php -- --group external-http --test-suffix .php tests/phpunit/manual + * * A provider uses its default model, unless its `WP_TESTS_AI_*_MODEL` environment variable or * constant, such as `WP_TESTS_AI_GOOGLE_MODEL`, names another one. * @@ -85,13 +90,16 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { private static $admin_id; /** - * Creates the users, the post and the option the questions are about, and registers the core abilities. + * Loads the provider packages, creates the users, the post and the option the questions are about, + * and registers the core abilities. * * @param WP_UnitTest_Factory $factory Factory instance. */ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void { global $wp_current_filter; + self::register_provider_autoloaders(); + self::$admin_id = $factory->user->create( array( 'role' => 'administrator', @@ -209,8 +217,7 @@ public static function data_providers_and_abilities(): array { * Asks a provider a question and runs the abilities the model calls until it answers. * * The test is skipped when the provider has no API key, its package is not installed or it is - * unavailable: it limits the requests, has a server error or cannot be reached. Every other - * error fails the test. + * rate limited, returns a server error or cannot be reached. Every other error fails the test. * * @param string $provider Provider ID. * @param string[] $abilities Names of the abilities given to the model. @@ -230,23 +237,6 @@ private function ask( string $provider, array $abilities, string $question ): ar $this->markTestSkipped( "The $key_var environment variable or constant is not set." ); } - /* - * PHPUnit may run from a PHAR, which does not load the Composer autoloader of the checkout. - * That autoloader would also load the PHPUnit classes of the checkout, so only the classes - * of the provider package are loaded, from its `src` directory. - */ - $namespace = strstr( $provider_class, '\\Provider\\', true ) . '\\'; - $package_dir = dirname( __DIR__, 3 ) . "/vendor/wordpress/ai-provider-for-$provider/src/"; - if ( ! class_exists( $provider_class ) && is_dir( $package_dir ) ) { - spl_autoload_register( - static function ( string $class_name ) use ( $namespace, $package_dir ) { - $file = $package_dir . str_replace( '\\', '/', substr( $class_name, strlen( $namespace ) ) ) . '.php'; - if ( str_starts_with( $class_name, $namespace ) && file_exists( $file ) ) { - require $file; - } - } - ); - } if ( ! class_exists( $provider_class ) ) { $this->markTestSkipped( 'The AI provider packages are not installed. Run `composer update`, or `npm run env:composer -- update` in the local Docker environment.' ); } @@ -348,21 +338,47 @@ static function ( string $class_name ) use ( $namespace, $package_dir ) { } /** - * Gets a setting from an environment variable or, when that is empty or not set, a constant. + * Loads the classes of each installed provider package that the Composer autoloader does not load. * - * The AI Client reads the environment variable first too, so an empty constant in - * `wp-tests-config.php` does not hide a value in the environment. + * PHPUnit may run from a PHAR, which does not load the Composer autoloader of the checkout. + * That autoloader would also load the PHPUnit classes of the checkout, so only the classes + * of the provider packages are loaded, from their `src` directories. + */ + private static function register_provider_autoloaders(): void { + foreach ( self::PROVIDERS as $provider => $provider_class ) { + $namespace = strstr( $provider_class, '\\Provider\\', true ) . '\\'; + $package_dir = dirname( __DIR__, 3 ) . "/vendor/wordpress/ai-provider-for-$provider/src/"; + + if ( class_exists( $provider_class ) || ! is_dir( $package_dir ) ) { + continue; + } + + spl_autoload_register( + static function ( string $class_name ) use ( $namespace, $package_dir ) { + if ( ! str_starts_with( $class_name, $namespace ) ) { + return; + } + + $file = $package_dir . str_replace( '\\', '/', substr( $class_name, strlen( $namespace ) ) ) . '.php'; + if ( file_exists( $file ) ) { + require $file; + } + } + ); + } + } + + /** + * Gets a setting from an environment variable or, when that is empty or not set, a constant. * * @param string $name Name of the environment variable and the constant. * @return string The value, or an empty string when neither is set. */ private static function get_setting( string $name ): string { $value = getenv( $name ); - - if ( false === $value || '' === $value ) { - $value = defined( $name ) ? constant( $name ) : ''; + if ( ! $value && defined( $name ) ) { + $value = constant( $name ); } - return (string) $value; } } From 79e1f5287064257763701252d08a96d239b0fb59 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 27 Nov 2026 13:15:51 +0000 Subject: [PATCH 16/16] Build/Test Tools: Simplify the error handling and setup of the live AI provider tests. Handle the failed model list in one catch block, keep the namespace of each provider package next to its class, register the core abilities and their categories in one simulated action context, and document the model IDs and the precedence of a non-empty environment variable. See #66707. --- .env.example | 2 + .../manual/wpAiClientLiveProviders.php | 47 ++++++++++--------- wp-tests-config-sample.php | 7 +-- 3 files changed, 30 insertions(+), 26 deletions(-) diff --git a/.env.example b/.env.example index e74ab50024476..957c9edd7691f 100644 --- a/.env.example +++ b/.env.example @@ -91,6 +91,8 @@ LOCAL_WP_TESTS_DOMAIN=example.org # WP_TESTS_AI_ANTHROPIC_API_KEY= # WP_TESTS_AI_GOOGLE_API_KEY= # WP_TESTS_AI_OPENAI_API_KEY= +# +# Model IDs to use instead of the default models, such as `gemini-3.5-flash-lite`. # WP_TESTS_AI_ANTHROPIC_MODEL= # WP_TESTS_AI_GOOGLE_MODEL= # WP_TESTS_AI_OPENAI_MODEL= diff --git a/tests/phpunit/manual/wpAiClientLiveProviders.php b/tests/phpunit/manual/wpAiClientLiveProviders.php index 15148abeee687..f119030aa1652 100644 --- a/tests/phpunit/manual/wpAiClientLiveProviders.php +++ b/tests/phpunit/manual/wpAiClientLiveProviders.php @@ -39,14 +39,23 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase { /** - * Provider classes keyed by provider ID. + * Provider classes and the namespaces of their packages, keyed by provider ID. * - * @var array + * @var array */ private const PROVIDERS = array( - 'anthropic' => AnthropicProvider::class, - 'google' => GoogleProvider::class, - 'openai' => OpenAiProvider::class, + 'anthropic' => array( + 'class' => AnthropicProvider::class, + 'namespace' => 'WordPress\\AnthropicAiProvider\\', + ), + 'google' => array( + 'class' => GoogleProvider::class, + 'namespace' => 'WordPress\\GoogleAiProvider\\', + ), + 'openai' => array( + 'class' => OpenAiProvider::class, + 'namespace' => 'WordPress\\OpenAiAiProvider\\', + ), ); /** @@ -127,20 +136,14 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void ); update_option( 'timezone_string', 'Pacific/Chatham' ); - // The core abilities can only be registered while their registration actions run. - // Pop in finally so a setup exception cannot leave the simulated action on the stack. - $wp_current_filter[] = 'wp_abilities_api_categories_init'; + // The core abilities and their categories can only be registered while their registration actions run. + // Pop in finally so a setup exception cannot leave the simulated actions on the stack. + array_push( $wp_current_filter, 'wp_abilities_api_categories_init', 'wp_abilities_api_init' ); try { wp_register_core_ability_categories(); - } finally { - array_pop( $wp_current_filter ); - } - - $wp_current_filter[] = 'wp_abilities_api_init'; - try { wp_register_core_abilities(); } finally { - array_pop( $wp_current_filter ); + array_splice( $wp_current_filter, -2 ); } } @@ -226,7 +229,7 @@ public static function data_providers_and_abilities(): array { * that ran and the model ID. */ private function ask( string $provider, array $abilities, string $question ): array { - $provider_class = self::PROVIDERS[ $provider ]; + $provider_class = self::PROVIDERS[ $provider ]['class']; $prefix = 'WP_TESTS_AI_' . strtoupper( $provider ); $key_var = "{$prefix}_API_KEY"; $model_var = "{$prefix}_MODEL"; @@ -252,13 +255,11 @@ private function ask( string $provider, array $abilities, string $question ): ar */ try { $provider_class::modelMetadataDirectory()->listModelMetadata(); - } catch ( ClientException $e ) { - if ( 429 !== $e->getCode() ) { + } catch ( ClientException | NetworkException | ServerException $e ) { + if ( $e instanceof ClientException && 429 !== $e->getCode() ) { $this->fail( "The model list request failed, check the $key_var: " . $e->getMessage() ); } $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); - } catch ( NetworkException | ServerException $e ) { - $this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() ); } if ( $model && ! $provider_class::modelMetadataDirectory()->hasModelMetadata( $model ) ) { @@ -345,11 +346,11 @@ private function ask( string $provider, array $abilities, string $question ): ar * of the provider packages are loaded, from their `src` directories. */ private static function register_provider_autoloaders(): void { - foreach ( self::PROVIDERS as $provider => $provider_class ) { - $namespace = strstr( $provider_class, '\\Provider\\', true ) . '\\'; + foreach ( self::PROVIDERS as $provider => $package ) { + $namespace = $package['namespace']; $package_dir = dirname( __DIR__, 3 ) . "/vendor/wordpress/ai-provider-for-$provider/src/"; - if ( class_exists( $provider_class ) || ! is_dir( $package_dir ) ) { + if ( class_exists( $package['class'] ) || ! is_dir( $package_dir ) ) { continue; } diff --git a/wp-tests-config-sample.php b/wp-tests-config-sample.php index feaea8dc40826..421b915c1988b 100644 --- a/wp-tests-config-sample.php +++ b/wp-tests-config-sample.php @@ -25,9 +25,10 @@ /* * API keys and models for the live AI provider tests, which send real requests. - * An environment variable of the same name takes precedence over each constant. - * The tests of a provider are skipped while its key is not set, and a provider - * uses its default model while its model is not set. + * A non-empty environment variable of the same name takes precedence over each + * constant. The tests of a provider are skipped while its key is not set, and a + * provider uses its default model while its model is not set. A model is set by + * its ID, such as `gemini-3.5-flash-lite`. */ // define( 'WP_TESTS_AI_ANTHROPIC_API_KEY', '' ); // define( 'WP_TESTS_AI_GOOGLE_API_KEY', '' );