openai-php / laravel

⚡️ OpenAI PHP for Laravel is a supercharged PHP API client that allows you to interact with OpenAI API
MIT License
2.58k stars 179 forks source link

Add OpenAI factory service #106

Open Radiergummi opened 3 months ago

Radiergummi commented 3 months ago

Summary: This PR adds support for adding a custom OpenAI factory implementation by binding OpenAI\Factory.

While the Factory class itself is final, binding it to a service still has the benefit of letting users customize client bootstrapping by decorating or downright replacing the factory call with their own.

As a concrete example: Right now, OpenAI added projects to their API that require setting a specific header. The OpenAI factory from the openai-php/client package provides a withProject() method; this change is yet unreleased, however.
In the mean time, there's not a lot users can do, other than to wait or override the client binding. That is despite the client factory actually providing a lot of convenience helpers to add custom parameters to the instance: The service provider just doesn't expose them.

This PR changes that and binds the Factory to the container. This way, applications can decorate the factory, like so:

$this->app->extend(OpenAI\Factory::class, fn(OpenAI\Factory $factory) => $factory
    ->withHttpHeader('OpenAI-Project', config('openai.project'))
);

...and be done with it for the time being. Of course, this also allows all other kinds of possibly required customization.

I would expect this to ease the maintenance burden on the contributors a bit, since OpenAI's changes to their API don't have to be reflected immediately without users complaining.

Should solve #105, until the new client version is released.