2525use Symfony \AI \Platform \Result \ToolCall ;
2626use Symfony \AI \Platform \Result \ToolCallResult ;
2727use Symfony \AI \Platform \ResultConverterInterface ;
28- use Symfony \Component \HttpClient \EventSourceHttpClient ;
29- use Symfony \Contracts \HttpClient \ResponseInterface as HttpResponse ;
3028
3129/**
3230 * @author Roy Garrido
@@ -51,7 +49,7 @@ public function convert(RawResultInterface|RawHttpResult $result, array $options
5149 }
5250
5351 if ($ options ['stream ' ] ?? false ) {
54- return new StreamResult ($ this ->convertStream ($ response ));
52+ return new StreamResult ($ this ->convertStream ($ result ));
5553 }
5654
5755 $ data = $ result ->getData ();
@@ -69,50 +67,21 @@ public function convert(RawResultInterface|RawHttpResult $result, array $options
6967 return 1 === \count ($ choices ) ? $ choices [0 ] : new ChoiceResult (...$ choices );
7068 }
7169
72- private function convertStream (HttpResponse $ result ): \Generator
70+ private function convertStream (RawResultInterface $ result ): \Generator
7371 {
74- foreach ((new EventSourceHttpClient ())->stream ($ result ) as $ chunk ) {
75- if ($ chunk ->isFirst () || $ chunk ->isLast ()) {
72+ foreach ($ result ->getDataStream () as $ data ) {
73+ $ choices = array_map ($ this ->convertChoice (...), $ data ['candidates ' ] ?? []);
74+
75+ if (!$ choices ) {
7676 continue ;
7777 }
7878
79- $ jsonDelta = trim ($ chunk ->getContent ());
80-
81- // Remove leading/trailing brackets
82- if (str_starts_with ($ jsonDelta , '[ ' ) || str_starts_with ($ jsonDelta , ', ' )) {
83- $ jsonDelta = substr ($ jsonDelta , 1 );
84- }
85- if (str_ends_with ($ jsonDelta , '] ' )) {
86- $ jsonDelta = substr ($ jsonDelta , 0 , -1 );
79+ if (1 !== \count ($ choices )) {
80+ yield new ChoiceResult (...$ choices );
81+ continue ;
8782 }
8883
89- // Split in case of multiple JSON objects
90- $ deltas = explode (", \r\n" , $ jsonDelta );
91-
92- foreach ($ deltas as $ delta ) {
93- if ('' === $ delta ) {
94- continue ;
95- }
96-
97- try {
98- $ data = json_decode ($ delta , true , 512 , \JSON_THROW_ON_ERROR );
99- } catch (\JsonException $ e ) {
100- throw new RuntimeException ('Failed to decode JSON response. ' , previous: $ e );
101- }
102-
103- $ choices = array_map ($ this ->convertChoice (...), $ data ['candidates ' ] ?? []);
104-
105- if (!$ choices ) {
106- continue ;
107- }
108-
109- if (1 !== \count ($ choices )) {
110- yield new ChoiceResult (...$ choices );
111- continue ;
112- }
113-
114- yield $ choices [0 ]->getContent ();
115- }
84+ yield $ choices [0 ]->getContent ();
11685 }
11786 }
11887
0 commit comments