[ 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.

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

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

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

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

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

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

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

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.

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

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.

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

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

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

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

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

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

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

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

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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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

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

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

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

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

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

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

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

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

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

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

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.

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

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

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

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

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

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.

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

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

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

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.

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

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

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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

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.

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

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

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



Generated : Fri Jul 24 08:20:19 2026 Cross-referenced by PHPXref