Tars/src/Services/OpenAI/OpenAIClient.php
2025-03-17 19:40:42 +01:00

44 lines
1.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services\OpenAI;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
class OpenAIClient
{
public function __construct(
private readonly HttpClientInterface $httpClient,
#[Autowire('%env(OPENAI_API_KEY)%')]
private readonly string $apiKey,
#[Autowire('%env(OPENAI_API_URL)%')]
private readonly string $apiUrl
) {
}
public function chat(array $messages, float $temperature = 0.7, int $maxTokens = 2048): array
{
$response = $this->sendRequest('/chat/completions', [
'model' => 'o3-mini',
'messages' => $messages,
'reasoning_effort' => 'low',
]);
return $response->toArray();
}
public function sendRequest(string $endpoint, array $data): ResponseInterface
{
return $this->httpClient->request('POST', "{$this->apiUrl}{$endpoint}", [
'headers' => [
'Authorization' => "Bearer {$this->apiKey}",
'Content-Type' => 'application/json',
],
'json' => $data,
]);
}
}