First Commit

This commit is contained in:
marco
2026-09-01 09:22:30 -03:00
commit a43ae23eb4
407 changed files with 36138 additions and 0 deletions
+76
View File
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace App\Services\Ai;
use App\Models\AiProvider;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
class OpenRouterService implements AiServiceInterface
{
/**
* @param AiProvider $provider
*/
public function __construct(private AiProvider $provider)
{
$this->client = new Client([
'base_uri' => rtrim((string) $provider->base_url, '/') . '/',
'timeout' => 120,
]);
}
public function chat(array $messages, array $data = []): array
{
$apiKey = $data['api_key'] ?? $this->provider->api_key;
if (empty($apiKey)) {
throw new \InvalidArgumentException('OpenRouter API key is not configured.');
}
try {
$response = $this->client->post('chat/completions', [
'headers' => [
'Authorization' => 'Bearer ' . $apiKey,
'Content-Type' => 'application/json',
'HTTP-Referer' => $data['http_referer'] ?? config('app.url'),
'X-Title' => $data['x_title'] ?? config('app.name'),
],
'json' => [
'model' => (string) ($data['model'] ?? ''),
'messages' => $messages,
'temperature' => isset($data['temperature']) ? (float) $data['temperature'] : null,
'max_tokens' => isset($data['max_tokens']) ? (int) $data['max_tokens'] : null,
],
]);
$body = json_decode($response->getBody()->getContents(), true);
if (!isset($body['choices'][0]['message']['content'])) {
throw new \RuntimeException('Invalid response structure from OpenRouter.');
}
return [
'content' => $body['choices'][0]['message']['content'],
'tokens_used' => $body['usage']['total_tokens'] ?? null,
'model' => $body['model'] ?? (string) ($data['model'] ?? ''),
];
} catch (GuzzleException $e) {
Log::error('OpenRouter API error: ' . $e->getMessage());
throw new \RuntimeException('Failed to generate prompt with OpenRouter: ' . $e->getMessage(), (int) $e->getCode(), $e);
}
}
/**
* {@inheritdoc}
*/
public function generatePrompt(array $data): array
{
return $this->chat(
[['role' => 'user', 'content' => (string) ($data['prompt'] ?? '')]],
$data
);
}
}