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
+36
View File
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Services\Ai;
use App\Models\AiProvider;
use InvalidArgumentException;
class AiServiceFactory
{
/**
* Create an AI service instance based on the provider.
*
* @param AiProvider|string $provider
* @return AiServiceInterface
*/
public static function make(AiProvider|string $provider): AiServiceInterface
{
if (is_string($provider)) {
$provider = AiProvider::withTrashed()->where('slug', $provider)
->firstOrFail();
}
if (!$provider->is_active) {
throw new InvalidArgumentException('AI provider is not active.');
}
return match ($provider->slug) {
'openrouter', 'openrouter-test' => new OpenRouterService($provider),
'stepfun' => new StepFunService($provider),
'llamacpp' => new LlamaCppService($provider),
default => throw new InvalidArgumentException("Unsupported AI provider: {$provider->slug}"),
};
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Services\Ai;
interface AiServiceInterface
{
/**
* Generate a prompt using the AI provider.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
public function generatePrompt(array $data): array;
/**
* Send a chat conversation to the AI provider.
*
* @param array<int, array{role: string, content: string}> $messages
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
public function chat(array $messages, array $data = []): array;
}
+73
View File
@@ -0,0 +1,73 @@
<?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 LlamaCppService 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
{
$baseUrl = rtrim((string) $this->provider->base_url, '/');
if (empty($baseUrl)) {
throw new \InvalidArgumentException('Llama.cpp base URL is not configured.');
}
try {
$response = $this->client->post('v1/chat/completions', [
'headers' => [
'Content-Type' => 'application/json',
],
'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 Llama.cpp server.');
}
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('Llama.cpp API error: ' . $e->getMessage());
throw new \RuntimeException('Failed to generate prompt with Llama.cpp: ' . $e->getMessage(), (int) $e->getCode(), $e);
}
}
/**
* {@inheritdoc}
*/
public function generatePrompt(array $data): array
{
return $this->chat(
[['role' => 'user', 'content' => (string) ($data['prompt'] ?? '')]],
$data
);
}
}
+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
);
}
}
+86
View File
@@ -0,0 +1,86 @@
<?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 StepFunService 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('StepFun API key is not configured.');
}
try {
$payload = [
'model' => (string) ($data['model'] ?? ''),
'messages' => $messages,
];
if (isset($data['temperature'])) {
$payload['temperature'] = (float) $data['temperature'];
}
if (isset($data['max_tokens'])) {
$payload['max_tokens'] = (int) $data['max_tokens'];
}
if (!empty($data['reasoning_effort'])) {
$payload['reasoning_effort'] = (string) $data['reasoning_effort'];
}
$response = $this->client->post('chat/completions', [
'headers' => [
'Authorization' => 'Bearer ' . $apiKey,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
$body = json_decode($response->getBody()->getContents(), true);
if (!isset($body['choices'][0]['message']['content'])) {
throw new \RuntimeException('Invalid response structure from StepFun.');
}
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('StepFun API error: ' . $e->getMessage());
throw new \RuntimeException('Failed to generate prompt with StepFun: ' . $e->getMessage(), (int) $e->getCode(), $e);
}
}
/**
* {@inheritdoc}
*/
public function generatePrompt(array $data): array
{
return $this->chat(
[['role' => 'user', 'content' => (string) ($data['prompt'] ?? '')]],
$data
);
}
}