getApiKey() ); } /** * {@inheritDoc} * * @since 1.0.0 */ public function generateImageResult( array $prompt ): GenerativeAiResult { if ( function_exists( 'set_time_limit' ) ) { // Allow queue poll window; hosts may still enforce a hard cap. set_time_limit( (int) self::OVERALL_TIMEOUT + 60 ); } $params = $this->prepareGenerateImageParams( $prompt ); $model_id = $this->metadata()->getId(); $submit = $this->submitToQueue( $model_id, $params ); $this->waitUntilComplete( $submit['status_url'], $submit['request_id'] ); $result = $this->fetchQueueResult( $submit['response_url'] ); if ( ! isset( $result['request_id'] ) && '' !== $submit['request_id'] ) { $result['request_id'] = $submit['request_id']; } return $this->parseResponseToGenerativeAiResult( $result ); } /** * POST to queue.fal.run and return tracking URLs. * * @since 1.1.4 * @param string $model_id Model id. * @param array $params Request body. * @return array{request_id: string, status_url: string, response_url: string} */ private function submitToQueue( string $model_id, array $params ): array { $response = $this->sendAuthenticatedRequest( HttpMethodEnum::POST(), FalProvider::queueUrl( $model_id ), $params ); ResponseUtil::throwIfNotSuccessful( $response ); $data = $response->getData(); if ( ! is_array( $data ) ) { throw ResponseException::fromInvalidData( esc_html( $this->providerMetadata()->getName() ), 'body', 'Queue submit response must be an associative array.' ); } $request_id = isset( $data['request_id'] ) && is_string( $data['request_id'] ) ? $data['request_id'] : ''; $status_url = isset( $data['status_url'] ) && is_string( $data['status_url'] ) ? $data['status_url'] : ''; $response_url = isset( $data['response_url'] ) && is_string( $data['response_url'] ) ? $data['response_url'] : ''; if ( '' === $request_id || '' === $status_url || '' === $response_url ) { throw ResponseException::fromMissingData( esc_html( $this->providerMetadata()->getName() ), 'request_id/status_url/response_url' ); } $this->assertFalQueueUrl( $status_url ); $this->assertFalQueueUrl( $response_url ); return array( 'request_id' => $request_id, 'status_url' => $status_url, 'response_url' => $response_url, ); } /** * Poll status_url until COMPLETED or failure / overall timeout. * * @since 1.1.4 * @param string $status_url Queue status URL from submit. * @param string $request_id Request id for error messages. * @return void */ private function waitUntilComplete( string $status_url, string $request_id ): void { $deadline = microtime( true ) + self::OVERALL_TIMEOUT; while ( microtime( true ) < $deadline ) { $response = $this->sendAuthenticatedRequest( HttpMethodEnum::GET(), $status_url, null ); ResponseUtil::throwIfNotSuccessful( $response ); $data = $response->getData(); if ( ! is_array( $data ) ) { throw ResponseException::fromInvalidData( esc_html( $this->providerMetadata()->getName() ), 'status', 'Queue status response must be an associative array.' ); } $status = isset( $data['status'] ) && is_string( $data['status'] ) ? strtoupper( $data['status'] ) : ''; if ( 'COMPLETED' === $status ) { if ( isset( $data['error'] ) && is_string( $data['error'] ) && '' !== $data['error'] ) { throw new ResponseException( esc_html( sprintf( /* translators: 1: request id, 2: fal error message. */ __( 'fal.ai request %1$s failed: %2$s', 'ai-provider-for-fal-ai' ), $request_id, $data['error'] ) ) ); } return; } if ( in_array( $status, array( 'FAILED', 'CANCELLED', 'CANCELED' ), true ) ) { $message = isset( $data['error'] ) && is_string( $data['error'] ) && '' !== $data['error'] ? $data['error'] : $status; throw new ResponseException( esc_html( sprintf( /* translators: 1: request id, 2: status or error. */ __( 'fal.ai request %1$s ended with status: %2$s', 'ai-provider-for-fal-ai' ), $request_id, $message ) ) ); } sleep( self::POLL_INTERVAL ); } throw new ResponseException( esc_html( sprintf( /* translators: 1: request id, 2: timeout seconds. */ __( 'fal.ai request %1$s timed out after %2$d seconds waiting in the queue.', 'ai-provider-for-fal-ai' ), $request_id, (int) self::OVERALL_TIMEOUT ) ) ); } /** * GET the final result payload from response_url. * * @since 1.1.4 * @param string $response_url Queue response URL from submit. * @return array */ private function fetchQueueResult( string $response_url ): array { $response = $this->sendAuthenticatedRequest( HttpMethodEnum::GET(), $response_url, null ); ResponseUtil::throwIfNotSuccessful( $response ); $data = $response->getData(); if ( ! is_array( $data ) ) { throw ResponseException::fromInvalidData( esc_html( $this->providerMetadata()->getName() ), 'body', 'Queue result response must be an associative array.' ); } return $data; } /** * Send an authenticated request with a short per-call HTTP timeout. * * @since 1.1.4 * @param HttpMethodEnum $method HTTP method. * @param string $uri Absolute URL. * @param array|null $body JSON body or null for GET. * @return Response */ private function sendAuthenticatedRequest( HttpMethodEnum $method, string $uri, ?array $body ): Response { $existing = $this->getRequestOptions(); $options = null !== $existing ? RequestOptions::fromArray( $existing->toArray() ) : new RequestOptions(); // Prefer short per-call timeouts so long jobs use polling, not one hung socket. if ( null === $options->getTimeout() || $options->getTimeout() > self::HTTP_TIMEOUT ) { $options->setTimeout( self::HTTP_TIMEOUT ); } $headers = array(); if ( null !== $body ) { $headers['Content-Type'] = 'application/json'; } $request = new Request( $method, $uri, $headers, $body, $options ); $request = $this->getRequestAuthentication()->authenticateRequest( $request ); return $this->getHttpTransporter()->send( $request ); } /** * Reject non-fal queue URLs (SSRF guard for URLs returned by submit). * * @since 1.1.4 * @param string $url URL from fal submit response. * @return void */ private function assertFalQueueUrl( string $url ): void { $host = wp_parse_url( $url, PHP_URL_HOST ); if ( ! is_string( $host ) || 'queue.fal.run' !== strtolower( $host ) ) { throw ResponseException::fromInvalidData( esc_html( $this->providerMetadata()->getName() ), 'url', 'Queue tracking URL must be on queue.fal.run.' ); } } /** * Build fal request body from the prompt + model config. * * @since 1.0.0 * @param list $prompt Prompt messages. * @return array */ protected function prepareGenerateImageParams( array $prompt ): array { $config = $this->getConfig(); $model_id = $this->metadata()->getId(); $params = array( 'prompt' => $this->preparePromptParam( $prompt ), 'num_images' => 1, ); $candidate_count = $config->getCandidateCount(); if ( null !== $candidate_count && $candidate_count > 0 ) { $params['num_images'] = $candidate_count; } if ( $this->supportsSharedImageSizeParam( $model_id ) ) { $image_size = $this->prepareImageSizeParam( $model_id, $config->getOutputMediaOrientation(), $config->getOutputMediaAspectRatio() ); if ( null !== $image_size ) { $params['image_size'] = $image_size; } } elseif ( $this->supportsAspectRatioParam( $model_id ) ) { $aspect = $config->getOutputMediaAspectRatio(); if ( is_string( $aspect ) && '' !== $aspect ) { $params['aspect_ratio'] = $aspect; } } $custom_options = $config->getCustomOptions(); foreach ( $custom_options as $key => $value ) { if ( isset( $params[ $key ] ) ) { throw new InvalidArgumentException( esc_html( sprintf( /* translators: %s: custom option key. */ __( 'The custom option "%s" conflicts with an existing parameter.', 'ai-provider-for-fal-ai' ), $key ) ) ); } $params[ $key ] = $value; } return $params; } /** * Whether this model accepts the shared Flux-style image_size mapping. * * @since 1.1.0 * @param string $model_id Model ID. * @return bool */ private function supportsSharedImageSizeParam( string $model_id ): bool { $with_image_size = array( 'openai/gpt-image-2', 'bytedance/seedream/v5/pro/text-to-image', ); return in_array( $model_id, $with_image_size, true ) || 0 === strpos( $model_id, 'fal-ai/flux' ) || 0 === strpos( $model_id, 'fal-ai/recraft' ); } /** * Whether this model prefers aspect_ratio over image_size. * * @since 1.1.0 * @param string $model_id Model ID. * @return bool */ private function supportsAspectRatioParam( string $model_id ): bool { return 0 === strpos( $model_id, 'fal-ai/nano-banana' ); } /** * Extract the single user text prompt. * * @since 1.0.0 * @param list $messages Prompt messages. * @return string */ protected function preparePromptParam( array $messages ): string { if ( 1 !== count( $messages ) ) { throw new InvalidArgumentException( 'The fal.ai API requires a single user message as prompt.' ); } $message = $messages[0]; if ( ! $message->getRole()->isUser() ) { throw new InvalidArgumentException( 'The fal.ai API requires a user message as prompt.' ); } $text = null; foreach ( $message->getParts() as $part ) { $text = $part->getText(); if ( null !== $text ) { break; } } if ( null === $text || '' === $text ) { throw new InvalidArgumentException( 'The fal.ai API requires a single text message part as prompt.' ); } return $text; } /** * Map orientation / aspect ratio to fal `image_size` (enum string or width/height). * * Seedream 16:9 / landscape uses explicit 2048×1152 so total area equals the * cheap billing tier ceiling (1536×1536 = 2,359,296 px) instead of a larger enum preset. * * @since 1.0.0 * @param string $model_id Model ID. * @param MediaOrientationEnum|null $orientation Orientation. * @param string|null $aspect_ratio Aspect ratio like "16:9". * @return string|array{width:int,height:int}|null */ protected function prepareImageSizeParam( string $model_id, ?MediaOrientationEnum $orientation, ?string $aspect_ratio ) { $wants_16_9 = ( '16:9' === $aspect_ratio ) || ( null === $aspect_ratio && null !== $orientation && $orientation->isLandscape() ); // Cheap-tier 16:9 for Seedream (area == 1536²). if ( $wants_16_9 && 'bytedance/seedream/v5/pro/text-to-image' === $model_id ) { return array( 'width' => 2048, 'height' => 1152, ); } if ( null !== $aspect_ratio ) { $map = array( '1:1' => 'square_hd', '16:9' => 'landscape_16_9', '9:16' => 'portrait_16_9', '4:3' => 'landscape_4_3', '3:4' => 'portrait_4_3', ); if ( isset( $map[ $aspect_ratio ] ) ) { return $map[ $aspect_ratio ]; } } if ( null !== $orientation ) { if ( $orientation->isLandscape() ) { return 'landscape_16_9'; } if ( $orientation->isPortrait() ) { return 'portrait_16_9'; } return 'square_hd'; } return null; } /** * Parse fal run response into a GenerativeAiResult. * * Expected shape (Flux family): * `{ "images": [ { "url": "...", "content_type": "image/jpeg" } ], ... }` * * @since 1.0.0 * @param mixed $response_data Decoded response body. * @return GenerativeAiResult */ protected function parseResponseToGenerativeAiResult( $response_data ): GenerativeAiResult { if ( ! is_array( $response_data ) ) { throw ResponseException::fromInvalidData( esc_html( $this->providerMetadata()->getName() ), 'body', 'The value must be an associative array.' ); } $images = $this->extractImages( $response_data ); if ( array() === $images ) { throw ResponseException::fromMissingData( esc_html( $this->providerMetadata()->getName() ), 'images' ); } $candidates = array(); foreach ( $images as $index => $image_data ) { if ( ! is_array( $image_data ) ) { throw ResponseException::fromInvalidData( esc_html( $this->providerMetadata()->getName() ), esc_html( "images[{$index}]" ), 'The value must be an associative array.' ); } $candidates[] = $this->parseImageToCandidate( $image_data, (int) $index ); } $request_id = ''; if ( isset( $response_data['request_id'] ) && is_string( $response_data['request_id'] ) ) { $request_id = $response_data['request_id']; } $provider_meta = $response_data; unset( $provider_meta['images'], $provider_meta['image'] ); return new GenerativeAiResult( $request_id, $candidates, new TokenUsage( 0, 0, 0 ), $this->providerMetadata(), $this->metadata(), $provider_meta ); } /** * Normalize various fal image payload shapes into a list. * * @since 1.0.0 * @param array $response_data Response body. * @return list */ protected function extractImages( array $response_data ): array { if ( isset( $response_data['images'] ) && is_array( $response_data['images'] ) ) { return array_values( $response_data['images'] ); } if ( isset( $response_data['image'] ) && is_array( $response_data['image'] ) ) { return array( $response_data['image'] ); } return array(); } /** * Convert one fal image object into a Candidate. * * @since 1.0.0 * @param array $image_data Image payload. * @param int $index Index in the images list. * @return Candidate */ protected function parseImageToCandidate( array $image_data, int $index ): Candidate { $mime = 'image/jpeg'; if ( isset( $image_data['content_type'] ) && is_string( $image_data['content_type'] ) ) { $mime = $image_data['content_type']; } elseif ( isset( $image_data['contentType'] ) && is_string( $image_data['contentType'] ) ) { $mime = $image_data['contentType']; } if ( isset( $image_data['url'] ) && is_string( $image_data['url'] ) && '' !== $image_data['url'] ) { // Prefer inline base64 so consumers that call getBase64Data() (e.g. WP AI plugin) work. // Fall back to remote File if download fails — URL consumers still succeed. $inline = $this->downloadUrlAsDataUri( $image_data['url'], $mime ); $image_file = $inline ? new File( $inline, $mime ) : new File( $image_data['url'], $mime ); } elseif ( isset( $image_data['file_data'] ) && is_string( $image_data['file_data'] ) ) { $image_file = new File( $image_data['file_data'], $mime ); } elseif ( isset( $image_data['b64_json'] ) && is_string( $image_data['b64_json'] ) ) { $image_file = new File( $image_data['b64_json'], $mime ); } else { throw ResponseException::fromInvalidData( esc_html( $this->providerMetadata()->getName() ), esc_html( "images[{$index}]" ), 'The value must contain a url or base64 image payload.' ); } $message = new Message( MessageRoleEnum::model(), array( new MessagePart( $image_file ) ) ); return new Candidate( $message, FinishReasonEnum::stop() ); } /** * Download a remote fal CDN URL into a data URI for inline File storage. * * @since 1.1.1 * @param string $url Remote image URL. * @param string $mime MIME type hint. * @return string|null data URI or null on failure. */ private function downloadUrlAsDataUri( string $url, string $mime ): ?string { $response = wp_remote_get( $url, array( 'timeout' => 60, ) ); if ( is_wp_error( $response ) ) { return null; } $code = (int) wp_remote_retrieve_response_code( $response ); $body = wp_remote_retrieve_body( $response ); if ( 200 !== $code || '' === $body ) { return null; } $header_type = wp_remote_retrieve_header( $response, 'content-type' ); if ( is_string( $header_type ) && '' !== $header_type ) { $mime = strtok( $header_type, ';' ) ?: $mime; } return 'data:' . $mime . ';base64,' . base64_encode( $body ); } }