$config */ public function __construct( private readonly string $provider, private readonly array $config, ) {} public function complete(AiRequest $request): AiResponse { $apiKey = (string) ($this->config['api_key'] ?? ''); $baseUrl = rtrim((string) ($this->config['base_url'] ?? ''), '/'); if ($apiKey === '' || $baseUrl === '') { throw new AiException("The API key or base URL for [$this->provider] is missing in .env.", AiException::SETUP); } try { $response = Http::withToken($apiKey) ->timeout((int) config('ai.timeout', 240)) ->acceptJson() ->post($baseUrl.'/chat/completions', [ 'model' => $request->model, 'max_tokens' => $request->maxTokens, 'response_format' => ['type' => 'json_object'], 'messages' => [ ['role' => 'system', 'content' => $request->system], ['role' => 'user', 'content' => $request->prompt], ], ]); } catch (ConnectionException $e) { throw new AiException("Could not reach [$this->provider]: ".$e->getMessage(), AiException::PROVIDER, $e); } if ($response->failed()) { throw new AiException("[$this->provider] answered with HTTP {$response->status()}: ".mb_substr($response->body(), 0, 300)); } if ($response->json('choices.0.finish_reason') === 'length') { throw new AiException("[$this->provider] ran out of room before finishing its answer.", AiException::INVALID_RESULT); } return new AiResponse( text: (string) $response->json('choices.0.message.content', ''), provider: $this->provider, model: $request->model, inputTokens: (int) $response->json('usage.prompt_tokens', 0), outputTokens: (int) $response->json('usage.completion_tokens', 0), ); } }