Compare commits

...
5 Commits
14 changed files with 281 additions and 37 deletions
+1 -1
View File
@@ -30,6 +30,6 @@ Szkielet komponentu Joomla 6 do gromadzenia pytań testowych.
## Instalacja ## Instalacja
W Joomla wybierz **System → Install → Install from Folder** i wskaż ten katalog. Manifestem instalacyjnym jest `com_testquestions.xml` (wersja 1.42.9). W Joomla wybierz **System → Install → Install from Folder** i wskaż ten katalog. Manifestem instalacyjnym jest `com_testquestions.xml` (wersja 1.43.4).
Po instalacji komponent jest dostępny w panelu administratora jako **Pytania testowe**. Po instalacji komponent jest dostępny w panelu administratora jako **Pytania testowe**.
@@ -65,10 +65,16 @@ COM_TESTQUESTIONS_SET_VARIANT_DURATION_INFO="Czas testu jest pobierany z zestawu
COM_TESTQUESTIONS_AI_SETTINGS="Ustawienia AI" COM_TESTQUESTIONS_AI_SETTINGS="Ustawienia AI"
COM_TESTQUESTIONS_AI_PROVIDER="Dostawca AI" COM_TESTQUESTIONS_AI_PROVIDER="Dostawca AI"
COM_TESTQUESTIONS_AI_API_KEY="Klucz API" COM_TESTQUESTIONS_AI_API_KEY="Klucz API"
COM_TESTQUESTIONS_AI_OPENAI_KEY="Klucz API OpenAI"
COM_TESTQUESTIONS_AI_GROK_KEY="Klucz API Grok"
COM_TESTQUESTIONS_AI_SETTINGS_MENU="Konfiguracja AI" COM_TESTQUESTIONS_AI_SETTINGS_MENU="Konfiguracja AI"
COM_TESTQUESTIONS_AI_SETTINGS_SAVED="Ustawienia AI zapisano." COM_TESTQUESTIONS_AI_SETTINGS_SAVED="Ustawienia AI zapisano."
COM_TESTQUESTIONS_AI_SAVE_FAILED="Nie udało się zapisać ustawień AI." COM_TESTQUESTIONS_AI_SAVE_FAILED="Nie udało się zapisać ustawień AI."
COM_TESTQUESTIONS_AI_PROVIDER_INVALID="Wybierz prawidłowego dostawcę AI." COM_TESTQUESTIONS_AI_PROVIDER_INVALID="Wybierz prawidłowego dostawcę AI."
COM_TESTQUESTIONS_AI_EVALUATE_ALL="AI — oceń wszystkie niezaliczone pytania otwarte (%s)"
COM_TESTQUESTIONS_AI_BULK_DONE="AI oceniło %s pytań."
COM_TESTQUESTIONS_AI_BULK_PARTIAL="AI oceniło %s pytań; nie udało się ocenić %s. Błąd: %s"
COM_TESTQUESTIONS_AI_NO_OPEN_QUESTIONS="Brak niezaliczonych pytań otwartych do oceny AI."
COM_TESTQUESTIONS_AI_EVALUATE="AI" COM_TESTQUESTIONS_AI_EVALUATE="AI"
COM_TESTQUESTIONS_AI_RESULT="Ocena AI" COM_TESTQUESTIONS_AI_RESULT="Ocena AI"
COM_TESTQUESTIONS_AI_NOT_CONFIGURED="Skonfiguruj dostawcę i klucz API w ustawieniach komponentu." COM_TESTQUESTIONS_AI_NOT_CONFIGURED="Skonfiguruj dostawcę i klucz API w ustawieniach komponentu."
@@ -0,0 +1 @@
-- No database changes required for version 1.43.0.
@@ -0,0 +1 @@
-- No database changes required for version 1.43.1.
@@ -0,0 +1 @@
-- No database changes required for version 1.43.2.
@@ -0,0 +1 @@
-- No database changes required for version 1.43.3.
@@ -0,0 +1 @@
-- No database changes required for version 1.43.4.
@@ -44,13 +44,23 @@ class AiController extends BaseController
$settings = json_decode((string) $row->params, true); $settings = json_decode((string) $row->params, true);
$settings = is_array($settings) ? $settings : []; $settings = is_array($settings) ? $settings : [];
$apiKey = trim((string) $input->post->get('ai_api_key', '', 'RAW')); $legacyKey = trim((string) ($settings['ai_api_key'] ?? ''));
$settings['ai_provider'] = $provider; $settings['ai_provider'] = $provider;
foreach (['openai', 'grok'] as $keyProvider) {
$fieldName = 'ai_' . $keyProvider . '_api_key';
$apiKey = trim((string) $input->post->get($fieldName, '', 'RAW'));
if ($apiKey !== '') { if ($apiKey !== '') {
$settings['ai_api_key'] = $apiKey; $settings[$fieldName] = $apiKey;
} }
if ($keyProvider === $provider && empty($settings[$fieldName]) && $legacyKey !== '') {
$settings[$fieldName] = $legacyKey;
}
}
unset($settings['ai_api_key']);
$extension = (object) [ $extension = (object) [
'extension_id' => (int) $row->extension_id, 'extension_id' => (int) $row->extension_id,
'params' => json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'params' => json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
@@ -63,6 +63,47 @@ class ResultController extends BaseController
); );
} }
public function aiAll(): void
{
if (!Session::checkToken()) {
throw new \RuntimeException(Text::_('JINVALID_TOKEN'), 403);
}
$input = Factory::getApplication()->getInput();
$id = $input->post->getInt('id');
$message = '';
$type = 'message';
try {
$summary = $this->getModel('Result')->evaluateAllWithAi($id);
if ($summary['failed'] > 0) {
$message = Text::sprintf(
'COM_TESTQUESTIONS_AI_BULK_PARTIAL',
$summary['evaluated'],
$summary['failed'],
$summary['first_error']
);
$type = 'warning';
} else {
$message = Text::sprintf('COM_TESTQUESTIONS_AI_BULK_DONE', $summary['evaluated']);
}
} catch (\Throwable $error) {
$errorMessage = $error->getMessage();
$message = $errorMessage === 'AI_NO_OPEN_QUESTIONS'
? Text::_('COM_TESTQUESTIONS_AI_NO_OPEN_QUESTIONS')
: ($errorMessage === 'AI_NOT_CONFIGURED'
? Text::_('COM_TESTQUESTIONS_AI_NOT_CONFIGURED')
: Text::sprintf('COM_TESTQUESTIONS_AI_ERROR', $errorMessage));
$type = 'error';
}
$this->setRedirect(
Route::_('index.php?option=com_testquestions&view=result&id=' . $id, false),
$message,
$type
);
}
private function saveAssessment(): void private function saveAssessment(): void
{ {
if (!Session::checkToken()) { if (!Session::checkToken()) {
@@ -92,7 +92,9 @@ class ResultModel extends BaseDatabaseModel
$params = ComponentHelper::getParams('com_testquestions'); $params = ComponentHelper::getParams('com_testquestions');
$provider = trim((string) $params->get('ai_provider', 'openai')); $provider = trim((string) $params->get('ai_provider', 'openai'));
$apiKey = trim((string) $params->get('ai_api_key', '')); $provider = strtolower(preg_replace('/[^a-z]/', '', $provider));
$keyName = 'ai_' . $provider . '_api_key';
$apiKey = trim((string) $params->get($keyName, $params->get('ai_api_key', '')));
$componentKeyLength = mb_strlen($apiKey); $componentKeyLength = mb_strlen($apiKey);
// Odczytaj zapisane parametry bezpośrednio z bazy. Dzięki temu nie użyjemy // Odczytaj zapisane parametry bezpośrednio z bazy. Dzięki temu nie użyjemy
@@ -115,14 +117,21 @@ class ResultModel extends BaseDatabaseModel
if ($storedProvider !== '') { if ($storedProvider !== '') {
$provider = $storedProvider; $provider = $storedProvider;
} }
}
$provider = strtolower(preg_replace('/[^a-z]/', '', $provider));
$keyName = 'ai_' . $provider . '_api_key';
$apiKey = trim((string) $params->get($keyName, $params->get('ai_api_key', '')));
$componentKeyLength = mb_strlen($apiKey);
$storedApiKey = is_array($storedParams)
? trim((string) ($storedParams[$keyName] ?? $storedParams['ai_api_key'] ?? ''))
: '';
if ($storedApiKey !== '' && !preg_match('/^\*+$/', $storedApiKey)) { if ($storedApiKey !== '' && !preg_match('/^\*+$/', $storedApiKey)) {
$apiKey = $storedApiKey; $apiKey = $storedApiKey;
} }
}
if (trim($apiKey) === '') { if (trim($apiKey) === '') {
$databaseKey = is_array($storedParams) ? trim((string) ($storedParams['ai_api_key'] ?? '')) : ''; $databaseKey = $storedApiKey;
$databaseKeyLength = preg_match('/^\*+$/', $databaseKey) ? 0 : mb_strlen($databaseKey); $databaseKeyLength = preg_match('/^\*+$/', $databaseKey) ? 0 : mb_strlen($databaseKey);
throw new \RuntimeException( throw new \RuntimeException(
'AI_KEY_EMPTY|provider=' . ($provider !== '' ? $provider : '(pusty)') 'AI_KEY_EMPTY|provider=' . ($provider !== '' ? $provider : '(pusty)')
@@ -132,25 +141,83 @@ class ResultModel extends BaseDatabaseModel
); );
} }
$feedback = (new AiService())->evaluate( $aiResult = (new AiService())->evaluate(
$provider, $provider,
$apiKey, $apiKey,
strip_tags((string) $question->question), strip_tags((string) $question->question),
(string) ($answer['selected'] ?? ''), (string) ($answer['selected'] ?? ''),
(string) $question->answer_open (string) $question->answer_open,
(int) $question->points
); );
$item->answers[$questionId]['ai_feedback'] = $feedback; $item->answers[$questionId]['ai_feedback'] = $aiResult['feedback'];
$item->answers[$questionId]['awarded_points'] = $aiResult['awarded_points'];
if ($aiResult['usage'] !== null) {
$item->answers[$questionId]['ai_usage'] = $aiResult['usage'];
}
$correctionPoints = 0;
foreach ($item->answers as $savedAnswer) {
$correctionPoints += (int) ($savedAnswer['awarded_points'] ?? 0);
}
$db = Factory::getContainer()->get('DatabaseDriver'); $db = Factory::getContainer()->get('DatabaseDriver');
$row = (object) [ $row = (object) [
'id' => $id, 'id' => $id,
'answers' => json_encode($item->answers, JSON_UNESCAPED_UNICODE), 'answers' => json_encode($item->answers, JSON_UNESCAPED_UNICODE),
'points_after' => (int) $item->points_before + $correctionPoints,
]; ];
if (!$db->updateObject('#__testquestions_results', $row, 'id')) { if (!$db->updateObject('#__testquestions_results', $row, 'id')) {
throw new \RuntimeException('Nie udało się zapisać oceny AI.'); throw new \RuntimeException('Nie udało się zapisać oceny AI.');
} }
return $feedback; return $aiResult['feedback'];
}
public function evaluateAllWithAi(int $id): array
{
$item = $this->getItem($id);
if (!$item) {
throw new \RuntimeException('Nie znaleziono zapisanego testu.');
}
$questionIds = [];
foreach ($item->answers as $questionId => $answer) {
$question = $item->questions[(int) $questionId] ?? null;
if ($question && $question->question_type === 'open' && empty($answer['correct'])) {
$questionIds[] = (int) $questionId;
}
}
if (!$questionIds) {
throw new \RuntimeException('AI_NO_OPEN_QUESTIONS');
}
$evaluated = 0;
$failed = 0;
$firstError = '';
foreach ($questionIds as $questionId) {
try {
$this->evaluateWithAi($id, $questionId);
$evaluated++;
} catch (\Throwable $error) {
$failed++;
$firstError = $firstError ?: $error->getMessage();
if (in_array($error->getMessage(), ['AI_NOT_CONFIGURED'], true)
|| str_starts_with($error->getMessage(), 'AI_KEY_EMPTY|')) {
break;
}
}
}
return [
'evaluated' => $evaluated,
'failed' => $failed,
'first_error' => $firstError,
'total' => count($questionIds),
];
} }
} }
@@ -8,7 +8,7 @@ use Joomla\CMS\Http\HttpFactory;
class AiService class AiService
{ {
public function evaluate(string $provider, string $apiKey, string $question, string $answer, string $pattern): string public function evaluate(string $provider, string $apiKey, string $question, string $answer, string $pattern, int $maxPoints): array
{ {
$provider = strtolower(trim($provider)); $provider = strtolower(trim($provider));
$provider = preg_replace('/[^a-z]/', '', $provider); $provider = preg_replace('/[^a-z]/', '', $provider);
@@ -24,11 +24,13 @@ class AiService
throw new \RuntimeException('Nieprawidłowy dostawca AI: ' . $provider); throw new \RuntimeException('Nieprawidłowy dostawca AI: ' . $provider);
} }
$input = "Oceń odpowiedź ucznia na pytanie otwarte.\n\n" $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" . "Pytanie:\n" . $question . "\n\n"
. "Wzorzec odpowiedzi:\n" . $pattern . "\n\n" . "Wzorzec odpowiedzi:\n" . $pattern . "\n\n"
. "Odpowiedź ucznia:\n" . ($answer !== '' ? $answer : 'Brak odpowiedzi') . "\n\n" . "Odpowiedź ucznia:\n" . ($answer !== '' ? $answer : 'Brak odpowiedzi') . "\n\n"
. "Napisz po polsku krótką ocenę: czy odpowiedź może zostać uznana za poprawną, jakie elementy są poprawne lub błędne oraz czy warto przyznać punkty. Nie zmieniaj wzorca odpowiedzi."; . "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.";
$payload = json_encode([ $payload = json_encode([
'model' => $config['model'], 'model' => $config['model'],
@@ -56,7 +58,62 @@ class AiService
throw new \RuntimeException('Brak treści odpowiedzi AI.'); throw new \RuntimeException('Brak treści odpowiedzi AI.');
} }
return $text; $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.');
}
$usage = $this->getUsage($body, $provider, $config['model']);
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' && $model === 'gpt-4.1-mini') {
$uncachedTokens = $inputTokens - $cachedTokens;
$cost = ($uncachedTokens * 0.40 + $cachedTokens * 0.10 + $outputTokens * 1.60) / 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 extractText(array $body): string private function extractText(array $body): string
@@ -2,7 +2,9 @@
<?php use Joomla\CMS\HTML\HTMLHelper; ?> <?php use Joomla\CMS\HTML\HTMLHelper; ?>
<?php use Joomla\CMS\Router\Route; ?> <?php use Joomla\CMS\Router\Route; ?>
<?php $provider = (string) ($this->settings['ai_provider'] ?? 'openai'); ?> <?php $provider = (string) ($this->settings['ai_provider'] ?? 'openai'); ?>
<?php $apiKey = (string) ($this->settings['ai_api_key'] ?? ''); ?> <?php $legacyKey = (string) ($this->settings['ai_api_key'] ?? ''); ?>
<?php $openaiKey = (string) ($this->settings['ai_openai_api_key'] ?? ($provider === 'openai' ? $legacyKey : '')); ?>
<?php $grokKey = (string) ($this->settings['ai_grok_api_key'] ?? ($provider === 'grok' ? $legacyKey : '')); ?>
<form action="<?php echo Route::_('index.php?option=com_testquestions&view=ai'); ?>" method="post" name="adminForm" id="adminForm"> <form action="<?php echo Route::_('index.php?option=com_testquestions&view=ai'); ?>" method="post" name="adminForm" id="adminForm">
<div class="card" style="max-width: 900px;"> <div class="card" style="max-width: 900px;">
<div class="card-body"> <div class="card-body">
@@ -14,13 +16,23 @@
</select> </select>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="ai-api-key" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_API_KEY'); ?></label> <label for="ai-openai-api-key" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_OPENAI_KEY'); ?></label>
<div class="input-group"> <div class="input-group">
<input type="password" id="ai-api-key" name="ai_api_key" value="<?php echo htmlspecialchars($apiKey, ENT_QUOTES, 'UTF-8'); ?>" class="form-control" size="120" maxlength="4096" autocomplete="new-password"> <input type="password" id="ai-openai-api-key" name="ai_openai_api_key" value="<?php echo htmlspecialchars($openaiKey, ENT_QUOTES, 'UTF-8'); ?>" class="form-control" size="120" maxlength="4096" autocomplete="new-password">
<button type="button" class="btn btn-outline-secondary" id="ai-key-toggle">Pokaż</button> <button type="button" class="btn btn-outline-secondary" data-ai-key-toggle="ai-openai-api-key">Pokaż</button>
</div> </div>
<small class="form-text text-muted"> <small class="form-text text-muted">
<?php echo $apiKey !== '' ? 'Zapisany klucz: ' . mb_strlen($apiKey) . ' znaków. Pozostaw pole bez zmian, aby zachować klucz.' : 'Nie zapisano jeszcze klucza API.'; ?> <?php echo $openaiKey !== '' ? 'Zapisany klucz: ' . mb_strlen($openaiKey) . ' znaków. Pozostaw pole bez zmian, aby go zachować.' : 'Nie zapisano klucza OpenAI.'; ?>
</small>
</div>
<div class="mb-3">
<label for="ai-grok-api-key" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROK_KEY'); ?></label>
<div class="input-group">
<input type="password" id="ai-grok-api-key" name="ai_grok_api_key" value="<?php echo htmlspecialchars($grokKey, ENT_QUOTES, 'UTF-8'); ?>" class="form-control" size="120" maxlength="4096" autocomplete="new-password">
<button type="button" class="btn btn-outline-secondary" data-ai-key-toggle="ai-grok-api-key">Pokaż</button>
</div>
<small class="form-text text-muted">
<?php echo $grokKey !== '' ? 'Zapisany klucz: ' . mb_strlen($grokKey) . ' znaków. Pozostaw pole bez zmian, aby go zachować.' : 'Nie zapisano klucza Grok.'; ?>
</small> </small>
</div> </div>
<button type="submit" class="btn btn-primary" onclick="this.form.task.value='ai.save';"> <button type="submit" class="btn btn-primary" onclick="this.form.task.value='ai.save';">
@@ -35,10 +47,12 @@
<?php echo HTMLHelper::_('form.token'); ?> <?php echo HTMLHelper::_('form.token'); ?>
</form> </form>
<script> <script>
document.getElementById('ai-key-toggle')?.addEventListener('click', function () { document.querySelectorAll('[data-ai-key-toggle]').forEach(function (button) {
const input = document.getElementById('ai-api-key'); button.addEventListener('click', function () {
const input = document.getElementById(this.dataset.aiKeyToggle);
const visible = input.type === 'text'; const visible = input.type === 'text';
input.type = visible ? 'password' : 'text'; input.type = visible ? 'password' : 'text';
this.textContent = visible ? 'Pokaż' : 'Ukryj'; this.textContent = visible ? 'Pokaż' : 'Ukryj';
});
}); });
</script> </script>
@@ -25,6 +25,37 @@
<dd class="col-sm-9"><?php echo floor((int) $this->item->execution_time / 60); ?>:<?php echo str_pad((string) ((int) $this->item->execution_time % 60), 2, '0', STR_PAD_LEFT); ?></dd> <dd class="col-sm-9"><?php echo floor((int) $this->item->execution_time / 60); ?>:<?php echo str_pad((string) ((int) $this->item->execution_time % 60), 2, '0', STR_PAD_LEFT); ?></dd>
</dl> </dl>
<form action="<?php echo Route::_('index.php?option=com_testquestions&view=result&id=' . (int) $this->item->id); ?>" method="post" name="adminForm" id="adminForm"> <form action="<?php echo Route::_('index.php?option=com_testquestions&view=result&id=' . (int) $this->item->id); ?>" method="post" name="adminForm" id="adminForm">
<?php $pendingAiCount = 0; ?>
<?php foreach ($this->item->answers as $questionId => $answer) : ?>
<?php $candidate = $this->item->questions[(int) $questionId] ?? null; ?>
<?php if ($candidate && $candidate->question_type === 'open' && empty($answer['correct'])) { $pendingAiCount++; } ?>
<?php endforeach; ?>
<?php if ($pendingAiCount > 0) : ?>
<div class="mb-3">
<button type="submit" class="btn btn-primary" formaction="<?php echo Route::_('index.php?option=com_testquestions&task=result.aiAll&id=' . (int) $this->item->id); ?>" onclick="this.form.task.value='result.aiAll';">
<?php echo \Joomla\CMS\Language\Text::sprintf('COM_TESTQUESTIONS_AI_EVALUATE_ALL', $pendingAiCount); ?>
</button>
<?php
$usageTotals = ['input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'providers' => []];
foreach ($this->item->answers as $savedAnswer) {
$usage = $savedAnswer['ai_usage'] ?? null;
if (!is_array($usage)) continue;
$usageTotals['input_tokens'] += (int) ($usage['input_tokens'] ?? 0);
$usageTotals['output_tokens'] += (int) ($usage['output_tokens'] ?? 0);
$usageTotals['total_tokens'] += (int) ($usage['total_tokens'] ?? 0);
if (is_numeric($usage['cost_usd'] ?? null)) $usageTotals['cost_usd'] += (float) $usage['cost_usd'];
if (!empty($usage['provider'])) $usageTotals['providers'][(string) $usage['provider']] = true;
}
?>
<?php if ($usageTotals['total_tokens'] > 0) : ?>
<span class="badge text-bg-light border ms-2" title="Suma dotychczasowych ocen AI">
✦ <?php echo implode(' + ', array_map('htmlspecialchars', array_keys($usageTotals['providers']))); ?>:
<?php echo number_format($usageTotals['total_tokens'], 0, ',', ' '); ?> tokenów,
<?php echo number_format($usageTotals['cost_usd'], 8, ',', ' '); ?> USD
</span>
<?php endif; ?>
</div>
<?php endif; ?>
<h2><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_ANSWERS'); ?></h2> <h2><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_ANSWERS'); ?></h2>
<?php foreach ($this->item->answers as $questionId => $answer) : ?> <?php foreach ($this->item->answers as $questionId => $answer) : ?>
<?php $question = $this->item->questions[(int) $questionId] ?? null; if (!$question) continue; ?> <?php $question = $this->item->questions[(int) $questionId] ?? null; if (!$question) continue; ?>
@@ -43,11 +74,23 @@
<button type="submit" name="ai_question_id" value="<?php echo (int) $questionId; ?>" onclick="this.form.task.value='result.ai';" formaction="<?php echo Route::_('index.php?option=com_testquestions&task=result.ai&id=' . (int) $this->item->id); ?>" class="btn btn-outline-primary"> <button type="submit" name="ai_question_id" value="<?php echo (int) $questionId; ?>" onclick="this.form.task.value='result.ai';" formaction="<?php echo Route::_('index.php?option=com_testquestions&task=result.ai&id=' . (int) $this->item->id); ?>" class="btn btn-outline-primary">
<?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_EVALUATE'); ?> <?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_EVALUATE'); ?>
</button> </button>
<?php if (!empty($answer['ai_usage']) && is_array($answer['ai_usage'])) : ?>
<?php $usage = $answer['ai_usage']; ?>
<?php $usageProvider = (string) ($usage['provider'] ?? ''); ?>
<span class="badge text-bg-light border ms-2" title="<?php echo $usageProvider === 'grok' ? 'Koszt zwrócony przez dostawcę' : 'Koszt obliczony z faktycznie wykorzystanych tokenów i stawek modelu'; ?>">
<?php echo $usageProvider === 'grok' ? '✦ Grok' : '◉ OpenAI'; ?> ·
<?php echo number_format((int) ($usage['input_tokens'] ?? 0), 0, ',', ' '); ?> in /
<?php echo number_format((int) ($usage['output_tokens'] ?? 0), 0, ',', ' '); ?> out ·
<?php echo is_numeric($usage['cost_usd'] ?? null) ? number_format((float) $usage['cost_usd'], 8, ',', ' ') . ' USD' : 'koszt niedostępny'; ?>
<?php echo ($usage['cost_source'] ?? '') === 'token_rates' ? ' (wyliczony)' : ''; ?>
</span>
<?php endif; ?>
</div> </div>
<?php if (!empty($answer['ai_feedback'])) : ?> <?php if (!empty($answer['ai_feedback'])) : ?>
<div class="alert alert-info mt-3"><strong><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_RESULT'); ?>:</strong><br><?php echo nl2br(htmlspecialchars((string) $answer['ai_feedback'], ENT_QUOTES, 'UTF-8')); ?></div> <div class="alert alert-info mt-3"><strong><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_RESULT'); ?>:</strong><br><?php echo nl2br(htmlspecialchars((string) $answer['ai_feedback'], ENT_QUOTES, 'UTF-8')); ?></div>
<?php endif; ?> <?php endif; ?>
<?php endif; ?> <?php endif; ?>
<?php if ($question->question_type === 'open') : ?>
<div class="row mt-3"> <div class="row mt-3">
<div class="col-md-3"> <div class="col-md-3">
<label for="awarded-points-<?php echo (int) $questionId; ?>" class="form-label"><?php echo \Joomla\CMS\Language\Text::sprintf('COM_TESTQUESTIONS_RESULT_AWARDED_POINTS', (int) ($question->points ?? 0)); ?></label> <label for="awarded-points-<?php echo (int) $questionId; ?>" class="form-label"><?php echo \Joomla\CMS\Language\Text::sprintf('COM_TESTQUESTIONS_RESULT_AWARDED_POINTS', (int) ($question->points ?? 0)); ?></label>
@@ -59,6 +102,7 @@
</div> </div>
</div> </div>
<?php endif; ?> <?php endif; ?>
<?php endif; ?>
</article> </article>
<?php endforeach; ?> <?php endforeach; ?>
<input type="hidden" name="task" value="result.save"> <input type="hidden" name="task" value="result.save">
+1 -1
View File
@@ -4,7 +4,7 @@
<creationDate>2026-10-14</creationDate> <creationDate>2026-10-14</creationDate>
<author>Komponent</author> <author>Komponent</author>
<license>GNU General Public License version 2 or later</license> <license>GNU General Public License version 2 or later</license>
<version>1.42.9</version> <version>1.43.4</version>
<description>COM_TESTQUESTIONS_DESCRIPTION</description> <description>COM_TESTQUESTIONS_DESCRIPTION</description>
<element>com_testquestions</element> <element>com_testquestions</element>
<namespace path="src">Komponent\Component\Testquestions</namespace> <namespace path="src">Komponent\Component\Testquestions</namespace>