-
-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathServiceProvider.php
More file actions
105 lines (89 loc) · 2.91 KB
/
ServiceProvider.php
File metadata and controls
105 lines (89 loc) · 2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
declare(strict_types=1);
namespace OpenAI\Laravel;
use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use OpenAI;
use OpenAI\Client;
use OpenAI\Contracts\ClientContract;
use OpenAI\Laravel\Commands\InstallCommand;
use OpenAI\Laravel\Exceptions\ApiKeyIsMissing;
use OpenAI\Webhooks\WebhookSignatureVerifier;
/**
* @internal
*/
final class ServiceProvider extends BaseServiceProvider implements DeferrableProvider
{
/**
* Register any application services.
*/
public function register(): void
{
$this->app->singleton(ClientContract::class, static function (): Client {
$apiKey = config('openai.api_key');
$organization = config('openai.organization');
$project = config('openai.project');
$baseUri = config('openai.base_uri');
if (! is_string($apiKey) || ($organization !== null && ! is_string($organization))) {
throw ApiKeyIsMissing::create();
}
$client = OpenAI::factory()
->withApiKey($apiKey)
->withOrganization($organization)
->withHttpClient(new \GuzzleHttp\Client(['timeout' => config('openai.request_timeout', 30)]));
if (is_string($project)) {
$client->withProject($project);
}
if (is_string($baseUri)) {
$client->withBaseUri($baseUri);
}
return $client->make();
});
$this->app->alias(ClientContract::class, 'openai');
$this->app->alias(ClientContract::class, Client::class);
$this->app
->when(WebhookSignatureVerifier::class)
->needs('$secret')
->give(fn () => config('openai.webhook.secret'));
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__.'/../config/openai.php' => config_path('openai.php'),
]);
$this->commands([
InstallCommand::class,
]);
}
$this->registerRoutes();
}
private function registerRoutes(): void
{
if (config('openai.webhook.enabled')) {
Route::group([
'namespace' => 'OpenAI\Laravel\Http\Controllers',
'domain' => config('openai.webhook.domain'),
'as' => 'openai.',
], fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php'));
}
}
/**
* Get the services provided by the provider.
*
* @return array<int, string>
*/
public function provides(): array
{
return [
WebhookSignatureVerifier::class,
Client::class,
ClientContract::class,
'openai',
];
}
}