44
55/**
66 * Real OpenAI Client Implementation
7- *
7+ *
88 * Concrete implementation of OpenAIClient interface for making
99 * actual calls to OpenAI API.
1010 */
1111class RealOpenAIClient implements OpenAIClient
1212{
1313 private string $ apiKey ;
1414 private string $ baseUrl = 'https://api.openai.com/v1 ' ;
15-
15+
1616 public function __construct (string $ apiKey = '' )
1717 {
1818 $ this ->apiKey = $ apiKey ?: getenv ('OPENAI_API_KEY ' ) ?: '' ;
1919 }
20-
20+
2121 public function chat (array $ context ): array
2222 {
2323 if (empty ($ this ->apiKey )) {
2424 throw new \InvalidArgumentException ('OpenAI API key is required ' );
2525 }
26-
26+
2727 $ url = $ this ->baseUrl . '/chat/completions ' ;
2828 $ headers = [
2929 'Authorization: Bearer ' . $ this ->apiKey ,
3030 'Content-Type: application/json ' ,
3131 ];
32-
32+
3333 $ response = $ this ->makeRequest ($ url , $ context , $ headers );
34-
34+
3535 return json_decode ($ response , true ) ?: [];
3636 }
37-
37+
3838 public function getSupportedModels (): array
3939 {
4040 return [
@@ -45,17 +45,17 @@ public function getSupportedModels(): array
4545 'gpt-4-turbo-preview '
4646 ];
4747 }
48-
48+
4949 public function getProviderName (): string
5050 {
5151 return 'openai ' ;
5252 }
53-
53+
5454 public function supportsToolCalling (): bool
5555 {
5656 return true ;
5757 }
58-
58+
5959 private function makeRequest (string $ url , array $ data , array $ headers ): string
6060 {
6161 $ ch = curl_init ();
@@ -67,22 +67,22 @@ private function makeRequest(string $url, array $data, array $headers): string
6767 CURLOPT_RETURNTRANSFER => true ,
6868 CURLOPT_TIMEOUT => 30 ,
6969 ]);
70-
70+
7171 $ response = curl_exec ($ ch );
7272 $ httpCode = curl_getinfo ($ ch , CURLINFO_HTTP_CODE );
73-
73+
7474 if ($ response === false ) {
7575 $ error = curl_error ($ ch );
7676 curl_close ($ ch );
7777 throw new \RuntimeException ("cURL request failed: {$ error }" );
7878 }
79-
79+
8080 curl_close ($ ch );
81-
81+
8282 if ($ httpCode !== 200 ) {
8383 throw new \RuntimeException ("OpenAI API request failed with HTTP code: {$ httpCode }" );
8484 }
85-
85+
8686 return (string ) $ response ;
8787 }
88- }
88+ }
0 commit comments