| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- <?php
-
- namespace App\Ai\Drivers;
-
- use App\Ai\AiDriver;
- use App\Ai\AiException;
- use App\Ai\AiRequest;
- use App\Ai\AiResponse;
- use Illuminate\Http\Client\ConnectionException;
- use Illuminate\Support\Facades\Http;
-
- /**
- * Any provider that speaks the common "chat completions" format.
- * DeepSeek uses it, and so do many others, so a new provider is usually just a config entry.
- */
- final class OpenAiCompatibleDriver implements AiDriver
- {
- /**
- * @param array<string, mixed> $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),
- );
- }
- }
|