PromptBuilder
- Since
- 0.1.0
- Source
wp-includes/php-ai-client/src/Builders/PromptBuilder.php:50
Fluent builder for constructing AI prompts.
Description
This class provides a fluent interface for building prompts with various content types and model configurations. It automatically infers model requirements based on the features used in the prompt.
Compatibility
- WordPress
- since 0.1.0
- 6.7.7
- 6.8.8
- 6.9.7
- 7.0.4
- 7.1.0
Present in 2 of the 5 tracked releases, added in 0.1.0.
Properties · 8
$registryWordPress\AiClient\Providers\ProviderRegistryprivate$messagesWordPress\AiClient\Builders\list<Message>protected$modelWordPress\AiClient\Providers\Models\Contracts\ModelInterface|nullprotected$modelPreferenceKeysWordPress\AiClient\Builders\list<string>protected$providerIdOrClassNamestring|nullprotected$modelConfigWordPress\AiClient\Providers\Models\DTO\ModelConfigprotected$requestOptionsWordPress\AiClient\Providers\Http\DTO\RequestOptions|nullprotected$eventDispatcherWordPress\AiClientDependencies\Psr\EventDispatcher\EventDispatcherInterface|nullprivate
Methods · 72
- __construct()Constructor.
- __clone()Creates a deep clone of this builder.
- withText()Adds text to the current message.
- withFile()Adds a file to the current message.
- withFunctionResponse()Adds a function response to the current message.
- withMessageParts()Adds message parts to the current message.
- withHistory()Adds conversation history messages.
- usingModel()Sets the model to use for generation.
- usingModelPreference()Sets preferred models to evaluate in order.
- usingModelConfig()Sets the model configuration.
- usingProvider()Sets the provider to use for generation.
- usingSystemInstruction()Sets the system instruction.
- usingMaxTokens()Sets the maximum number of tokens to generate.
- usingTemperature()Sets the temperature for generation.
- usingTopP()Sets the top-p value for generation.
- usingTopK()Sets the top-k value for generation.
- usingStopSequences()Sets stop sequences for generation.
- usingCandidateCount()Sets the number of candidates to generate.
- usingFunctionDeclarations()Sets the function declarations available to the model.
- usingPresencePenalty()Sets the presence penalty for generation.
- usingFrequencyPenalty()Sets the frequency penalty for generation.
- usingWebSearch()Sets the web search configuration.
- usingRequestOptions()Sets the request options for HTTP transport.
- usingTopLogprobs()Sets the top log probabilities configuration.
- asOutputMimeType()Sets the output MIME type.
- asOutputSchema()Sets the output schema.
- asOutputModalities()Sets the output modalities.
- asOutputFileType()Sets the output file type.
- asOutputMediaOrientation()Sets the output media orientation.
- asOutputMediaAspectRatio()Sets the output media aspect ratio.
- asOutputSpeechVoice()Sets the output speech voice.
- asJsonResponse()Configures the prompt for JSON response output.
- inferCapabilityFromOutputModalities()Infers the capability from configured output modalities.
- inferCapabilityFromModelInterfaces()Infers the capability from a model's implemented interfaces.
- isSupported()Checks if the current prompt is supported by the selected model.
- isSupportedForTextGeneration()Checks if the prompt is supported for text generation.
- isSupportedForImageGeneration()Checks if the prompt is supported for image generation.
- isSupportedForTextToSpeechConversion()Checks if the prompt is supported for text to speech conversion.
- isSupportedForVideoGeneration()Checks if the prompt is supported for video generation.
- isSupportedForSpeechGeneration()Checks if the prompt is supported for speech generation.
- isSupportedForMusicGeneration()Checks if the prompt is supported for music generation.
- isSupportedForEmbeddingGeneration()Checks if the prompt is supported for embedding generation.
- generateResult()Generates a result from the prompt.
- executeModelGeneration()Executes the model generation based on capability.
- generateTextResult()Generates a text result from the prompt.
- generateImageResult()Generates an image result from the prompt.
- generateSpeechResult()Generates a speech result from the prompt.
- convertTextToSpeechResult()Converts text to speech and returns the result.
- generateVideoResult()Generates a video result from the prompt.
- generateText()Generates text from the prompt.
- generateTexts()Generates multiple text candidates from the prompt.
- generateImage()Generates an image from the prompt.
- generateImages()Generates multiple images from the prompt.
- convertTextToSpeech()Converts text to speech.
- convertTextToSpeeches()Converts text to multiple speech outputs.
- generateSpeech()Generates speech from the prompt.
- generateSpeeches()Generates multiple speech outputs from the prompt.
- generateVideo()Generates a video from the prompt.
- generateVideos()Generates multiple videos from the prompt.
- appendPartToMessages()Appends a MessagePart to the messages array.
- getConfiguredModel()Gets the model to use for generation.
- bindModelRequestOptions()Binds configured request options to the model if present and supported.
- getCandidateModelsMap()Builds a map of candidate models that satisfy the requirements for efficient lookup.
- generateMapFromCandidates()Generates a candidate map from model metadata with both provider-specific and model-only keys.
- normalizePreferenceIdentifier()Normalizes and validates a preference identifier string.
- createProviderModelPreferenceKey()Creates a preference key for a provider/model combination.
- createModelPreferenceKey()Creates a preference key for a model identifier.
- parseMessage()Parses various input types into a Message with the given role.
- validateMessages()Validates the messages array for prompt generation.
- isMessagesList()Checks if the value is a list of Message objects.
- includeOutputModalities()Includes output modalities if not already present.
- dispatchEvent()Dispatches an event if an event dispatcher is registered.
Source code
class PromptBuilder{ /** * @var ProviderRegistry The provider registry for finding suitable models. */ private ProviderRegistry $registry; /** * @var list<Message> The messages in the conversation. */ protected array $messages = []; /** * @var ModelInterface|null The model to use for generation. */ protected ?ModelInterface $model = null; /** * @var list<string> Ordered list of preference keys to check when selecting a model. */ protected array $modelPreferenceKeys = []; /** * @var string|null The provider ID or class name. */ protected ?string $providerIdOrClassName = null; /** * @var ModelConfig The model configuration. */ protected ModelConfig $modelConfig; /** * @var RequestOptions|null The request options for HTTP transport. */ protected ?RequestOptions $requestOptions = null; /** * @var EventDispatcherInterface|null The event dispatcher for prompt lifecycle events. */ private ?EventDispatcherInterface $eventDispatcher = null; // phpcs:disable Generic.Files.LineLength.TooLong /** * Constructor. * * @since 0.1.0 * * @param ProviderRegistry $registry The provider registry for finding suitable models. * @param Prompt $prompt Optional initial prompt content. * @param EventDispatcherInterface|null $eventDispatcher Optional event dispatcher for lifecycle events. */ // phpcs:enable Generic.Files.LineLength.TooLong public function __construct(ProviderRegistry $registry, $prompt = null, ?EventDispatcherInterface $eventDispatcher = null) { $this->registry = $registry; $this->modelConfig = new ModelConfig(); $this->eventDispatcher = $eventDispatcher; if ($prompt === null) { return; } // Check if it's a list of Messages - set as messages if ($this->isMessagesList($prompt)) { $this->messages = $prompt; return; } // Parse it as a user message $userMessage = $this->parseMessage($prompt, MessageRoleEnum::user()); $this->messages[] = $userMessage; } /** * Creates a deep clone of this builder. * * Clones all mutable state including messages, model configuration, and request options. * Service objects (registry, model, event dispatcher) are intentionally NOT cloned * as they are shared dependencies. * * @since 0.4.2 */ public function __clone() { // Deep clone messages array (Message has __clone) $clonedMessages = []; foreach ($this->messages as $message) { $clonedMessages[] = clone $message; } $this->messages = $clonedMessages; // Clone model config (ModelConfig has __clone)Changelog
Introduced in 0.1.0. Unchanged from 7.0.4 through 7.1.0.
Signature, return type and hooks compared across 2 parsed releases.
About this page
- Parsed data
- Generated from the wordpress-develop 7.1.0 tag, from
src/wp-includes/php-ai-client/src/Builders/PromptBuilder.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it. - Corrections
- Something wrong on this page? Report it and it gets fixed in the next regeneration.