openai-php / client

āš”ļø OpenAI PHP is a supercharged community-maintained PHP API client that allows you to interact with OpenAI API.
MIT License
4.86k stars 502 forks source link

fully typed responses and requests #4

Closed gehrisandro closed 2 years ago

gehrisandro commented 2 years ago

Hi @nunomaduro

First of all, thank you for reviewing and merging my previous PRs so quickly! šŸ‘ It's a pleasure to help you with this package. Learned already a lot about (Open)AI and even more from your way how to build a clean package.

I am a huge fan of using fully typed responses and requests. Therefore I gave it a try with the moderations endpoint to see how it could work.

What I ended up with is the following:

$client = OpenAI::client('TOKEN');

$request = new ModerationCreateRequest(input: 'I want to kill them.', model: ModerationModel::TextModerationLatest);

$response = $client->moderations()->create($request);

dump($response->id); // modr-5vvCuUd3dRjgIumIZIu0yBepv5qwL
dump($response->model); // text-moderation-003
dump($response->results[0]->flagged); // true
dump($response->results[0]->categories[0]->toArray()); // ["category" => "hate", "violated" => true, "score" => 0.40681719779968 ]

In my opinion this gives the developers the better UX than plain arrays.

More or less I took the approach Steve McDougall described here: https://laravel-news.com/working-with-data-in-api-integrations

I also implemented request factories to give the user various options how to create the request instance:

// create the request directly
$request = new ModerationCreateRequest(
    input: 'I want to kill them.',
    model: ModerationModel::TextModerationLatest,
);

// pass an array to a factory instance
$request = (new ModerationCreateRequestFactory)->make([
    'input' => 'I want to kill them.',
    'model' => ModerationModel::TextModerationLatest,
]);

// pass an array to a static factory method
$request = ModerationCreateRequestFactory::new([
    'input' => 'I want to kill them.',
    'model' => ModerationModel::TextModerationLatest,
]);

If you want to have a look, I pushed the POC here: https://github.com/gehrisandro/openai-php-client/tree/poc-strong-typed-requests-and-responses

nunomaduro commented 2 years ago

I am in favour of typing responses. Can you make a regular pull request and we work from there?