@@ -18,6 +18,7 @@ public function messages(): array
1818 {
1919 return $ this ->messages ;
2020 }
21+
2122 public function addUserTextMessage (string $ text ): self
2223 {
2324 return $ this ->addMessage (self ::ROLE_USER , $ text );
@@ -41,7 +42,7 @@ public function addUserImageMessage(string $url, ?string $text = null): self
4142 'media_type ' => $ mediaType
4243 ],
4344 ];
44- $ message = [ $ imageMessage ];
45+ $ message = [$ imageMessage ];
4546
4647 if ($ text ) {
4748 $ textMessage = [
@@ -81,16 +82,31 @@ public function addMessage(string $role, string|array $content): self
8182 if ($ block ['type ' ] == 'text ' && !array_key_exists ('text ' , $ block )) {
8283 throw new \InvalidArgumentException ('Block text property is required for text type. Index: ' . $ i );
8384 }
84- if ($ block ['type ' ] == 'image ' && (!array_key_exists ('media_type ' , $ block ) || !array_key_exists ('data ' , $ block ))) {
85- throw new \InvalidArgumentException ('Block media type and data property are required for image type. Index: ' . $ i );
85+ if ($ block ['type ' ] == 'image ' && (!array_key_exists ('media_type ' , $ block ) || !array_key_exists (
86+ 'data ' ,
87+ $ block
88+ ))) {
89+ throw new \InvalidArgumentException (
90+ 'Block media type and data property are required for image type. Index: ' . $ i
91+ );
8692 }
8793 }
94+ } else {
95+ // let's standardize the way the blocks are passed
96+ $ content = [
97+ [
98+ 'type ' => 'text ' ,
99+ 'text ' => $ content
100+ ]
101+ ];
88102 }
89103
90104 if (count ($ this ->messages ) > 0 ) {
91105 $ lastMessage = $ this ->messages [count ($ this ->messages ) - 1 ];
92106 if ($ lastMessage ['role ' ] === $ role ) {
93- throw new \InvalidArgumentException ('Roles must alternate between "user" and "assistant". Message ' . count ($ this ->messages ) . ' has the same role as the previous message. ' );
107+ // merge messages of the same role
108+ $ this ->messages [count ($ this ->messages ) - 1 ]['content ' ] = array_merge ($ lastMessage ['content ' ], $ content );
109+ return $ this ;
94110 }
95111 }
96112
0 commit comments