Skip to content

Commit c28ea0b

Browse files
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.
1 parent a396057 commit c28ea0b

4 files changed

Lines changed: 84 additions & 63 deletions

File tree

‎.env.example‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,10 +91,12 @@ LOCAL_WP_TESTS_DOMAIN=example.org
9191
#
9292
# The tests of a provider are skipped while its key is not set. A provider uses its
9393
# default model unless its `WP_TESTS_AI_*_MODEL` variable names another one.
94+
#
95+
# Only the tests read these names, so the keys are not used by the local site.
9496
##
95-
# ANTHROPIC_API_KEY=
96-
# GOOGLE_API_KEY=
97-
# OPENAI_API_KEY=
97+
# WP_TESTS_AI_ANTHROPIC_API_KEY=
98+
# WP_TESTS_AI_GOOGLE_API_KEY=
99+
# WP_TESTS_AI_OPENAI_API_KEY=
98100
# WP_TESTS_AI_ANTHROPIC_MODEL=
99101
# WP_TESTS_AI_GOOGLE_MODEL=
100102
# WP_TESTS_AI_OPENAI_MODEL=

‎composer.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,9 @@
5656
"phpstan/phpstan-phpunit": "2.1.2",
5757
"phpstan/phpstan-strict-rules": "2.1.2",
5858
"yoast/phpunit-polyfills": "^1.1.0",
59-
"wordpress/ai-provider-for-anthropic": "^1.0.5",
60-
"wordpress/ai-provider-for-google": "^1.2.1",
61-
"wordpress/ai-provider-for-openai": "^1.2.0"
59+
"wordpress/ai-provider-for-anthropic": "1.0.5",
60+
"wordpress/ai-provider-for-google": "1.2.1",
61+
"wordpress/ai-provider-for-openai": "1.2.0"
6262
},
6363
"config": {
6464
"audit": { "ignore": [ "GHSA-hmqg-cxww-wqhq", "PKSA-rdkp-vv9z-mjkg" ] },

‎docker-compose.yml‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,10 @@ services:
5050
GITHUB_EVENT_NAME: ${GITHUB_EVENT_NAME-false}
5151
HOST_PATH: ${PWD-}/${LOCAL_DIR-src}
5252
# Passed through for the live AI provider tests, and only when they are set.
53-
ANTHROPIC_API_KEY:
54-
GOOGLE_API_KEY:
55-
OPENAI_API_KEY:
53+
# Only the tests read these names, so the keys are not used by the local site.
54+
WP_TESTS_AI_ANTHROPIC_API_KEY:
55+
WP_TESTS_AI_GOOGLE_API_KEY:
56+
WP_TESTS_AI_OPENAI_API_KEY:
5657
WP_TESTS_AI_ANTHROPIC_MODEL:
5758
WP_TESTS_AI_GOOGLE_MODEL:
5859
WP_TESTS_AI_OPENAI_MODEL:

‎tests/phpunit/tests/ai-client/wpAiClientLiveProviders.php‎

Lines changed: 72 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,14 @@
22
/**
33
* Tests that live AI providers can call the core abilities through the AI Client.
44
*
5-
* These tests send real requests. The tests of a provider only run when its API key is in
6-
* the `ANTHROPIC_API_KEY`, `GOOGLE_API_KEY` or `OPENAI_API_KEY` environment variable:
5+
* These tests send real requests. The tests of a provider only run when its API key is in the
6+
* `WP_TESTS_AI_ANTHROPIC_API_KEY`, `WP_TESTS_AI_GOOGLE_API_KEY` or `WP_TESTS_AI_OPENAI_API_KEY`
7+
* environment variable:
78
*
8-
* ANTHROPIC_API_KEY=… vendor/bin/phpunit --group external-http --filter Tests_AI_Client_LiveProviders
9+
* WP_TESTS_AI_ANTHROPIC_API_KEY=… vendor/bin/phpunit --group external-http --filter Tests_AI_Client_LiveProviders
10+
*
11+
* The provider tools and the Connectors read other names, such as `ANTHROPIC_API_KEY`, so a key
12+
* set for them does not start these tests, and a key set for these tests is not used by a site.
913
*
1014
* A provider uses its default model, unless a `WP_TESTS_AI_{PROVIDER}_MODEL` environment
1115
* variable, such as `WP_TESTS_AI_GOOGLE_MODEL`, names another one.
@@ -20,20 +24,24 @@
2024

2125
use WordPress\AiClient\Messages\DTO\MessagePart;
2226
use WordPress\AiClient\Messages\DTO\UserMessage;
27+
use WordPress\AiClient\Providers\Http\DTO\ApiKeyRequestAuthentication;
2328
use WordPress\AiClient\Providers\Http\Exception\ClientException;
2429
use WordPress\AiClient\Providers\Http\Exception\NetworkException;
2530
use WordPress\AiClient\Providers\Http\Exception\ServerException;
2631
use WordPress\AiClient\Providers\ProviderRegistry;
32+
use WordPress\AnthropicAiProvider\Provider\AnthropicProvider;
33+
use WordPress\GoogleAiProvider\Provider\GoogleProvider;
34+
use WordPress\OpenAiAiProvider\Provider\OpenAiProvider;
2735

2836
class Tests_AI_Client_LiveProviders extends WP_UnitTestCase {
2937

3038
/**
3139
* Provider classes keyed by provider ID.
3240
*/
3341
private const PROVIDERS = array(
34-
'anthropic' => 'WordPress\AnthropicAiProvider\Provider\AnthropicProvider',
35-
'google' => 'WordPress\GoogleAiProvider\Provider\GoogleProvider',
36-
'openai' => 'WordPress\OpenAiAiProvider\Provider\OpenAiProvider',
42+
'anthropic' => AnthropicProvider::class,
43+
'google' => GoogleProvider::class,
44+
'openai' => OpenAiProvider::class,
3745
);
3846

3947
/**
@@ -48,6 +56,11 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase {
4856
'core/content-query' => array( 'What is the title of the post with the slug "live-provider-post"?', 'Quokka Lighthouse Notes' ),
4957
);
5058

59+
/**
60+
* How many requests a model may take to answer.
61+
*/
62+
private const MAX_ROUNDS = 6;
63+
5164
/**
5265
* ID of the administrator who asks the questions.
5366
*
@@ -61,6 +74,8 @@ class Tests_AI_Client_LiveProviders extends WP_UnitTestCase {
6174
* @param WP_UnitTest_Factory $factory Factory instance.
6275
*/
6376
public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void {
77+
global $wp_current_filter;
78+
6479
self::$admin_id = $factory->user->create(
6580
array(
6681
'role' => 'administrator',
@@ -82,9 +97,8 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void
8297
);
8398
$factory->post->create(
8499
array(
85-
'post_author' => self::$admin_id,
86-
'post_name' => 'live-provider-post',
87-
'post_title' => 'Quokka Lighthouse Notes',
100+
'post_name' => 'live-provider-post',
101+
'post_title' => 'Quokka Lighthouse Notes',
88102
)
89103
);
90104

@@ -95,23 +109,14 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void
95109
wp_unregister_ability_category( $ability_category->get_slug() );
96110
}
97111

98-
remove_action( 'wp_abilities_api_categories_init', '_unhook_core_ability_categories_registration', 1 );
99-
remove_action( 'wp_abilities_api_init', '_unhook_core_abilities_registration', 1 );
100-
101-
add_action( 'wp_abilities_api_categories_init', 'wp_register_core_ability_categories' );
102-
add_action( 'wp_abilities_api_init', 'wp_register_core_abilities' );
103-
do_action( 'wp_abilities_api_categories_init' );
104-
do_action( 'wp_abilities_api_init' );
112+
// The core abilities can only be registered while their registration actions run.
113+
$wp_current_filter[] = 'wp_abilities_api_categories_init';
114+
wp_register_core_ability_categories();
115+
array_pop( $wp_current_filter );
105116

106-
/*
107-
* Restore the hooks right away instead of after the class. The first test of a run
108-
* snapshots the hooks and every test resets them to that snapshot, so changes left
109-
* here would leak into every later test whenever this class runs first.
110-
*/
111-
remove_action( 'wp_abilities_api_categories_init', 'wp_register_core_ability_categories' );
112-
remove_action( 'wp_abilities_api_init', 'wp_register_core_abilities' );
113-
add_action( 'wp_abilities_api_categories_init', '_unhook_core_ability_categories_registration', 1 );
114-
add_action( 'wp_abilities_api_init', '_unhook_core_abilities_registration', 1 );
117+
$wp_current_filter[] = 'wp_abilities_api_init';
118+
wp_register_core_abilities();
119+
array_pop( $wp_current_filter );
115120
}
116121

117122
/**
@@ -156,15 +161,16 @@ public function set_up(): void {
156161
*/
157162
public function test_provider_answers_with_core_abilities( string $provider, array $abilities ): void {
158163
$questions = array_intersect_key( self::QUESTIONS, array_flip( $abilities ) );
159-
$called = array();
160-
$answer = $this->ask( $provider, $abilities, implode( ' ', array_column( $questions, 0 ) ), $called );
164+
165+
list( $answer, $called, $model ) = $this->ask( $provider, $abilities, implode( ' ', array_column( $questions, 0 ) ) );
161166

162167
// A model may quote a value as it is in the JSON it received, where slashes are escaped.
163168
$answer = str_replace( '\/', '/', $answer );
164169
$missing = array_filter( array_column( $questions, 1 ), static fn ( $value ) => false === stripos( $answer, $value ) );
170+
$context = "Model: $model. Answer: $answer";
165171

166-
$this->assertSameSets( $abilities, array_unique( $called ), 'The model should call every ability it is given.' );
167-
$this->assertSame( array(), array_values( $missing ), "The answer should contain every expected value. Answer: $answer" );
172+
$this->assertSameSets( $abilities, $called, "Every ability given to the model should run without an error. $context" );
173+
$this->assertSame( array(), $missing, "The answer should contain every expected value. $context" );
168174
}
169175

170176
/**
@@ -196,89 +202,101 @@ public static function data_providers_and_abilities(): array {
196202
* @param string $provider Provider ID.
197203
* @param string[] $abilities Names of the abilities given to the model.
198204
* @param string $question The question.
199-
* @param string[] $called Receives the name of the ability of each call.
200-
* @return string The answer.
205+
* @return array{0: string, 1: string[], 2: string} The answer, the names of the abilities
206+
* that ran without an error and the model ID.
201207
*/
202-
private function ask( string $provider, array $abilities, string $question, array &$called ): string {
203-
$key_name = strtoupper( $provider ) . '_API_KEY';
204-
if ( ! getenv( $key_name ) ) {
208+
private function ask( string $provider, array $abilities, string $question ): array {
209+
$provider_class = self::PROVIDERS[ $provider ];
210+
$key_name = 'WP_TESTS_AI_' . strtoupper( $provider ) . '_API_KEY';
211+
$model_name = 'WP_TESTS_AI_' . strtoupper( $provider ) . '_MODEL';
212+
$api_key = getenv( $key_name );
213+
$model = getenv( $model_name );
214+
215+
if ( ! $api_key ) {
205216
$this->markTestSkipped( "The $key_name environment variable is not set." );
206217
}
207-
if ( ! class_exists( self::PROVIDERS[ $provider ] ) ) {
218+
if ( ! class_exists( $provider_class ) ) {
208219
$this->markTestSkipped( 'The AI provider packages are not installed. Run `composer update`.' );
209220
}
210221

211-
// A registry of its own keeps the provider out of the default registry other tests use.
212222
$registry = new ProviderRegistry();
213-
$registry->registerProvider( self::PROVIDERS[ $provider ] );
223+
$registry->registerProvider( $provider_class );
224+
$registry->setProviderRequestAuthentication( $provider, new ApiKeyRequestAuthentication( $api_key ) );
214225

215226
/*
216227
* The AI Client reports a provider whose models cannot be listed as one without models,
217228
* so list them here to get the reason. A successful list is cached for the requests below.
218229
* Any other exception, such as a response the provider changed, is an error of the test.
219230
*/
220231
try {
221-
self::PROVIDERS[ $provider ]::modelMetadataDirectory()->listModelMetadata();
232+
$models = $provider_class::modelMetadataDirectory()->listModelMetadata();
222233
} catch ( NetworkException | ServerException $e ) {
223234
$this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() );
224235
} catch ( ClientException $e ) {
225236
if ( 429 === $e->getCode() ) {
226237
$this->markTestSkipped( 'The provider is unavailable: ' . $e->getMessage() );
227238
}
228-
$this->fail( "The provider rejected the $key_name: " . $e->getMessage() );
239+
$this->fail( "The model list request failed, check the $key_name: " . $e->getMessage() );
240+
}
241+
242+
// A model preference that matches no model would fall back to another model without an error.
243+
if ( $model && ! in_array( $model, array_map( static fn ( $metadata ) => $metadata->getId(), $models ), true ) ) {
244+
$this->fail( "The provider has no \"$model\" model, check the $model_name." );
229245
}
230246

231247
$resolver = new WP_AI_Client_Ability_Function_Resolver( ...$abilities );
232248
$messages = array( new UserMessage( array( new MessagePart( $question ) ) ) );
249+
$called = array();
233250

234-
for ( $round = 0; $round < 6; $round++ ) {
251+
for ( $round = 0; $round < self::MAX_ROUNDS; $round++ ) {
235252
$builder = ( new WP_AI_Client_Prompt_Builder( $registry, $messages ) )
236253
->using_provider( $provider )
237254
->using_system_instruction( 'Answer every question with the abilities. Quote the values they return unchanged.' )
238255
->using_abilities( ...$abilities );
239256

240-
$model = getenv( 'WP_TESTS_AI_' . strtoupper( $provider ) . '_MODEL' );
241257
if ( $model ) {
242258
$builder->using_model_preference( $model );
243259
}
244260

245261
$result = $builder->generate_text_result();
246262

247263
if ( is_wp_error( $result ) ) {
248-
$status = $result->get_error_data()['status'] ?? 0;
249-
$message = "($status): " . $result->get_error_message();
264+
$status = $result->get_error_data()['status'] ?? 0;
265+
$error = "($status): " . $result->get_error_message();
250266

251267
// Only a rate limit, a server error of the provider and a network error skip the test.
252268
if ( 429 === $status || in_array( $result->get_error_code(), array( 'prompt_network_error', 'prompt_upstream_server_error' ), true ) ) {
253-
$this->markTestSkipped( "The provider is unavailable $message" );
269+
$this->markTestSkipped( "The provider is unavailable $error" );
254270
}
255-
$this->fail( "The request failed $message" );
271+
$this->fail( "The request failed $error" );
256272
}
257273

258-
// OpenAI returns each function call as its own candidate, so keep them all, not just toMessage().
274+
// OpenAI returns each function call as its own candidate, so keep the message of each one.
259275
$has_calls = false;
260-
foreach ( $result->getCandidates() as $candidate ) {
261-
$message = $candidate->getMessage();
276+
foreach ( $result->toMessages() as $message ) {
262277
$messages[] = $message;
263278

264279
if ( ! $resolver->has_ability_calls( $message ) ) {
265280
continue;
266281
}
267282

268-
foreach ( $message->getParts() as $part ) {
269-
if ( $part->getFunctionCall() ) {
270-
$called[] = WP_AI_Client_Ability_Function_Resolver::function_name_to_ability_name( $part->getFunctionCall()->getName() );
283+
// Only an ability that ran without an error counts as called.
284+
$response = $resolver->execute_abilities( $message );
285+
foreach ( $response->getParts() as $part ) {
286+
$data = $part->getFunctionResponse()->getResponse();
287+
if ( ! is_array( $data ) || ! isset( $data['error'] ) ) {
288+
$called[] = WP_AI_Client_Ability_Function_Resolver::function_name_to_ability_name( $part->getFunctionResponse()->getName() );
271289
}
272290
}
273-
$messages[] = $resolver->execute_abilities( $message );
291+
$messages[] = $response;
274292
$has_calls = true;
275293
}
276294

277295
if ( ! $has_calls ) {
278-
return implode( "\n", $result->toTexts() );
296+
return array( implode( "\n", $result->toTexts() ), array_unique( $called ), $result->getModelMetadata()->getId() );
279297
}
280298
}
281299

282-
$this->fail( 'The model kept calling abilities without answering.' );
300+
$this->fail( 'The model kept calling abilities without answering. Abilities that ran: ' . implode( ', ', array_unique( $called ) ) );
283301
}
284302
}

0 commit comments

Comments
 (0)