[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ai-client/ -> class-wp-ai-client-prompt-builder.php (source)

   1  <?php
   2  /**
   3   * WP AI Client: WP_AI_Client_Prompt_Builder class
   4   *
   5   * @package WordPress
   6   * @subpackage AI
   7   * @since 7.0.0
   8   */
   9  
  10  use WordPress\AiClient\AiClient;
  11  use WordPress\AiClient\Builders\PromptBuilder;
  12  use WordPress\AiClient\Files\DTO\File;
  13  use WordPress\AiClient\Files\Enums\FileTypeEnum;
  14  use WordPress\AiClient\Files\Enums\MediaOrientationEnum;
  15  use WordPress\AiClient\Messages\DTO\Message;
  16  use WordPress\AiClient\Messages\DTO\MessagePart;
  17  use WordPress\AiClient\Messages\Enums\ModalityEnum;
  18  use WordPress\AiClient\Providers\Http\DTO\RequestOptions;
  19  use WordPress\AiClient\Providers\Models\Contracts\ModelInterface;
  20  use WordPress\AiClient\Providers\Models\DTO\ModelConfig;
  21  use WordPress\AiClient\Providers\Models\Enums\CapabilityEnum;
  22  use WordPress\AiClient\Providers\ProviderRegistry;
  23  use WordPress\AiClient\Results\DTO\GenerativeAiResult;
  24  use WordPress\AiClient\Tools\DTO\FunctionDeclaration;
  25  use WordPress\AiClient\Tools\DTO\FunctionResponse;
  26  use WordPress\AiClient\Tools\DTO\WebSearch;
  27  
  28  /**
  29   * Fluent builder for constructing AI prompts, returning WP_Error on failure.
  30   *
  31   * This class provides a fluent interface for building prompts with various
  32   * content types and model configurations. It wraps the PHP AI Client SDK's
  33   * PromptBuilder and adds WordPress-specific behavior including WP_Error
  34   * handling instead of exceptions, snake_case method naming, and integration
  35   * with the Abilities API.
  36   *
  37   * Only the generating methods will return a WP_Error, to not break the fluent
  38   * interface. As soon as any exception is caught in a chain of method calls,
  39   * the returned instance will be in an error state, and all subsequent method
  40   * calls will be no-ops that just return the same error state instance. Only
  41   * when a generating method is called, the WP_Error will be returned. The
  42   * support check methods are the exception to the no-op behavior: they return
  43   * false rather than the error state instance.
  44   *
  45   * @since 7.0.0
  46   * @since 7.2.0 Now extends the `WP_AI_Client_Builder` base class.
  47   *
  48   * @see WP_AI_Client_Builder
  49   *
  50   * @phpstan-import-type Prompt from PromptBuilder
  51   *
  52   * @method self with_text(string $text) Adds text to the current message.
  53   * @method self with_file($file, ?string $mimeType = null) Adds a file to the current message.
  54   * @method self with_function_response(FunctionResponse $functionResponse) Adds a function response to the current message.
  55   * @method self with_message_parts(MessagePart ...$parts) Adds message parts to the current message.
  56   * @method self with_history(Message ...$messages) Adds conversation history messages.
  57   * @method self using_model(ModelInterface $model) Sets the model to use for generation.
  58   * @method self using_model_preference(...$preferredModels) Sets preferred models to evaluate in order.
  59   * @method self using_model_config(ModelConfig $config) Sets the model configuration.
  60   * @method self using_provider(string $providerIdOrClassName) Sets the provider to use for generation.
  61   * @method self using_system_instruction(string $systemInstruction) Sets the system instruction.
  62   * @method self using_max_tokens(int $maxTokens) Sets the maximum number of tokens to generate.
  63   * @method self using_temperature(float $temperature) Sets the temperature for generation.
  64   * @method self using_top_p(float $topP) Sets the top-p value for generation.
  65   * @method self using_top_k(int $topK) Sets the top-k value for generation.
  66   * @method self using_stop_sequences(string ...$stopSequences) Sets stop sequences for generation.
  67   * @method self using_candidate_count(int $candidateCount) Sets the number of candidates to generate.
  68   * @method self using_function_declarations(FunctionDeclaration ...$functionDeclarations) Sets the function declarations available to the model.
  69   * @method self using_presence_penalty(float $presencePenalty) Sets the presence penalty for generation.
  70   * @method self using_frequency_penalty(float $frequencyPenalty) Sets the frequency penalty for generation.
  71   * @method self using_web_search(WebSearch $webSearch) Sets the web search configuration.
  72   * @method self using_request_options(RequestOptions $options) Sets the request options for HTTP transport.
  73   * @method self using_top_logprobs(?int $topLogprobs = null) Sets the top log probabilities configuration.
  74   * @method self as_output_mime_type(string $mimeType) Sets the output MIME type.
  75   * @method self as_output_schema(array<string, mixed> $schema) Sets the output schema.
  76   * @method self as_output_modalities(ModalityEnum ...$modalities) Sets the output modalities.
  77   * @method self as_output_file_type(FileTypeEnum $fileType) Sets the output file type.
  78   * @method self as_output_media_orientation(MediaOrientationEnum $orientation) Sets the output media orientation.
  79   * @method self as_output_media_aspect_ratio(string $aspectRatio) Sets the output media aspect ratio.
  80   * @method self as_output_speech_voice(string $voice) Sets the output speech voice.
  81   * @method self as_json_response(?array<string, mixed> $schema = null) Configures the prompt for JSON response output.
  82   * @method bool is_supported(?CapabilityEnum $capability = null) Checks if the prompt is supported for the given capability.
  83   * @method bool is_supported_for_text_generation() Checks if the prompt is supported for text generation.
  84   * @method bool is_supported_for_image_generation() Checks if the prompt is supported for image generation.
  85   * @method bool is_supported_for_text_to_speech_conversion() Checks if the prompt is supported for text to speech conversion.
  86   * @method bool is_supported_for_video_generation() Checks if the prompt is supported for video generation.
  87   * @method bool is_supported_for_speech_generation() Checks if the prompt is supported for speech generation.
  88   * @method bool is_supported_for_music_generation() Checks if the prompt is supported for music generation.
  89   * @method bool is_supported_for_embedding_generation() Checks if the prompt is supported for embedding generation.
  90   * @method GenerativeAiResult|WP_Error generate_result(?CapabilityEnum $capability = null) Generates a result from the prompt.
  91   * @method GenerativeAiResult|WP_Error generate_text_result() Generates a text result from the prompt.
  92   * @method GenerativeAiResult|WP_Error generate_image_result() Generates an image result from the prompt.
  93   * @method GenerativeAiResult|WP_Error generate_speech_result() Generates a speech result from the prompt.
  94   * @method GenerativeAiResult|WP_Error convert_text_to_speech_result() Converts text to speech and returns the result.
  95   * @method GenerativeAiResult|WP_Error generate_video_result() Generates a video result from the prompt.
  96   * @method string|WP_Error generate_text() Generates text from the prompt.
  97   * @method list<string>|WP_Error generate_texts(?int $candidateCount = null) Generates multiple text candidates from the prompt.
  98   * @method File|WP_Error generate_image() Generates an image from the prompt.
  99   * @method list<File>|WP_Error generate_images(?int $candidateCount = null) Generates multiple images from the prompt.
 100   * @method File|WP_Error convert_text_to_speech() Converts text to speech.
 101   * @method list<File>|WP_Error convert_text_to_speeches(?int $candidateCount = null) Converts text to multiple speech outputs.
 102   * @method File|WP_Error generate_speech() Generates speech from the prompt.
 103   * @method list<File>|WP_Error generate_speeches(?int $candidateCount = null) Generates multiple speech outputs from the prompt.
 104   * @method File|WP_Error generate_video() Generates a video from the prompt.
 105   * @method list<File>|WP_Error generate_videos(?int $candidateCount = null) Generates multiple videos from the prompt.
 106   */
 107  class WP_AI_Client_Prompt_Builder extends WP_AI_Client_Builder {
 108  
 109      /**
 110       * List of methods that generate a result from the prompt.
 111       *
 112       * Structured as a map for faster lookups.
 113       *
 114       * @since 7.0.0
 115       * @var array<string, bool>
 116       */
 117      private static array $generating_methods = array(
 118          'generate_result'               => true,
 119          'generate_text_result'          => true,
 120          'generate_image_result'         => true,
 121          'generate_speech_result'        => true,
 122          'convert_text_to_speech_result' => true,
 123          'generate_video_result'         => true,
 124          'generate_text'                 => true,
 125          'generate_texts'                => true,
 126          'generate_image'                => true,
 127          'generate_images'               => true,
 128          'convert_text_to_speech'        => true,
 129          'convert_text_to_speeches'      => true,
 130          'generate_speech'               => true,
 131          'generate_speeches'             => true,
 132          'generate_video'                => true,
 133          'generate_videos'               => true,
 134      );
 135  
 136      /**
 137       * List of methods that check whether the prompt is supported.
 138       *
 139       * Structured as a map for faster lookups.
 140       *
 141       * @since 7.0.0
 142       * @var array<string, bool>
 143       */
 144      private static array $support_check_methods = array(
 145          'is_supported'                               => true,
 146          'is_supported_for_text_generation'           => true,
 147          'is_supported_for_image_generation'          => true,
 148          'is_supported_for_text_to_speech_conversion' => true,
 149          'is_supported_for_video_generation'          => true,
 150          'is_supported_for_speech_generation'         => true,
 151          'is_supported_for_music_generation'          => true,
 152          'is_supported_for_embedding_generation'      => true,
 153      );
 154  
 155      /**
 156       * Registers WordPress abilities as function declarations for the AI model.
 157       *
 158       * Converts each WP_Ability to a FunctionDeclaration using the wpab__ prefix
 159       * naming convention and passes them to the underlying prompt builder.
 160       *
 161       * @since 7.0.0
 162       *
 163       * @param WP_Ability|string ...$abilities The abilities to register, either as WP_Ability objects or ability name strings.
 164       * @return self The current instance for method chaining.
 165       */
 166  	public function using_abilities( ...$abilities ): self {
 167          $declarations = array();
 168  
 169          foreach ( $abilities as $ability ) {
 170              if ( is_string( $ability ) ) {
 171                  $ability_name = $ability;
 172                  $ability      = wp_get_ability( $ability );
 173                  if ( ! $ability ) {
 174                      _doing_it_wrong(
 175                          __METHOD__,
 176                          sprintf(
 177                              /* translators: %s: string value of the ability name. */
 178                              __( 'The ability %s was not found.' ),
 179                              '<code>' . esc_html( $ability_name ) . '</code>'
 180                          ),
 181                          '7.0.0'
 182                      );
 183                      continue;
 184                  }
 185              }
 186  
 187              // This is only here as a sanity check, the method signature should ensure this already.
 188              if ( ! $ability instanceof WP_Ability ) {
 189                  continue;
 190              }
 191  
 192              $function_name = WP_AI_Client_Ability_Function_Resolver::ability_name_to_function_name( $ability->get_name() );
 193              $input_schema  = wp_prepare_json_schema_for_client( $ability->get_input_schema() );
 194  
 195              $declarations[] = new FunctionDeclaration(
 196                  $function_name,
 197                  $ability->get_description(),
 198                  ! empty( $input_schema ) ? $input_schema : null
 199              );
 200          }
 201  
 202          if ( ! empty( $declarations ) ) {
 203              return $this->using_function_declarations( ...$declarations );
 204          }
 205  
 206          return $this;
 207      }
 208  
 209      /**
 210       * Creates the wrapped prompt builder instance from the PHP AI Client SDK.
 211       *
 212       * @since 7.2.0
 213       *
 214       * @param ProviderRegistry $registry The provider registry for finding suitable models.
 215       * @param Prompt           $prompt   Initial prompt content, or null.
 216       *                                   A string for simple text prompts,
 217       *                                   a MessagePart or Message object for
 218       *                                   structured content, an array for a
 219       *                                   message array shape, or a list of
 220       *                                   parts or messages for multi-turn
 221       *                                   conversations.
 222       * @return PromptBuilder The SDK prompt builder instance.
 223       */
 224  	protected function create_sdk_builder( ProviderRegistry $registry, $prompt ): object {
 225          return new PromptBuilder( $registry, $prompt, AiClient::getEventDispatcher() );
 226      }
 227  
 228      /**
 229       * Retrieves the prefix used for WP_Error codes created by this builder.
 230       *
 231       * @since 7.2.0
 232       *
 233       * @return string The error code prefix.
 234       */
 235  	protected function get_error_code_prefix(): string {
 236          return 'prompt';
 237      }
 238  
 239      /**
 240       * Retrieves the error message to use when the prompt is prevented by a filter.
 241       *
 242       * @since 7.2.0
 243       *
 244       * @return string The translated error message.
 245       */
 246  	protected function get_prevented_error_message(): string {
 247          return __( 'Prompt execution was prevented by a filter.' );
 248      }
 249  
 250      /**
 251       * Checks whether the prompt is prevented by the `wp_ai_client_prevent_prompt` filter.
 252       *
 253       * @since 7.2.0
 254       *
 255       * @return bool Whether the prompt is prevented.
 256       */
 257  	protected function is_prevented_by_filter(): bool {
 258          /**
 259           * Filters whether to prevent the prompt from being executed.
 260           *
 261           * @since 7.0.0
 262           *
 263           * @param bool                        $prevent Whether to prevent the prompt. Default false.
 264           * @param WP_AI_Client_Prompt_Builder $builder A clone of the prompt builder instance (read-only).
 265           */
 266          return (bool) apply_filters( 'wp_ai_client_prevent_prompt', false, clone $this );
 267      }
 268  
 269      /**
 270       * Retrieves the methods that generate a result from the prompt.
 271       *
 272       * @since 7.2.0
 273       *
 274       * @return array<string, bool> The generating methods map.
 275       */
 276  	protected function get_generating_methods(): array {
 277          return self::$generating_methods;
 278      }
 279  
 280      /**
 281       * Retrieves the methods that check whether the prompt is supported.
 282       *
 283       * @since 7.2.0
 284       *
 285       * @return array<string, bool> The support check methods map.
 286       */
 287  	protected function get_support_check_methods(): array {
 288          return self::$support_check_methods;
 289      }
 290  }


Generated : Sun Nov 1 08:20:35 2026 Cross-referenced by PHPXref