Automattic\WooCommerce\Blocks\AI

Connection::fetch_ai_responses()publicWC 1.0

Fetch the AI responses in parallel using the given token and prompts.

Method of the class: Connection{}

No Hooks.

Return

Array|WP_Error. The responses or a WP_Error object.

Usage

$Connection = new Connection();
$Connection->fetch_ai_responses( $token, $prompts, $timeout, $response_format );
$token(string) (required)
The JWT token.
$prompts(array) (required)
The prompts to send to the API.
$timeout(int)
The timeout for the request.
Default: 15
$response_format(string)
The response format.
Default: null

Connection::fetch_ai_responses() code WC 9.4.2

public function fetch_ai_responses( $token, array $prompts, $timeout = 15, $response_format = null ) {
	if ( $token instanceof \WP_Error ) {
		return $token;
	}

	$requests = array();
	foreach ( $prompts as $prompt ) {
		$data = array(
			'feature' => 'woocommerce_blocks_patterns',
			'prompt'  => $prompt,
			'token'   => $token,
			'model'   => self::MODEL,
		);

		if ( $response_format ) {
			$data['response_format'] = $response_format;
		}

		$requests[] = array(
			'url'     => self::TEXT_COMPLETION_API_URL,
			'type'    => 'POST',
			'headers' => array( 'Content-Type' => 'application/json; charset=utf-8' ),
			'data'    => wp_json_encode( $data ),
		);
	}

	$responses = Requests::request_multiple( $requests, array( 'timeout' => $timeout ) );

	$processed_responses = array();

	foreach ( $responses as $key => $response ) {
		if ( is_wp_error( $response ) || is_a( $response, Exception::class ) ) {
			return new WP_Error( 'failed-to-connect-with-the-ai-endpoint', esc_html__( 'Failed to connect with the AI endpoint: try again later.', 'woocommerce' ) );
		}

		$processed_responses[ $key ] = json_decode( $response->body, true );
	}

	return $processed_responses;
}