@@ -95,6 +95,7 @@ public function doConvertEmbeddings(array $data): ResultInterface
9595
9696 private function convertStream (ResponseInterface $ result ): \Generator
9797 {
98+ $ toolCalls = [];
9899 foreach ((new EventSourceHttpClient ())->stream ($ result ) as $ chunk ) {
99100 if ($ chunk instanceof FirstChunk || $ chunk instanceof LastChunk) {
100101 continue ;
@@ -106,6 +107,14 @@ private function convertStream(ResponseInterface $result): \Generator
106107 throw new RuntimeException ('Failed to decode JSON: ' .$ e ->getMessage ());
107108 }
108109
110+ if ($ this ->streamIsToolCall ($ data )) {
111+ $ toolCalls = $ this ->convertStreamToToolCalls ($ toolCalls , $ data );
112+ }
113+
114+ if ([] !== $ toolCalls && $ this ->isToolCallsStreamFinished ($ data )) {
115+ yield new ToolCallResult (...$ toolCalls );
116+ }
117+
109118 yield new OllamaMessageChunk (
110119 $ data ['model ' ],
111120 new \DateTimeImmutable ($ data ['created_at ' ]),
@@ -114,4 +123,39 @@ private function convertStream(ResponseInterface $result): \Generator
114123 );
115124 }
116125 }
126+
127+ /**
128+ * @param array<string, mixed> $toolCalls
129+ * @param array<string, mixed> $data
130+ *
131+ * @return array<ToolCall>
132+ */
133+ private function convertStreamToToolCalls (array $ toolCalls , array $ data ): array
134+ {
135+ if (!isset ($ data ['message ' ]['tool_calls ' ])) {
136+ return $ toolCalls ;
137+ }
138+
139+ foreach ($ data ['message ' ]['tool_calls ' ] ?? [] as $ id => $ toolCall ) {
140+ $ toolCalls [] = new ToolCall ($ id , $ toolCall ['function ' ]['name ' ], $ toolCall ['function ' ]['arguments ' ]);
141+ }
142+
143+ return $ toolCalls ;
144+ }
145+
146+ /**
147+ * @param array<string, mixed> $data
148+ */
149+ private function streamIsToolCall (array $ data ): bool
150+ {
151+ return isset ($ data ['message ' ]['tool_calls ' ]);
152+ }
153+
154+ /**
155+ * @param array<string, mixed> $data^
156+ */
157+ private function isToolCallsStreamFinished (array $ data ): bool
158+ {
159+ return isset ($ data ['done ' ]) && true === $ data ['done ' ];
160+ }
117161}
0 commit comments