WordPress\AiClient\Builders

PromptBuilder::parseMessage │ private │ WP 0.1.0

Parses various input types into a Message with the given role.

Method of the class: PromptBuilder{}

No Hooks.

Returns

Message. The parsed message.

Usage

// private - for code of main (parent) class only
$result = $this->parseMessage( $input, $defaultRole ): Message;
$input(mixed) (required)
The input to parse.
$defaultRole(MessageRoleEnum) (required)
The role for the message if not specified by input.

Changelog

Since 0.1.0 Introduced.

PromptBuilder::parseMessage() code WP 7.1.2

private function parseMessage($input, MessageRoleEnum $defaultRole): Message
{
    // Handle Message input directly
    if ($input instanceof Message) {
        return $input;
    }
    // Handle single MessagePart
    if ($input instanceof MessagePart) {
        return new Message($defaultRole, [$input]);
    }
    // Handle string input
    if (is_string($input)) {
        if (trim($input) === '') {
            throw new InvalidArgumentException('Cannot create a message from an empty string.');
        }
        return new Message($defaultRole, [new MessagePart($input)]);
    }
    // Handle array input
    if (!is_array($input)) {
        throw new InvalidArgumentException('Input must be a string, MessagePart, MessagePartArrayShape, ' . 'a list of string|MessagePart|MessagePartArrayShape, or a Message instance.');
    }
    // Handle MessageArrayShape input
    if (Message::isArrayShape($input)) {
        return Message::fromArray($input);
    }
    // Check if it's a MessagePartArrayShape
    if (MessagePart::isArrayShape($input)) {
        return new Message($defaultRole, [MessagePart::fromArray($input)]);
    }
    // It should be a list of string|MessagePart|MessagePartArrayShape
    if (!array_is_list($input)) {
        throw new InvalidArgumentException('Array input must be a list array.');
    }
    // Empty array check
    if (empty($input)) {
        throw new InvalidArgumentException('Cannot create a message from an empty array.');
    }
    $parts = [];
    foreach ($input as $item) {
        if (is_string($item)) {
            $parts[] = new MessagePart($item);
        } elseif ($item instanceof MessagePart) {
            $parts[] = $item;
        } elseif (is_array($item) && MessagePart::isArrayShape($item)) {
            $parts[] = MessagePart::fromArray($item);
        } else {
            throw new InvalidArgumentException('Array items must be strings, MessagePart instances, or MessagePartArrayShape.');
        }
    }
    return new Message($defaultRole, $parts);
}