1111use function end ;
1212use function is_array ;
1313use function json_encode ;
14+ use function strtoupper ;
1415
1516trait HandleStructured
1617{
@@ -33,31 +34,57 @@ public function structured(
3334 $ last_message = end ($ messages );
3435 if ($ last_message instanceof Message && $ last_message ->getRole () === MessageRole::USER ->value ) {
3536 $ last_message ->setContents (
36- $ last_message ->getContent () . ' Respond using this JSON schema: ' . json_encode ($ response_format )
37+ $ last_message ->getContent () . ' Respond using this JSON schema: ' . json_encode ($ response_format )
3738 );
3839 }
3940 } else {
40- // If there are no tools, we can enforce the structured output.
41- $ this ->parameters ['generationConfig ' ]['response_schema ' ] = $ this ->adaptSchema ($ response_format );
42- $ this ->parameters ['generationConfig ' ]['response_mime_type ' ] = 'application/json ' ;
41+ $ this ->parameters ['generationConfig ' ]['responseSchema ' ] = $ this ->adaptSchema ($ response_format );
42+ $ this ->parameters ['generationConfig ' ]['responseMimeType ' ] = 'application/json ' ;
4343 }
4444
4545 return $ this ->chat ($ messages );
4646 }
4747
4848 /**
49- * Gemini does not support additionalProperties attribute .
49+ * Adapt Neuron schema to Gemini requirements .
5050 */
5151 protected function adaptSchema (array $ schema ): array
5252 {
5353 if (array_key_exists ('additionalProperties ' , $ schema )) {
5454 unset($ schema ['additionalProperties ' ]);
5555 }
5656
57- foreach ($ schema as $ key => $ value ) {
58- if (is_array ($ value )) {
59- $ schema [$ key ] = $ this ->adaptSchema ($ value );
57+ if (array_key_exists ('type ' , $ schema )) {
58+ if (is_array ($ schema ['type ' ])) {
59+ foreach ($ schema ['type ' ] as $ type ) {
60+ if ($ type !== 'null ' ) {
61+ $ schema ['type ' ] = strtoupper ((string ) $ type );
62+ break ;
63+ }
64+ }
65+ } else {
66+ $ schema ['type ' ] = strtoupper ((string ) $ schema ['type ' ]);
6067 }
68+
69+ $ schema ['type ' ] = match ($ schema ['type ' ]) {
70+ 'INT ' => 'INTEGER ' ,
71+ 'BOOL ' => 'BOOLEAN ' ,
72+ 'DOUBLE ' , 'FLOAT ' => 'NUMBER ' ,
73+ default => $ schema ['type ' ]
74+ };
75+ }
76+
77+ if (array_key_exists ('properties ' , $ schema ) && is_array ($ schema ['properties ' ])) {
78+ foreach ($ schema ['properties ' ] as $ key => $ value ) {
79+ if (is_array ($ value )) {
80+ $ schema ['properties ' ][$ key ] = $ this ->adaptSchema ($ value );
81+ }
82+ }
83+ $ schema ['properties ' ] = (object ) $ schema ['properties ' ];
84+ }
85+
86+ if (array_key_exists ('items ' , $ schema ) && is_array ($ schema ['items ' ])) {
87+ $ schema ['items ' ] = $ this ->adaptSchema ($ schema ['items ' ]);
6188 }
6289
6390 return $ schema ;
0 commit comments