Automattic\WooCommerce\Blocks\AIContent

UpdatePatterns::fetch_and_validate_ai_responses()privateWC 1.0

Fetches and validates the AI responses.

Метод класса: UpdatePatterns{}

Хуков нет.

Возвращает

Массив|Разное.

Использование

// private - только в коде основоного (родительского) класса
$result = $this->fetch_and_validate_ai_responses( $ai_connection, $token, $formatted_prompts, $expected_results_format );
$ai_connection(Connection) (обязательный)
The AI connection.
$token(строка|WP_Error) (обязательный)
The JWT token.
$formatted_prompts(массив) (обязательный)
The array of formatted prompts.
$expected_results_format(массив) (обязательный)
The array of expected results format.

Код UpdatePatterns::fetch_and_validate_ai_responses() WC 9.4.2

private function fetch_and_validate_ai_responses( $ai_connection, $token, $formatted_prompts, $expected_results_format ) {
	$ai_request_retries = 0;
	$ai_responses       = [];
	$success            = false;
	while ( $ai_request_retries < 5 && ! $success ) {
		$ai_request_retries ++;
		$ai_responses = $ai_connection->fetch_ai_responses( $token, $formatted_prompts, 60, 'json_object' );

		if ( is_wp_error( $ai_responses ) ) {
			continue;
		}

		if ( empty( $ai_responses ) ) {
			continue;
		}

		$loops_success = [];
		$i             = 0;
		foreach ( $ai_responses as $ai_response ) {
			if ( ! isset( $ai_response['completion'] ) ) {
				$loops_success[] = false;
				continue;
			}

			$completion = json_decode( $ai_response['completion'], true );

			if ( ! is_array( $completion ) ) {
				$loops_success[] = false;
				continue;
			}

			$diff = array_diff_key( $expected_results_format[ $i ], $completion );
			$i ++;

			if ( ! empty( $diff ) ) {
				$loops_success[] = false;
				continue;
			}

			$empty_results = false;
			foreach ( $completion as $completion_item ) {
				foreach ( $completion_item as $value ) {
					if ( empty( $value ) ) {
						$empty_results = true;
					}
				}
			}

			if ( $empty_results ) {
				$loops_success[] = false;
				continue;
			}

			$loops_success[] = true;
		}

		if ( ! in_array( false, $loops_success, true ) ) {
			$success = true;
		}
	}

	if ( ! $success ) {
		return new WP_Error( 'failed_to_fetch_ai_responses', __( 'Failed to fetch AI responses.', 'woocommerce' ) );
	}

	return $ai_responses;
}