I am looking for a way with a Form API form in Drupal to have an #ajax event on a form field. When submitted, this calls a remote API.
How can I stream the response out to the screen without the request being terminated before completing the stream read?
I thought maybe I could do this in the #ajax callback:
/**
* {@inheritdoc}
*/
public function getResponse(array &$form, FormStateInterface $form_state) {
$prompt = $form_state->getValue('prompt');
$model = $form_state->getValue('model');
$stream = $this->client->completions()->createStreamed(
[
'model' => $model,
'prompt' => trim($prompt),
],
);
foreach ($stream as $response) {
$value = $form['response']['#value'];
$value .= ' ' . trim($response->choices[0]->text) ?? $this->t('No answer was provided.');
$form['response']['#value'] = $value;
return $form['response'];
}
}
But this won't work. Is there a way to do this within Drupal currently?
foreach
loop? That will never work, because a function can only return once. It'll never get past the first iteration of the loop. I'm not even sure there's really a use case for this - the AJAX response will be JSON, and valid JSON needs the whole document to be parsed. The receiver would have to wait until all parts of the response were streamed before it could make sense of the output