Skip to content

[0.x] Adds typed responses for all remaining resources #6

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

Merged
merged 1 commit into from
Oct 4, 2022
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: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,30 @@ $client->models()->delete($model); // ['id' => 'curie:ft-acmeco-2021-03-03-21-44
Creates a completion for the provided prompt and parameters.

```php
$client->completions()->create($parameters); // ['choices' => [...], ...]
$response = $client->completions()->create([
'model' => 'text-davinci-002',
'prompt' => 'Say this is a test',
'max_tokens' => 6,
'temperature' => 0
]);

$response->id; // 'cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7'
$response->object; // 'text_completion'
$response->created; // 1589478378
$response->model; // 'text-davinci-002'

foreach ($response->choices as $result) {
$result->text; // '\n\nThis is a test'
$result->index; // 0
$result->logprobs; // null
$result->finishReason; // 'length'
}

$response->usage->promptTokens; // 5,
$response->usage->completionTokens; // 6,
$response->usage->totalTokens; // 11

$response->toArray(); // ['id' => 'cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7', ...]
```

### `Edits` Resource
Expand Down
8 changes: 4 additions & 4 deletions src/Resources/Completions.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace OpenAI\Resources;

use OpenAI\Responses\Completions\CreateResponse;
use OpenAI\ValueObjects\Transporter\Payload;

final class Completions
Expand All @@ -16,15 +17,14 @@ final class Completions
* @see https://beta.openai.com/docs/api-reference/completions/create-completion
*
* @param array<string, mixed> $parameters
* @return array<string, array<string, mixed>|string>
*/
public function create(array $parameters): array
public function create(array $parameters): CreateResponse
{
$payload = Payload::create('completions', $parameters);

/** @var array<string, array<string, mixed>|string> $result */
/** @var array{id: string, object: string, created: int, model: string, choices: array<int, array{text: string, index: int, logprobs: int|null, finish_reason: string}>, usage: array{prompt_tokens: int, completion_tokens: int, total_tokens: int}} $result */
$result = $this->transporter->requestObject($payload);

return $result;
return CreateResponse::from($result);
}
}
62 changes: 62 additions & 0 deletions src/Responses/Completions/CreateResponse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

declare(strict_types=1);

namespace OpenAI\Responses\Completions;

use OpenAI\Contracts\Response;

final class CreateResponse implements Response
{
/**
* @param array<int, CreateResponseChoice> $choices
*/
private function __construct(
public readonly string $id,
public readonly string $object,
public readonly int $created,
public readonly string $model,
public readonly array $choices,
public readonly CreateResponseUsage $usage,
) {
}

/**
* Acts as static factory, and returns a new Response instance.
*
* @param array{id: string, object: string, created: int, model: string, choices: array<int, array{text: string, index: int, logprobs: int|null, finish_reason: string}>, usage: array{prompt_tokens: int, completion_tokens: int, total_tokens: int}} $attributes
*/
public static function from(array $attributes): self
{
$choices = array_map(fn (array $result): CreateResponseChoice => CreateResponseChoice::from(
$result
), $attributes['choices']);

return new self(
$attributes['id'],
$attributes['object'],
$attributes['created'],
$attributes['model'],
$choices,
CreateResponseUsage::from($attributes['usage'])
);
}

/**
* @return array{id: string, object: string, created: int, model: string, choices: array<int, array{text: string, index: int, logprobs: int|null, finish_reason: string}>, usage: array{prompt_tokens: int, completion_tokens: int, total_tokens: int}}
*/
public function toArray(): array
{
return [
'id' => $this->id,
'object' => $this->object,
'created' => $this->created,
'model' => $this->model,
'choices' => array_map(
static fn (CreateResponseChoice $result): array => $result->toArray(),
$this->choices,
),
'usage' => $this->usage->toArray(),
];
}
}
42 changes: 42 additions & 0 deletions src/Responses/Completions/CreateResponseChoice.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

declare(strict_types=1);

namespace OpenAI\Responses\Completions;

final class CreateResponseChoice
{
private function __construct(
public readonly string $text,
public readonly int $index,
public readonly ?int $logprobs,
public readonly string $finishReason,
) {
}

/**
* @param array{text: string, index: int, logprobs: int|null, finish_reason: string} $attributes
*/
public static function from(array $attributes): self
{
return new self(
$attributes['text'],
$attributes['index'],
$attributes['logprobs'],
$attributes['finish_reason'],
);
}

/**
* @return array{text: string, index: int, logprobs: int|null, finish_reason: string}
*/
public function toArray(): array
{
return [
'text' => $this->text,
'index' => $this->index,
'logprobs' => $this->logprobs,
'finish_reason' => $this->finishReason,
];
}
}
39 changes: 39 additions & 0 deletions src/Responses/Completions/CreateResponseUsage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

namespace OpenAI\Responses\Completions;

final class CreateResponseUsage
{
private function __construct(
public readonly int $promptTokens,
public readonly int $completionTokens,
public readonly int $totalTokens,
) {
}

/**
* @param array{prompt_tokens: int, completion_tokens: int, total_tokens: int} $attributes
*/
public static function from(array $attributes): self
{
return new self(
$attributes['prompt_tokens'],
$attributes['completion_tokens'],
$attributes['total_tokens'],
);
}

/**
* @return array{prompt_tokens: int, completion_tokens: int, total_tokens: int}
*/
public function toArray(): array
{
return [
'prompt_tokens' => $this->promptTokens,
'completion_tokens' => $this->completionTokens,
'total_tokens' => $this->totalTokens,
];
}
}
25 changes: 24 additions & 1 deletion tests/Resources/Completions.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
<?php

use OpenAI\Responses\Completions\CreateResponse;
use OpenAI\Responses\Completions\CreateResponseChoice;
use OpenAI\Responses\Completions\CreateResponseUsage;

test('create', function () {
$client = mockClient('POST', 'completions', [
'model' => 'da-vince',
Expand All @@ -11,5 +15,24 @@
'prompt' => 'hi',
]);

expect($result)->toBeArray()->toBe(completion());
expect($result)
->toBeInstanceOf(CreateResponse::class)
->id->toBe('cmpl-5uS6a68SwurhqAqLBpZtibIITICna')
->object->toBe('text_completion')
->created->toBe(1664136088)
->model->toBe('davinci')
->choices->toBeArray()->toHaveCount(1)
->choices->each->toBeInstanceOf(CreateResponseChoice::class)
->usage->toBeInstanceOf(CreateResponseUsage::class);

expect($result->choices[0])
->text->toBe("el, she elaborates more on the Corruptor's role, suggesting K")
->index->toBe(0)
->logprobs->toBe(null)
->finishReason->toBe('length');

expect($result->usage)
->promptTokens->toBe(1)
->completionTokens->toBe(16)
->totalTokens->toBe(17);
});
27 changes: 27 additions & 0 deletions tests/Responses/Completions/CreateResponse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

use OpenAI\Responses\Completions\CreateResponse;
use OpenAI\Responses\Completions\CreateResponseChoice;
use OpenAI\Responses\Completions\CreateResponseUsage;

test('from', function () {
$completion = CreateResponse::from(completion());

expect($completion)
->toBeInstanceOf(CreateResponse::class)
->id->toBe('cmpl-5uS6a68SwurhqAqLBpZtibIITICna')
->object->toBe('text_completion')
->created->toBe(1664136088)
->model->toBe('davinci')
->choices->toBeArray()->toHaveCount(1)
->choices->each->toBeInstanceOf(CreateResponseChoice::class)
->usage->toBeInstanceOf(CreateResponseUsage::class);
});

test('to array', function () {
$completion = CreateResponse::from(completion());

expect($completion->toArray())
->toBeArray()
->toBe(completion());
});
20 changes: 20 additions & 0 deletions tests/Responses/Completions/CreateResponseChoice.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

use OpenAI\Responses\Completions\CreateResponseChoice;

test('from', function () {
$result = CreateResponseChoice::from(completion()['choices'][0]);

expect($result)
->text->toBe("el, she elaborates more on the Corruptor's role, suggesting K")
->index->toBe(0)
->logprobs->toBe(null)
->finishReason->toBe('length');
});

test('to array', function () {
$result = CreateResponseChoice::from(completion()['choices'][0]);

expect($result->toArray())
->toBe(completion()['choices'][0]);
});
19 changes: 19 additions & 0 deletions tests/Responses/Completions/CreateResponseUsage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

use OpenAI\Responses\Completions\CreateResponseUsage;

test('from', function () {
$result = CreateResponseUsage::from(completion()['usage']);

expect($result)
->promptTokens->toBe(1)
->completionTokens->toBe(16)
->totalTokens->toBe(17);
});

test('to array', function () {
$result = CreateResponseUsage::from(completion()['usage']);

expect($result->toArray())
->toBe(completion()['usage']);
});