Automattic\WooCommerce\Blocks\AI

Connection::fetch_ai_response()publicWC 1.0

The post request.

Method of the class: Connection{}

No Hooks.

Return

Mixed.

Usage

$Connection = new Connection();
$Connection->fetch_ai_response( $token, $prompt, $timeout, $response_format );
$token(string) (required)
The JWT token.
$prompt(string) (required)
The prompt 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_response() code WC 9.3.3

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

	$body = array(
		'feature' => 'woocommerce_blocks_patterns',
		'prompt'  => $prompt,
		'token'   => $token,
		'model'   => self::MODEL,
	);

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

	$response = wp_remote_post(
		self::TEXT_COMPLETION_API_URL,
		array(
			'body'    => $body,
			'timeout' => $timeout,
		)
	);

	if ( is_wp_error( $response ) ) {
		return new \WP_Error( $response->get_error_code(), esc_html__( 'Failed to connect with the AI endpoint: try again later.', 'woocommerce' ), $response->get_error_message() );
	}

	$body = wp_remote_retrieve_body( $response );

	return json_decode( $body, true );
}