[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/php-ai-client/src/Builders/ -> PromptBuilder.php (summary)

(no description)

File Size: 1466 lines (55 kb)
Included or required:0 times
Referenced: 0 times
Includes or requires: 0 files

Defines 1 class

PromptBuilder:: (72 methods):
  __construct()
  __clone()
  withText()
  withFile()
  withFunctionResponse()
  withMessageParts()
  withHistory()
  usingModel()
  usingModelPreference()
  usingModelConfig()
  usingProvider()
  usingSystemInstruction()
  usingMaxTokens()
  usingTemperature()
  usingTopP()
  usingTopK()
  usingStopSequences()
  usingCandidateCount()
  usingFunctionDeclarations()
  usingPresencePenalty()
  usingFrequencyPenalty()
  usingWebSearch()
  usingRequestOptions()
  usingTopLogprobs()
  asOutputMimeType()
  asOutputSchema()
  asOutputModalities()
  asOutputFileType()
  asOutputMediaOrientation()
  asOutputMediaAspectRatio()
  asOutputSpeechVoice()
  asJsonResponse()
  inferCapabilityFromOutputModalities()
  inferCapabilityFromModelInterfaces()
  isSupported()
  isSupportedForTextGeneration()
  isSupportedForImageGeneration()
  isSupportedForTextToSpeechConversion()
  isSupportedForVideoGeneration()
  isSupportedForSpeechGeneration()
  isSupportedForMusicGeneration()
  isSupportedForEmbeddingGeneration()
  generateResult()
  executeModelGeneration()
  generateTextResult()
  generateImageResult()
  generateSpeechResult()
  convertTextToSpeechResult()
  generateVideoResult()
  generateText()
  generateTexts()
  generateImage()
  generateImages()
  convertTextToSpeech()
  convertTextToSpeeches()
  generateSpeech()
  generateSpeeches()
  generateVideo()
  generateVideos()
  appendPartToMessages()
  getConfiguredModel()
  bindModelRequestOptions()
  getCandidateModelsMap()
  generateMapFromCandidates()
  normalizePreferenceIdentifier()
  createProviderModelPreferenceKey()
  createModelPreferenceKey()
  parseMessage()
  validateMessages()
  isMessagesList()
  includeOutputModalities()
  dispatchEvent()


Class: PromptBuilder  - X-Ref

Fluent builder for constructing AI prompts.

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.

__construct(ProviderRegistry $registry, $prompt = null, ?EventDispatcherInterface $eventDispatcher = null)   X-Ref
Constructor.

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.

__clone()   X-Ref
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.


withText(string $text)   X-Ref
Adds text to the current message.

return: self
param: string $text The text to add.

withFile($file, ?string $mimeType = null)   X-Ref
Adds a file to the current message.

Accepts:
- File object
- URL string (remote file)
- Base64-encoded data string
- Data URI string (data:mime/type;base64,data)
- Local file path string

return: self
param: string|File $file The file (File object or string representation).
param: string|null $mimeType The MIME type (optional, ignored if File object provided).

withFunctionResponse(FunctionResponse $functionResponse)   X-Ref
Adds a function response to the current message.

return: self
param: FunctionResponse $functionResponse The function response.

withMessageParts(MessagePart ...$parts)   X-Ref
Adds message parts to the current message.

return: self
param: MessagePart ...$parts The message parts to add.

withHistory(Message ...$messages)   X-Ref
Adds conversation history messages.

Historical messages are prepended to the beginning of the message list,
before the current message being built.

return: self
param: Message ...$messages The messages to add to history.

usingModel(ModelInterface $model)   X-Ref
Sets the model to use for generation.

The model's configuration will be merged with the builder's configuration,
with the builder's configuration taking precedence for any overlapping settings.

return: self
param: ModelInterface $model The model to use.

usingModelPreference(...$preferredModels)   X-Ref
Sets preferred models to evaluate in order.

return: self
param: string|ModelInterface|array{0:string,1:string} ...$preferredModels The preferred models as model IDs,

usingModelConfig(ModelConfig $config)   X-Ref
Sets the model configuration.

Merges the provided configuration with the builder's configuration,
with builder configuration taking precedence.

return: self
param: ModelConfig $config The model configuration to merge.

usingProvider(string $providerIdOrClassName)   X-Ref
Sets the provider to use for generation.

return: self
param: string $providerIdOrClassName The provider ID or class name.

usingSystemInstruction(string $systemInstruction)   X-Ref
Sets the system instruction.

System instructions are stored in the model configuration and guide
the AI model's behavior throughout the conversation.

return: self
param: string $systemInstruction The system instruction text.

usingMaxTokens(int $maxTokens)   X-Ref
Sets the maximum number of tokens to generate.

return: self
param: int $maxTokens The maximum number of tokens.

usingTemperature(float $temperature)   X-Ref
Sets the temperature for generation.

return: self
param: float $temperature The temperature value.

usingTopP(float $topP)   X-Ref
Sets the top-p value for generation.

return: self
param: float $topP The top-p value.

usingTopK(int $topK)   X-Ref
Sets the top-k value for generation.

return: self
param: int $topK The top-k value.

usingStopSequences(string ...$stopSequences)   X-Ref
Sets stop sequences for generation.

return: self
param: string ...$stopSequences The stop sequences.

usingCandidateCount(int $candidateCount)   X-Ref
Sets the number of candidates to generate.

return: self
param: int $candidateCount The number of candidates.

usingFunctionDeclarations(FunctionDeclaration ...$functionDeclarations)   X-Ref
Sets the function declarations available to the model.

return: self
param: FunctionDeclaration ...$functionDeclarations The function declarations.

usingPresencePenalty(float $presencePenalty)   X-Ref
Sets the presence penalty for generation.

return: self
param: float $presencePenalty The presence penalty value.

usingFrequencyPenalty(float $frequencyPenalty)   X-Ref
Sets the frequency penalty for generation.

return: self
param: float $frequencyPenalty The frequency penalty value.

usingWebSearch(WebSearch $webSearch)   X-Ref
Sets the web search configuration.

return: self
param: WebSearch $webSearch The web search configuration.

usingRequestOptions(RequestOptions $requestOptions)   X-Ref
Sets the request options for HTTP transport.

return: self
param: RequestOptions $requestOptions The request options.

usingTopLogprobs(?int $topLogprobs = null)   X-Ref
Sets the top log probabilities configuration.

If $topLogprobs is null, enables log probabilities.
If $topLogprobs has a value, enables log probabilities and sets the number of top log probabilities to return.

return: self
param: int|null $topLogprobs The number of top log probabilities to return, or null to enable log probabilities.

asOutputMimeType(string $mimeType)   X-Ref
Sets the output MIME type.

return: self
param: string $mimeType The MIME type.

asOutputSchema(array $schema)   X-Ref
Sets the output schema.

return: self
param: array<string, mixed> $schema The output schema.

asOutputModalities(ModalityEnum ...$modalities)   X-Ref
Sets the output modalities.

return: self
param: ModalityEnum ...$modalities The output modalities.

asOutputFileType(FileTypeEnum $fileType)   X-Ref
Sets the output file type.

return: self
param: FileTypeEnum $fileType The output file type.

asOutputMediaOrientation(MediaOrientationEnum $orientation)   X-Ref
Sets the output media orientation.

return: self
param: MediaOrientationEnum $orientation The output media orientation.

asOutputMediaAspectRatio(string $aspectRatio)   X-Ref
Sets the output media aspect ratio.

If set, this supersedes the output media orientation, as it is a more
specific configuration.

return: self
param: string $aspectRatio The aspect ratio (e.g. "16:9", "3:2").

asOutputSpeechVoice(string $voice)   X-Ref
Sets the output speech voice.

return: self
param: string $voice The output speech voice.

asJsonResponse(?array $schema = null)   X-Ref
Configures the prompt for JSON response output.

return: self
param: array<string, mixed>|null $schema Optional JSON schema.

inferCapabilityFromOutputModalities()   X-Ref
Infers the capability from configured output modalities.

return: CapabilityEnum The inferred capability.

inferCapabilityFromModelInterfaces(ModelInterface $model)   X-Ref
Infers the capability from a model's implemented interfaces.

return: CapabilityEnum|null The inferred capability, or null if none can be inferred.
param: ModelInterface $model The model to infer capability from.

isSupported(?CapabilityEnum $capability = null)   X-Ref
Checks if the current prompt is supported by the selected model.

return: bool True if supported, false otherwise.
param: CapabilityEnum|null $capability Optional capability to check support for.

isSupportedForTextGeneration()   X-Ref
Checks if the prompt is supported for text generation.

return: bool True if text generation is supported.

isSupportedForImageGeneration()   X-Ref
Checks if the prompt is supported for image generation.

return: bool True if image generation is supported.

isSupportedForTextToSpeechConversion()   X-Ref
Checks if the prompt is supported for text to speech conversion.

return: bool True if text to speech conversion is supported.

isSupportedForVideoGeneration()   X-Ref
Checks if the prompt is supported for video generation.

return: bool True if video generation is supported.

isSupportedForSpeechGeneration()   X-Ref
Checks if the prompt is supported for speech generation.

return: bool True if speech generation is supported.

isSupportedForMusicGeneration()   X-Ref
Checks if the prompt is supported for music generation.

return: bool True if music generation is supported.

isSupportedForEmbeddingGeneration()   X-Ref
Checks if the prompt is supported for embedding generation.

return: bool True if embedding generation is supported.

generateResult(?CapabilityEnum $capability = null)   X-Ref
Generates a result from the prompt.

This is the primary execution method that generates a result (containing
potentially multiple candidates) based on the specified capability or
the configured output modality.

return: GenerativeAiResult The generated result containing candidates.
param: CapabilityEnum|null $capability Optional capability to use for generation.

executeModelGeneration(ModelInterface $model, CapabilityEnum $capability, array $messages)   X-Ref
Executes the model generation based on capability.

return: GenerativeAiResult The generated result.
param: ModelInterface $model The model to use for generation.
param: CapabilityEnum $capability The capability to use.
param: list<Message> $messages The messages to send.

generateTextResult()   X-Ref
Generates a text result from the prompt.

return: GenerativeAiResult The generated result containing text candidates.

generateImageResult()   X-Ref
Generates an image result from the prompt.

return: GenerativeAiResult The generated result containing image candidates.

generateSpeechResult()   X-Ref
Generates a speech result from the prompt.

return: GenerativeAiResult The generated result containing speech audio candidates.

convertTextToSpeechResult()   X-Ref
Converts text to speech and returns the result.

return: GenerativeAiResult The generated result containing speech audio candidates.

generateVideoResult()   X-Ref
Generates a video result from the prompt.

return: GenerativeAiResult The generated result containing video candidates.

generateText()   X-Ref
Generates text from the prompt.

return: string The generated text.

generateTexts(?int $candidateCount = null)   X-Ref
Generates multiple text candidates from the prompt.

return: list<string> The generated texts.
param: int|null $candidateCount The number of candidates to generate.

generateImage()   X-Ref
Generates an image from the prompt.

return: File The generated image file.

generateImages(?int $candidateCount = null)   X-Ref
Generates multiple images from the prompt.

return: list<File> The generated image files.
param: int|null $candidateCount The number of images to generate.

convertTextToSpeech()   X-Ref
Converts text to speech.

return: File The generated speech audio file.

convertTextToSpeeches(?int $candidateCount = null)   X-Ref
Converts text to multiple speech outputs.

return: list<File> The generated speech audio files.
param: int|null $candidateCount The number of speech outputs to generate.

generateSpeech()   X-Ref
Generates speech from the prompt.

return: File The generated speech audio file.

generateSpeeches(?int $candidateCount = null)   X-Ref
Generates multiple speech outputs from the prompt.

return: list<File> The generated speech audio files.
param: int|null $candidateCount The number of speech outputs to generate.

generateVideo()   X-Ref
Generates a video from the prompt.

return: File The generated video file.

generateVideos(?int $candidateCount = null)   X-Ref
Generates multiple videos from the prompt.

return: list<File> The generated video files.
param: int|null $candidateCount The number of videos to generate.

appendPartToMessages(MessagePart $part)   X-Ref
Appends a MessagePart to the messages array.

If the last message has a user role, the part is added to it.
Otherwise, a new UserMessage is created with the part.

return: void
param: MessagePart $part The part to append.

getConfiguredModel(CapabilityEnum $capability)   X-Ref
Gets the model to use for generation.

If a model has been explicitly set, validates it meets requirements and returns it.
Otherwise, finds a suitable model based on the prompt requirements.

return: ModelInterface The model to use.
param: CapabilityEnum $capability The capability the model will be using.

bindModelRequestOptions(ModelInterface $model)   X-Ref
Binds configured request options to the model if present and supported.

Request options are only applicable to API-based models that make HTTP requests.

return: void
param: ModelInterface $model The model to bind request options to.

getCandidateModelsMap(ModelRequirements $requirements)   X-Ref
Builds a map of candidate models that satisfy the requirements for efficient lookup.

return: array<string, array{0:string,1:string}> Map of preference keys to [providerId, modelId] tuples.
param: ModelRequirements $requirements The requirements derived from the prompt.

generateMapFromCandidates(string $providerId, array $modelsMetadata)   X-Ref
Generates a candidate map from model metadata with both provider-specific and model-only keys.

return: array<string, array{0:string,1:string}> Map of preference keys to [providerId, modelId] tuples.
param: string $providerId The provider ID.
param: list<ModelMetadata> $modelsMetadata The models metadata to map.

normalizePreferenceIdentifier($value, string $emptyMessage = 'Model preference identifiers cannot be empty.')   X-Ref
Normalizes and validates a preference identifier string.

return: string The normalized identifier.
param: mixed $value The value to normalize.
param: string $emptyMessage The message for empty or invalid values.

createProviderModelPreferenceKey(string $providerId, string $modelId)   X-Ref
Creates a preference key for a provider/model combination.

return: string The generated preference key.
param: string $providerId The provider identifier.
param: string $modelId The model identifier.

createModelPreferenceKey(string $modelId)   X-Ref
Creates a preference key for a model identifier.

return: string The generated preference key.
param: string $modelId The model identifier.

parseMessage($input, MessageRoleEnum $defaultRole)   X-Ref
Parses various input types into a Message with the given role.

return: Message The parsed message.
param: mixed $input The input to parse.
param: MessageRoleEnum $defaultRole The role for the message if not specified by input.

validateMessages()   X-Ref
Validates the messages array for prompt generation.

Ensures that:
- The first message is a user message
- The last message is a user message
- The last message has parts

return: void

isMessagesList($value)   X-Ref
Checks if the value is a list of Message objects.

return: bool True if the value is a list of Message objects.
param: mixed $value The value to check.

includeOutputModalities(ModalityEnum ...$modalities)   X-Ref
Includes output modalities if not already present.

Adds the given modalities to the output modalities list if they're not
already included. If output modalities is null, initializes it with
the given modalities.

return: void
param: ModalityEnum ...$modalities The modalities to include.

dispatchEvent(object $event)   X-Ref
Dispatches an event if an event dispatcher is registered.

return: void
param: object $event The event to dispatch.



Generated : Sat Jun 13 09:38:55 2026 Cross-referenced by PHPXref