openai-php / client

⚡️ OpenAI PHP is a supercharged community-maintained PHP API client that allows you to interact with OpenAI API.
MIT License
4.82k stars 499 forks source link

[Bug]: Audio Speech for TTS with requestStream #276

Closed dposkachei closed 9 months ago

dposkachei commented 10 months ago

Description

Response for audio speech for TTS must be with requestStream format https://platform.openai.com/docs/guides/text-to-speech

This type of file editing allows you to correctly use new TTS functionality:

namespace OpenAI\Resources;

final class Audio implements AudioContract
{
...

    public function speech(array $parameters): ResponseInterface
    {
        $payload = Payload::create('audio/speech', $parameters);

        return $this->transporter->requestStream($payload);
    }

...
}
namespace OpenAI\Contracts;

interface TransporterContract
{
...

    public function requestStream(Payload $payload): ResponseInterface;

...
}

And then the file can be saved to the system:

$response = $this->client->audio()->speech([
    'model' => 'tts-1',
    'input' => 'Test for testing',
    'voice' => 'alloy',
]);
$filePath = '/tmp/example.mp3';

$file = fopen($filePath, 'w');
while (!$response->getBody()->eof()) {
    fwrite($file, $response->getBody()->read(1024));
}
fclose($file);

Steps To Reproduce

$response = $this->client->audio()->speech([
    'model' => 'tts-1',
    'input' => 'Test for testing',
    'voice' => 'alloy',
]);

$filePath = '/tmp/example.mp3';
file_put_contents($filePath, $binaryData); // the file contains only part of the phrase

OpenAI PHP Client Version

v0.7.10

PHP Version

8.2.10

Notes

Thank you for this package, you would have come to this small edit yourself, just a little help for the new update :)

gehrisandro commented 10 months ago

Hi @dposkachei

Thank you for your report.

I wasn't aware the response is chunked. But nevertheless, it should return the full response, as it waits for the complete response. Maybe you are using a different Http-Client than Guzzle?

Probably I will add a second method speechStreamed to get an iterator. But I think it is handy to have a method to fetch the complete response and not having to use an iterator. What do you think?

gehrisandro commented 10 months ago

Here is the streaming implementation: https://github.com/openai-php/client/pull/282