Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support uploading files #9

Merged
merged 4 commits into from
Oct 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ Embeddings
To create an embedding for a given text, use https://platform.openai.com/docs/guides/embeddings/what-are-embeddings

```php
use util\cmd\Console;
use com\openai\rest\OpenAIEndpoint;
use util\cmd\Console;

$ai= new OpenAIEndpoint('https://'.getenv('OPENAI_API_KEY').'@api.openai.com/v1');

Expand All @@ -85,8 +85,8 @@ Text to speech
To stream generate audio, use the API's *transmit()* method, which sends the given payload and returns the response. See https://platform.openai.com/docs/guides/text-to-speech/overview

```php
use util\cmd\Console;
use com\openai\rest\OpenAIEndpoint;
use util\cmd\Console;

$ai= new OpenAIEndpoint('https://'.getenv('OPENAI_API_KEY').'@api.openai.com/v1');
$payload= [
Expand All @@ -101,6 +101,27 @@ while ($stream->available()) {
}
```

Speech to text
--------------
To convert audio into text, upload files via the API's *upload()* method, which returns an upload instance. See https://platform.openai.com/docs/guides/speech-to-text/overview

```php
use com\openai\rest\OpenAIEndpoint;
use io\File;
use util\cmd\Console;
use util\MimeType;

$ai= new OpenAIEndpoint('https://'.getenv('OPENAI_API_KEY').'@api.openai.com/v1');
$file= new File($argv[1]);

$response= $ai->api('/audio/transcriptions')
->open(['model', 'whisper-1'])
->transfer('file', $file->in(), $file->filename, MimeType::getByFileName($file->filename))
->finish()
;
Console::writeLine($response->value());
```

Tracing the calls
-----------------
REST API calls can be traced with the [logging library](https://github.com/xp-framework/logging):
Expand Down
23 changes: 16 additions & 7 deletions src/main/php/com/openai/rest/Api.class.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php namespace com\openai\rest;

use webservices\rest\{RestResource, RestResponse, UnexpectedStatus};
use webservices\rest\{RestResource, RestResponse, RestUpload, UnexpectedStatus};

class Api {
const JSON= 'application/json';
Expand All @@ -24,17 +24,26 @@ public function __construct(RestResource $resource, RateLimit $rateLimit) {
*/
public function transmit($payload, $mime= self::JSON): RestResponse {
$r= $this->resource->post($payload, $mime);

// Update rate limit if header is present
if (null !== ($remaining= $r->header('x-ratelimit-remaining-requests'))) {
$this->rateLimit->remaining= (int)$remaining;
}

$this->rateLimit->update($r->header('x-ratelimit-remaining-requests'));
if (200 === $r->status()) return $r;

throw new UnexpectedStatus($r);
}

/**
* Starts an upload
*
* @param [:string] $params
* @return com.openai.rest.Upload
*/
public function open($params= []): Upload {
$upload= $this->resource->upload('POST');
foreach ($params as $name => $value) {
$upload->pass($name, $value);
}
return new Upload($upload, $this->rateLimit);
}

/** Invokes API and returns result */
public function invoke(array $payload) {
$this->resource->accepting(self::JSON);
Expand Down
5 changes: 5 additions & 0 deletions src/main/php/com/openai/rest/RateLimit.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
class RateLimit implements Value {
public $remaining= null;

/** Update rate limit if header is present */
public function update(?int $remaining): void {
null === $remaining || $this->remaining= $remaining;
}

/** @return string */
public function toString() {
return nameof($this).'(remaining: '.(null === $this->remaining ? '(n/a)' : $this->remaining).')';
Expand Down
54 changes: 54 additions & 0 deletions src/main/php/com/openai/rest/Upload.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php namespace com\openai\rest;

use io\streams\{InputStream, OutputStream};
use webservices\rest\{RestResponse, RestUpload, UnexpectedStatus};

class Upload {
private $upload, $rateLimit;

/** Creates a new API instance from a given REST resource */
public function __construct(RestUpload $upload, RateLimit $rateLimit) {
$this->upload= $upload;
$this->rateLimit= $rateLimit;
}

/**
* Transfer a given stream
*
* @param string $name
* @param io.streams.InputStream $in
* @param string $filename
* @param ?string $mime Uses `util.MimeType` if omitted
* @return self
*/
public function transfer($name, InputStream $in, $filename, $mime= null): self {
$this->upload->transfer($name, $in, $filename, $mime);
return $this;
}

/**
* Return a stream for writing
*
* @param string $name
* @param string $filename
* @param ?string $mime Uses `util.MimeType` if omitted
* @return io.streams.OutputStream
*/
public function stream($name, $filename, $mime= null): OutputStream {
return $this->upload->stream($name, $filename, $mime);
}

/**
* Finish uploading and return response
*
* @return webservices.rest.RestResponse
* @throws webservices.rest.UnexpectedStatus
*/
public function finish(): RestResponse {
$r= $this->upload->finish();
$this->rateLimit->update($r->header('x-ratelimit-remaining-requests'));
if (200 === $r->status()) return $r;

throw new UnexpectedStatus($r);
}
}
16 changes: 15 additions & 1 deletion src/test/php/com/openai/unittest/ApiEndpointTest.class.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php namespace com\openai\unittest;

use io\streams\Streams;
use io\streams\{Streams, MemoryInputStream};
use test\{Assert, Expect, Test};
use webservices\rest\{TestEndpoint, UnexpectedStatus};

Expand All @@ -12,6 +12,9 @@ protected abstract function fixture(... $args);
/** Returns a testing API endpoint */
private function testingEndpoint(): TestEndpoint {
return new TestEndpoint([
'POST /audio/transcriptions' => function($call) {
return $call->respond(200, 'OK', ['Content-Type' => 'application/json'], '"Test"');
},
'POST /chat/completions' => function($call) {
if ($call->request()->payload()->value()['stream'] ?? false) {
$headers= ['Content-Type' => 'text/event-stream'];
Expand Down Expand Up @@ -57,6 +60,17 @@ public function transmit() {
);
}

#[Test]
public function upload() {
$endpoint= $this->fixture($this->testingEndpoint());
Assert::equals('Test', $endpoint->api('/audio/transcriptions')
->open(['model' => 'whisper-1'])
->transfer('file', new MemoryInputStream("\xf3\xff..."), 'test.mp3', 'audio/mp3')
->finish()
->value()
);
}

#[Test, Expect(UnexpectedStatus::class)]
public function invoke_non_existant_api() {
$endpoint= $this->fixture($this->testingEndpoint());
Expand Down
Loading