*/ class PromptMessage extends Content { /** * Create a new PromptMessage instance. * * @param Role $role The role of the message * @param TextContent|ImageContent|AudioContent|EmbeddedResource $content The content of the message */ public function __construct( public readonly Role $role, public readonly TextContent|ImageContent|AudioContent|EmbeddedResource $content, ) { parent::__construct('prompt'); } /** * @param PromptMessageData $data */ public static function fromArray(array $data): self { if (!isset($data['role']) || !\is_string($data['role'])) { throw new InvalidArgumentException('Missing or invalid "role" in PromptMessage data.'); } if (!isset($data['content']) || !\is_array($data['content'])) { throw new InvalidArgumentException('Missing or invalid "content" in PromptMessage data.'); } $contentData = $data['content']; $contentType = $contentData['type'] ?? null; if (!\is_string($contentType)) { throw new InvalidArgumentException('Missing or invalid content "type" for PromptMessage.'); } $content = match ($contentType) { 'text' => TextContent::fromArray($contentData), 'image' => ImageContent::fromArray($contentData), 'audio' => AudioContent::fromArray($contentData), 'resource' => EmbeddedResource::fromArray($contentData), default => throw new InvalidArgumentException(\sprintf('Invalid content type "%s" for PromptMessage.', $contentType)), }; if (null === $role = Role::tryFrom($data['role'])) { throw new InvalidArgumentException(\sprintf('Invalid "role" value "%s" in PromptMessage data.', $data['role'])); } return new self($role, $content); } /** * Convert the message to an array. * * @return array{ * role: string, * content: TextContent|ImageContent|AudioContent|EmbeddedResource * } */ public function jsonSerialize(): array { return [ 'role' => $this->role->value, 'content' => $this->content, ]; } }