181 lines
7.3 KiB
PHP
181 lines
7.3 KiB
PHP
<?php
|
|
|
|
namespace Komponent\Component\Testquestions\Administrator\Service;
|
|
|
|
defined('_JEXEC') or die;
|
|
|
|
use Joomla\CMS\Http\HttpFactory;
|
|
|
|
class AiService
|
|
{
|
|
public static function availableModels(): array
|
|
{
|
|
return [
|
|
'openai' => [
|
|
'gpt-4.1-mini' => 'GPT-4.1 mini (starszy)',
|
|
'gpt-5.6-luna' => 'GPT-5.6 Luna',
|
|
'gpt-5.6-terra' => 'GPT-5.6 Terra',
|
|
'gpt-5.6-sol' => 'GPT-5.6 Sol',
|
|
'gpt-6-luna' => 'GPT-6 Luna',
|
|
],
|
|
'grok' => [
|
|
'grok-4.7' => 'Grok 4.7',
|
|
'grok-4.20' => 'Grok 4.20 Reasoning',
|
|
'grok-4.20-non-reasoning' => 'Grok 4.20 Non-Reasoning',
|
|
],
|
|
];
|
|
}
|
|
|
|
public function evaluate(string $provider, string $apiKey, string $model, string $question, string $answer, string $pattern, int $maxPoints): array
|
|
{
|
|
$provider = strtolower(trim($provider));
|
|
$provider = preg_replace('/[^a-z]/', '', $provider);
|
|
$config = $provider === 'grok'
|
|
? ['url' => 'https://api.x.ai/v1/responses']
|
|
: ['url' => 'https://api.openai.com/v1/responses'];
|
|
|
|
if (trim($apiKey) === '') {
|
|
throw new \RuntimeException('AI_NOT_CONFIGURED');
|
|
}
|
|
|
|
if (!in_array($provider, ['openai', 'grok'], true)) {
|
|
throw new \RuntimeException('Nieprawidłowy dostawca AI: ' . $provider);
|
|
}
|
|
|
|
if (!isset(self::availableModels()[$provider][$model])) {
|
|
throw new \RuntimeException('Wybrany model AI nie jest obsługiwany.');
|
|
}
|
|
|
|
$input = "Oceń odpowiedź ucznia na pytanie otwarte i ustal liczbę uznanych punktów.\n"
|
|
. "Maksymalna liczba punktów za to pytanie: " . max(0, $maxPoints) . ".\n"
|
|
. "Przyznaj liczbę całkowitą od 0 do maksymalnej liczby punktów. Przyznaj punkty proporcjonalnie za poprawne elementy odpowiedzi; pełne punkty za komplet, część punktów za częściową odpowiedź. Nie przekraczaj limitu.\n\n"
|
|
. "Pytanie:\n" . $question . "\n\n"
|
|
. "Wzorzec odpowiedzi:\n" . $pattern . "\n\n"
|
|
. "Odpowiedź ucznia:\n" . ($answer !== '' ? $answer : 'Brak odpowiedzi') . "\n\n"
|
|
. "Zwróć wyłącznie poprawny obiekt JSON w formacie {\"awarded_points\": liczba_całkowita, \"feedback\": \"krótka ocena po polsku\"}. W ocenie opisz poprawne i brakujące elementy. Nie zmieniaj wzorca odpowiedzi.";
|
|
|
|
$requestData = [
|
|
'model' => $model,
|
|
'input' => $input,
|
|
];
|
|
// GPT-5.x reasoning models do not accept a custom temperature.
|
|
if ($provider === 'grok' || $model === 'gpt-4.1-mini') {
|
|
$requestData['temperature'] = 0.1;
|
|
}
|
|
$payload = json_encode($requestData, JSON_UNESCAPED_UNICODE);
|
|
|
|
$response = HttpFactory::getHttp()->post(
|
|
$config['url'],
|
|
$payload,
|
|
[
|
|
'Authorization' => 'Bearer ' . trim($apiKey),
|
|
'Content-Type' => 'application/json',
|
|
],
|
|
60
|
|
);
|
|
$body = json_decode((string) $response->body, true);
|
|
|
|
if ((int) $response->code < 200 || (int) $response->code >= 300) {
|
|
throw new \RuntimeException((string) ($body['error']['message'] ?? ('HTTP ' . (int) $response->code)));
|
|
}
|
|
|
|
$text = $this->extractText($body);
|
|
if ($text === '') {
|
|
throw new \RuntimeException('Brak treści odpowiedzi AI.');
|
|
}
|
|
|
|
$jsonText = preg_replace('/^```(?:json)?\s*|\s*```$/i', '', trim($text));
|
|
$result = json_decode($jsonText, true);
|
|
|
|
if (!is_array($result) || !isset($result['awarded_points']) || !is_numeric($result['awarded_points'])) {
|
|
$start = strpos($jsonText, '{');
|
|
$end = strrpos($jsonText, '}');
|
|
if ($start !== false && $end !== false && $end > $start) {
|
|
$result = json_decode(substr($jsonText, $start, $end - $start + 1), true);
|
|
}
|
|
}
|
|
|
|
if (!is_array($result) || !isset($result['awarded_points']) || !is_numeric($result['awarded_points'])) {
|
|
throw new \RuntimeException('AI zwróciło nieprawidłowy format oceny i punktów.');
|
|
}
|
|
|
|
$actualModel = (string) ($body['model'] ?? $model);
|
|
$usage = $this->getUsage($body, $provider, $model);
|
|
if ($usage !== null) {
|
|
$usage['model'] = $actualModel;
|
|
}
|
|
|
|
return [
|
|
'awarded_points' => min(max(0, $maxPoints), max(0, (int) $result['awarded_points'])),
|
|
'feedback' => trim((string) ($result['feedback'] ?? '')),
|
|
'usage' => $usage,
|
|
];
|
|
}
|
|
|
|
private function getUsage(array $body, string $provider, string $model): ?array
|
|
{
|
|
$usage = $body['usage'] ?? null;
|
|
if (!is_array($usage) || !isset($usage['input_tokens'], $usage['output_tokens'])) {
|
|
return null;
|
|
}
|
|
|
|
$inputTokens = max(0, (int) $usage['input_tokens']);
|
|
$outputTokens = max(0, (int) $usage['output_tokens']);
|
|
$cachedTokens = min($inputTokens, max(0, (int) ($usage['input_tokens_details']['cached_tokens'] ?? 0)));
|
|
$cost = null;
|
|
$costSource = '';
|
|
|
|
if ($provider === 'grok' && isset($usage['cost_in_usd_ticks']) && is_numeric($usage['cost_in_usd_ticks'])) {
|
|
$cost = (float) $usage['cost_in_usd_ticks'] / 10000000000;
|
|
$costSource = 'provider';
|
|
} elseif ($provider === 'openai' && isset($this->openAiRates()[$model])) {
|
|
[$inputRate, $cachedRate, $outputRate, $cacheWriteRate] = $this->openAiRates()[$model];
|
|
$uncachedTokens = $inputTokens - $cachedTokens;
|
|
$cacheWriteTokens = min($uncachedTokens, max(0, (int) ($usage['input_tokens_details']['cache_write_tokens'] ?? 0)));
|
|
$uncachedTokens -= $cacheWriteTokens;
|
|
$cost = ($uncachedTokens * $inputRate + $cachedTokens * $cachedRate + $cacheWriteTokens * $cacheWriteRate + $outputTokens * $outputRate) / 1000000;
|
|
$costSource = 'token_rates';
|
|
}
|
|
|
|
return [
|
|
'provider' => $provider,
|
|
'model' => $model,
|
|
'input_tokens' => $inputTokens,
|
|
'output_tokens' => $outputTokens,
|
|
'total_tokens' => (int) ($usage['total_tokens'] ?? ($inputTokens + $outputTokens)),
|
|
'cached_input_tokens' => $cachedTokens,
|
|
'cost_usd' => $cost,
|
|
'cost_source' => $costSource,
|
|
];
|
|
}
|
|
|
|
private function openAiRates(): array
|
|
{
|
|
return [
|
|
'gpt-4.1-mini' => [0.40, 0.10, 1.60, 0.40],
|
|
'gpt-5.6-luna' => [0.20, 0.02, 1.20, 0.25],
|
|
'gpt-5.6-terra' => [2.00, 0.20, 12.00, 2.50],
|
|
'gpt-5.6-sol' => [4.00, 0.40, 20.00, 5.00],
|
|
'gpt-6-luna' => [0.10, 0.01, 0.50, 0.125],
|
|
];
|
|
}
|
|
|
|
private function extractText(array $body): string
|
|
{
|
|
if (!empty($body['output_text']) && is_string($body['output_text'])) {
|
|
return trim($body['output_text']);
|
|
}
|
|
|
|
$parts = [];
|
|
foreach ((array) ($body['output'] ?? []) as $output) {
|
|
foreach ((array) ($output['content'] ?? []) as $content) {
|
|
if (!empty($content['text']) && is_string($content['text'])) {
|
|
$parts[] = $content['text'];
|
|
}
|
|
}
|
|
}
|
|
|
|
return trim(implode("\n", $parts));
|
|
}
|
|
}
|