236 lines
10 KiB
PHP
236 lines
10 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',
|
|
],
|
|
'groq' => [
|
|
'openai/gpt-oss-120b' => 'GPT OSS 120B',
|
|
'openai/gpt-oss-20b' => 'GPT OSS 20B',
|
|
'llama-3.3-70b-versatile' => 'Llama 3.3 70B Versatile',
|
|
],
|
|
'gemini' => [
|
|
'gemini-3.8-flash' => 'Gemini 3.8 Flash',
|
|
'gemini-3.1-pro-preview' => 'Gemini 3.1 Pro (Preview)',
|
|
],
|
|
];
|
|
}
|
|
|
|
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 = match ($provider) {
|
|
'grok' => ['url' => 'https://api.x.ai/v1/responses'],
|
|
'groq' => ['url' => 'https://api.groq.com/openai/v1/chat/completions'],
|
|
'gemini' => ['url' => 'https://generativelanguage.googleapis.com/v1beta/models/' . rawurlencode($model) . ':generateContent'],
|
|
default => ['url' => 'https://api.openai.com/v1/responses'],
|
|
};
|
|
|
|
if (trim($apiKey) === '') {
|
|
throw new \RuntimeException('AI_NOT_CONFIGURED');
|
|
}
|
|
|
|
if (!in_array($provider, ['openai', 'grok', 'groq', 'gemini'], 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 = match ($provider) {
|
|
'groq' => [
|
|
'model' => $model,
|
|
'messages' => [['role' => 'user', 'content' => $input]],
|
|
'temperature' => 0.1,
|
|
],
|
|
'gemini' => [
|
|
'contents' => [['parts' => [['text' => $input]]]],
|
|
'generationConfig' => [
|
|
'maxOutputTokens' => 256,
|
|
'responseMimeType' => 'application/json',
|
|
'thinkingConfig' => ['thinkingLevel' => 'low'],
|
|
],
|
|
],
|
|
default => [
|
|
'model' => $model,
|
|
'input' => $input,
|
|
],
|
|
};
|
|
// GPT-5.x reasoning models do not accept a custom temperature.
|
|
if ($provider === 'grok' || ($provider === 'openai' && $model === 'gpt-4.1-mini')) {
|
|
$requestData['temperature'] = 0.1;
|
|
}
|
|
$payload = json_encode($requestData, JSON_UNESCAPED_UNICODE);
|
|
|
|
$headers = [
|
|
'Content-Type' => 'application/json',
|
|
];
|
|
if ($provider === 'gemini') {
|
|
$headers['x-goog-api-key'] = trim($apiKey);
|
|
} else {
|
|
$headers['Authorization'] = 'Bearer ' . trim($apiKey);
|
|
}
|
|
|
|
$response = HttpFactory::getHttp()->post(
|
|
$config['url'],
|
|
$payload,
|
|
$headers,
|
|
$provider === 'gemini' ? 25 : 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
|
|
{
|
|
// Gemini uses camelCase UsageMetadata at the response root; the
|
|
// OpenAI-compatible providers return their counters in `usage`.
|
|
$usage = $body['usageMetadata'] ?? $body['usage'] ?? null;
|
|
if (!is_array($usage)) {
|
|
return null;
|
|
}
|
|
|
|
$inputTokens = max(0, (int) ($usage['input_tokens'] ?? $usage['prompt_tokens'] ?? $usage['promptTokenCount'] ?? 0));
|
|
$outputTokens = max(0, (int) ($usage['output_tokens'] ?? $usage['completion_tokens'] ?? (
|
|
(int) ($usage['candidatesTokenCount'] ?? 0) + (int) ($usage['thoughtsTokenCount'] ?? 0)
|
|
)));
|
|
if ((!isset($usage['input_tokens']) && !isset($usage['prompt_tokens']) && !isset($usage['promptTokenCount']))
|
|
|| (!isset($usage['output_tokens']) && !isset($usage['completion_tokens']) && !isset($usage['candidatesTokenCount']))) {
|
|
return null;
|
|
}
|
|
$cachedTokens = min($inputTokens, max(0, (int) ($usage['input_tokens_details']['cached_tokens'] ?? $usage['cachedContentTokenCount'] ?? 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'] ?? $usage['totalTokenCount'] ?? ($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 (isset($body['candidates'][0]['content']['parts']) && is_array($body['candidates'][0]['content']['parts'])) {
|
|
$parts = [];
|
|
foreach ($body['candidates'][0]['content']['parts'] as $part) {
|
|
if (isset($part['text']) && is_string($part['text'])) {
|
|
$parts[] = $part['text'];
|
|
}
|
|
}
|
|
return trim(implode("\n", $parts));
|
|
}
|
|
|
|
if (isset($body['choices'][0]['message']['content']) && is_string($body['choices'][0]['message']['content'])) {
|
|
return trim($body['choices'][0]['message']['content']);
|
|
}
|
|
|
|
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));
|
|
}
|
|
}
|