2026-08-06 20:47:06 +03:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Support\AiProviders;
|
|
|
|
|
|
|
|
|
|
use App\Models\AiProvider;
|
|
|
|
|
use Illuminate\Http\Client\ConnectionException;
|
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Text generation via OpenAI's Chat Completions API. Used for scripts,
|
|
|
|
|
* metadata (titles/descriptions/tags), and similar text content.
|
|
|
|
|
*/
|
|
|
|
|
class OpenAiDriver implements AiProviderDriver
|
|
|
|
|
{
|
|
|
|
|
public function generate(AiProvider $provider, string $prompt, array $options = []): AiGenerationResult
|
|
|
|
|
{
|
|
|
|
|
$model = $options['model'] ?? $provider->config['model'] ?? 'gpt-4o-mini';
|
|
|
|
|
|
2026-08-06 21:15:31 +03:00
|
|
|
$body = [
|
|
|
|
|
'model' => $model,
|
|
|
|
|
'messages' => [
|
|
|
|
|
['role' => 'user', 'content' => $prompt],
|
|
|
|
|
],
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
// Ask the API to guarantee valid JSON back, for callers that need
|
|
|
|
|
// structured output (e.g. a storyboard's scene breakdown). The
|
|
|
|
|
// prompt itself must still ask for JSON — this only enforces it.
|
|
|
|
|
if ($options['json_mode'] ?? false) {
|
|
|
|
|
$body['response_format'] = ['type' => 'json_object'];
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-06 20:47:06 +03:00
|
|
|
try {
|
|
|
|
|
$response = Http::withToken($provider->api_key)
|
2026-08-06 21:15:31 +03:00
|
|
|
->post('https://api.openai.com/v1/chat/completions', $body);
|
2026-08-06 20:47:06 +03:00
|
|
|
} catch (ConnectionException $e) {
|
|
|
|
|
throw new AiGenerationException("could not connect to OpenAI: {$e->getMessage()}");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ($response->failed()) {
|
|
|
|
|
throw new AiGenerationException($response->json('error.message') ?? 'unexpected response from OpenAI');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$content = $response->json('choices.0.message.content');
|
|
|
|
|
|
|
|
|
|
if (! $content) {
|
|
|
|
|
throw new AiGenerationException('unexpected response from OpenAI: missing message content');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return new AiGenerationResult($content, 'text/plain', $response->json());
|
|
|
|
|
}
|
|
|
|
|
}
|