Compare commits

..
5 Commits
Author SHA1 Message Date
Wojtek 37d8c6040c Show remaining API credits in AI settings 2026-10-16 15:12:33 +02:00
Wojtek 7ed00f95e6 Add GPT-6 Luna model option 2026-10-16 13:22:18 +02:00
Wojtek 57065d4ca1 Add AI model selection per provider 2026-10-16 13:16:35 +02:00
Wojtek 7d9efd64f4 Show actual AI token usage and cost 2026-10-16 13:08:59 +02:00
Wojtek 6daca5be59 Configure separate OpenAI and Grok keys 2026-10-16 13:04:34 +02:00
13 changed files with 332 additions and 33 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.43.2). W Joomla wybierz **System → Install → Install from Folder** i wskaż ten katalog. Manifestem instalacyjnym jest `com_testquestions.xml` (wersja 1.43.7).
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,6 +65,23 @@ 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_OPENAI_MODEL="Model OpenAI"
COM_TESTQUESTIONS_AI_GROK_MODEL="Model Grok"
COM_TESTQUESTIONS_AI_MODEL_INVALID="Wybierz prawidłowy model dla każdego dostawcy AI."
COM_TESTQUESTIONS_AI_BALANCE="Saldo kont API"
COM_TESTQUESTIONS_AI_OPENAI_BALANCE_INFO="OpenAI nie udostępnia salda przedpłaconych środków przez zwykłe API. Saldo sprawdzisz w panelu rozliczeń: "
COM_TESTQUESTIONS_AI_OPENAI_BILLING_LINK="Otwórz rozliczenia OpenAI"
COM_TESTQUESTIONS_AI_GROK_TEAM_ID="ID zespołu xAI"
COM_TESTQUESTIONS_AI_GROK_MANAGEMENT_KEY="Klucz zarządzający xAI"
COM_TESTQUESTIONS_AI_GROK_MANAGEMENT_KEY_SAVED="Klucz zarządzający jest zapisany. Pozostaw pole bez zmian, aby go zachować."
COM_TESTQUESTIONS_AI_GROK_MANAGEMENT_KEY_INFO="Wymagany jest osobny Management API key z xAI Console → Settings → Management Keys."
COM_TESTQUESTIONS_AI_CHECK_GROK_BALANCE="Sprawdź saldo xAI"
COM_TESTQUESTIONS_AI_GROK_BALANCE_INFO="Odczyt dotyczy dostępnych kredytów przedpłaconych zespołu xAI. Nie obejmuje limitu rozliczeń postpaid."
COM_TESTQUESTIONS_AI_GROK_BALANCE_CONFIG_REQUIRED="Aby sprawdzić saldo xAI, wpisz ID zespołu i klucz zarządzający, a następnie ponów próbę."
COM_TESTQUESTIONS_AI_GROK_BALANCE_FAILED="Nie udało się odczytać salda xAI. Sprawdź ID zespołu, klucz zarządzający i jego uprawnienia."
COM_TESTQUESTIONS_AI_GROK_BALANCE_RESULT="Dostępne kredyty przedpłacone xAI: $%s USD"
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."
@@ -0,0 +1 @@
-- No database changes required for version 1.43.3.
@@ -0,0 +1 @@
-- No database changes required for version 1.43.4.
@@ -0,0 +1 @@
-- No database changes required for version 1.43.5.
@@ -0,0 +1 @@
-- No database changes required for version 1.43.6.
@@ -0,0 +1 @@
-- No database changes required for version 1.43.7.
@@ -5,14 +5,75 @@ namespace Komponent\Component\Testquestions\Administrator\Controller;
defined('_JEXEC') or die; defined('_JEXEC') or die;
use Joomla\CMS\Factory; use Joomla\CMS\Factory;
use Joomla\CMS\Http\HttpFactory;
use Joomla\CMS\Language\Text; use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\BaseController; use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Router\Route; use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session; use Joomla\CMS\Session\Session;
use Komponent\Component\Testquestions\Administrator\Service\AiService;
class AiController extends BaseController class AiController extends BaseController
{ {
public function save(): void public function save(): void
{
$this->saveSettings();
$this->setRedirect(
Route::_('index.php?option=com_testquestions&view=ai', false),
Text::_('COM_TESTQUESTIONS_AI_SETTINGS_SAVED')
);
}
public function checkbalance(): void
{
$settings = $this->saveSettings();
$teamId = trim((string) ($settings['ai_grok_team_id'] ?? ''));
$managementKey = trim((string) ($settings['ai_grok_management_key'] ?? ''));
if ($teamId === '' || $managementKey === '') {
$this->setRedirect(
Route::_('index.php?option=com_testquestions&view=ai', false),
Text::_('COM_TESTQUESTIONS_AI_GROK_BALANCE_CONFIG_REQUIRED'),
'warning'
);
return;
}
try {
$response = HttpFactory::getHttp()->get(
'https://management-api.x.ai/v1/billing/teams/' . rawurlencode($teamId) . '/prepaid/balance',
['Authorization' => 'Bearer ' . $managementKey, 'Accept' => 'application/json'],
30
);
} catch (\Throwable $error) {
$this->setRedirect(
Route::_('index.php?option=com_testquestions&view=ai', false),
Text::_('COM_TESTQUESTIONS_AI_GROK_BALANCE_FAILED'),
'error'
);
return;
}
$body = json_decode((string) $response->body, true);
if ((int) $response->code < 200 || (int) $response->code >= 300 || !isset($body['total']['val']) || !is_numeric($body['total']['val'])) {
$this->setRedirect(
Route::_('index.php?option=com_testquestions&view=ai', false),
Text::_('COM_TESTQUESTIONS_AI_GROK_BALANCE_FAILED'),
'error'
);
return;
}
$balance = abs((float) $body['total']['val']) / 100;
$message = Text::sprintf('COM_TESTQUESTIONS_AI_GROK_BALANCE_RESULT', number_format($balance, 2, ',', ' '));
$this->setRedirect(
Route::_('index.php?option=com_testquestions&view=ai', false),
$message,
'message'
);
}
private function saveSettings(): array
{ {
if (!Session::checkToken()) { if (!Session::checkToken()) {
throw new \RuntimeException(Text::_('JINVALID_TOKEN'), 403); throw new \RuntimeException(Text::_('JINVALID_TOKEN'), 403);
@@ -29,6 +90,16 @@ class AiController extends BaseController
throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_PROVIDER_INVALID')); throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_PROVIDER_INVALID'));
} }
$models = AiService::availableModels();
$selectedModels = [];
foreach (['openai', 'grok'] as $modelProvider) {
$model = $input->post->getCmd('ai_' . $modelProvider . '_model', '');
if (!isset($models[$modelProvider][$model])) {
throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_MODEL_INVALID'));
}
$selectedModels[$modelProvider] = $model;
}
$db = Factory::getContainer()->get('DatabaseDriver'); $db = Factory::getContainer()->get('DatabaseDriver');
$row = $db->setQuery( $row = $db->setQuery(
$db->getQuery(true) $db->getQuery(true)
@@ -44,26 +115,42 @@ 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;
if ($apiKey !== '') { foreach ($selectedModels as $modelProvider => $model) {
$settings['ai_api_key'] = $apiKey; $settings['ai_' . $modelProvider . '_model'] = $model;
} }
foreach (['openai', 'grok'] as $keyProvider) {
$fieldName = 'ai_' . $keyProvider . '_api_key';
$apiKey = trim((string) $input->post->get($fieldName, '', 'RAW'));
if ($apiKey !== '') {
$settings[$fieldName] = $apiKey;
}
if ($keyProvider === $provider && empty($settings[$fieldName]) && $legacyKey !== '') {
$settings[$fieldName] = $legacyKey;
}
}
$teamId = trim((string) $input->post->get('ai_grok_team_id', '', 'STRING'));
if ($teamId !== '') {
$settings['ai_grok_team_id'] = $teamId;
}
$managementKey = trim((string) $input->post->get('ai_grok_management_key', '', 'RAW'));
if ($managementKey !== '') {
$settings['ai_grok_management_key'] = $managementKey;
}
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),
]; ];
if (!$db->updateObject('#__extensions', $extension, 'extension_id')) { if (!$db->updateObject('#__extensions', $extension, 'extension_id')) {
throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_SAVE_FAILED')); throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_SAVE_FAILED'));
} }
$this->setRedirect( return $settings;
Route::_('index.php?option=com_testquestions&view=ai', false),
Text::_('COM_TESTQUESTIONS_AI_SETTINGS_SAVED')
);
} }
public function cancel(): void public function cancel(): void
@@ -92,8 +92,12 @@ 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);
$defaultModels = ['openai' => 'gpt-4.1-mini', 'grok' => 'grok-4.7'];
$model = trim((string) $params->get('ai_' . $provider . '_model', $defaultModels[$provider] ?? ''));
// 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
// nieaktualnej wartości z pamięci ComponentHelper, a maska pola hasła // nieaktualnej wartości z pamięci ComponentHelper, a maska pola hasła
@@ -115,14 +119,27 @@ class ResultModel extends BaseDatabaseModel
if ($storedProvider !== '') { if ($storedProvider !== '') {
$provider = $storedProvider; $provider = $storedProvider;
} }
}
if ($storedApiKey !== '' && !preg_match('/^\*+$/', $storedApiKey)) { $provider = strtolower(preg_replace('/[^a-z]/', '', $provider));
$apiKey = $storedApiKey; $keyName = 'ai_' . $provider . '_api_key';
} $apiKey = trim((string) $params->get($keyName, $params->get('ai_api_key', '')));
$componentKeyLength = mb_strlen($apiKey);
$model = trim((string) (is_array($storedParams)
? ($storedParams['ai_' . $provider . '_model'] ?? $params->get('ai_' . $provider . '_model', $defaultModels[$provider] ?? ''))
: $params->get('ai_' . $provider . '_model', $defaultModels[$provider] ?? '')));
if ($model === '') {
$model = $defaultModels[$provider] ?? '';
}
$storedApiKey = is_array($storedParams)
? trim((string) ($storedParams[$keyName] ?? $storedParams['ai_api_key'] ?? ''))
: '';
if ($storedApiKey !== '' && !preg_match('/^\*+$/', $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)')
@@ -135,6 +152,7 @@ class ResultModel extends BaseDatabaseModel
$aiResult = (new AiService())->evaluate( $aiResult = (new AiService())->evaluate(
$provider, $provider,
$apiKey, $apiKey,
$model,
strip_tags((string) $question->question), strip_tags((string) $question->question),
(string) ($answer['selected'] ?? ''), (string) ($answer['selected'] ?? ''),
(string) $question->answer_open, (string) $question->answer_open,
@@ -142,6 +160,9 @@ class ResultModel extends BaseDatabaseModel
); );
$item->answers[$questionId]['ai_feedback'] = $aiResult['feedback']; $item->answers[$questionId]['ai_feedback'] = $aiResult['feedback'];
$item->answers[$questionId]['awarded_points'] = $aiResult['awarded_points']; $item->answers[$questionId]['awarded_points'] = $aiResult['awarded_points'];
if ($aiResult['usage'] !== null) {
$item->answers[$questionId]['ai_usage'] = $aiResult['usage'];
}
$correctionPoints = 0; $correctionPoints = 0;
foreach ($item->answers as $savedAnswer) { foreach ($item->answers as $savedAnswer) {
@@ -8,13 +8,31 @@ use Joomla\CMS\Http\HttpFactory;
class AiService class AiService
{ {
public function evaluate(string $provider, string $apiKey, string $question, string $answer, string $pattern, int $maxPoints): array 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 = strtolower(trim($provider));
$provider = preg_replace('/[^a-z]/', '', $provider); $provider = preg_replace('/[^a-z]/', '', $provider);
$config = $provider === 'grok' $config = $provider === 'grok'
? ['url' => 'https://api.x.ai/v1/responses', 'model' => 'grok-4.7'] ? ['url' => 'https://api.x.ai/v1/responses']
: ['url' => 'https://api.openai.com/v1/responses', 'model' => 'gpt-4.1-mini']; : ['url' => 'https://api.openai.com/v1/responses'];
if (trim($apiKey) === '') { if (trim($apiKey) === '') {
throw new \RuntimeException('AI_NOT_CONFIGURED'); throw new \RuntimeException('AI_NOT_CONFIGURED');
@@ -24,6 +42,10 @@ class AiService
throw new \RuntimeException('Nieprawidłowy dostawca AI: ' . $provider); 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" $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" . "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" . "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"
@@ -32,11 +54,15 @@ class AiService
. "Odpowiedź ucznia:\n" . ($answer !== '' ? $answer : 'Brak odpowiedzi') . "\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."; . "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([ $requestData = [
'model' => $config['model'], 'model' => $model,
'input' => $input, 'input' => $input,
'temperature' => 0.1, ];
], JSON_UNESCAPED_UNICODE); // 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( $response = HttpFactory::getHttp()->post(
$config['url'], $config['url'],
@@ -73,9 +99,64 @@ class AiService
throw new \RuntimeException('AI zwróciło nieprawidłowy format oceny i punktów.'); 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 [ return [
'awarded_points' => min(max(0, $maxPoints), max(0, (int) $result['awarded_points'])), 'awarded_points' => min(max(0, $maxPoints), max(0, (int) $result['awarded_points'])),
'feedback' => trim((string) ($result['feedback'] ?? '')), '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],
]; ];
} }
@@ -1,8 +1,13 @@
<?php defined('_JEXEC') or die; ?> <?php defined('_JEXEC') or die; ?>
<?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 $availableModels = \Komponent\Component\Testquestions\Administrator\Service\AiService::availableModels(); ?>
<?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 : '')); ?>
<?php $openaiModel = (string) ($this->settings['ai_openai_model'] ?? 'gpt-4.1-mini'); ?>
<?php $grokModel = (string) ($this->settings['ai_grok_model'] ?? 'grok-4.7'); ?>
<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,15 +19,66 @@
</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-model" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_OPENAI_MODEL'); ?></label>
<select id="ai-openai-model" name="ai_openai_model" class="form-select" required>
<?php foreach ($availableModels['openai'] as $modelId => $modelLabel) : ?>
<option value="<?php echo htmlspecialchars($modelId, ENT_QUOTES, 'UTF-8'); ?>" <?php echo $openaiModel === $modelId ? 'selected' : ''; ?>><?php echo htmlspecialchars($modelLabel, ENT_QUOTES, 'UTF-8'); ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="mb-3">
<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> </small>
</div> </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>
</div>
<div class="mb-3">
<label for="ai-grok-model" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROK_MODEL'); ?></label>
<select id="ai-grok-model" name="ai_grok_model" class="form-select" required>
<?php foreach ($availableModels['grok'] as $modelId => $modelLabel) : ?>
<option value="<?php echo htmlspecialchars($modelId, ENT_QUOTES, 'UTF-8'); ?>" <?php echo $grokModel === $modelId ? 'selected' : ''; ?>><?php echo htmlspecialchars($modelLabel, ENT_QUOTES, 'UTF-8'); ?></option>
<?php endforeach; ?>
</select>
</div>
<hr>
<h3><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_BALANCE'); ?></h3>
<div class="alert alert-info">
<?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_OPENAI_BALANCE_INFO'); ?>
<a href="https://platform.openai.com/settings/organization/billing/overview" target="_blank" rel="noopener noreferrer"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_OPENAI_BILLING_LINK'); ?></a>
</div>
<div class="mb-3">
<label for="ai-grok-team-id" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROK_TEAM_ID'); ?></label>
<input type="text" id="ai-grok-team-id" name="ai_grok_team_id" class="form-control" maxlength="255" value="<?php echo htmlspecialchars((string) ($this->settings['ai_grok_team_id'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>">
</div>
<div class="mb-3">
<label for="ai-grok-management-key" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROK_MANAGEMENT_KEY'); ?></label>
<div class="input-group">
<input type="password" id="ai-grok-management-key" name="ai_grok_management_key" value="<?php echo htmlspecialchars((string) ($this->settings['ai_grok_management_key'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>" class="form-control" maxlength="4096" autocomplete="new-password">
<button type="button" class="btn btn-outline-secondary" data-ai-key-toggle="ai-grok-management-key">Pokaż</button>
</div>
<small class="form-text text-muted">
<?php echo !empty($this->settings['ai_grok_management_key']) ? \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROK_MANAGEMENT_KEY_SAVED') : \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROK_MANAGEMENT_KEY_INFO'); ?>
</small>
</div>
<button type="submit" class="btn btn-outline-primary" onclick="this.form.task.value='ai.checkbalance';">
<?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_CHECK_GROK_BALANCE'); ?>
</button>
<div class="form-text mt-2"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROK_BALANCE_INFO'); ?></div>
<hr>
<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';">
<?php echo \Joomla\CMS\Language\Text::_('JTOOLBAR_SAVE'); ?> <?php echo \Joomla\CMS\Language\Text::_('JTOOLBAR_SAVE'); ?>
</button> </button>
@@ -35,10 +91,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 visible = input.type === 'text'; const input = document.getElementById(this.dataset.aiKeyToggle);
input.type = visible ? 'password' : 'text'; const visible = input.type === 'text';
this.textContent = visible ? 'Pokaż' : 'Ukryj'; input.type = visible ? 'password' : 'text';
this.textContent = visible ? 'Pokaż' : 'Ukryj';
});
}); });
</script> </script>
@@ -35,6 +35,25 @@
<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';"> <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); ?> <?php echo \Joomla\CMS\Language\Text::sprintf('COM_TESTQUESTIONS_AI_EVALUATE_ALL', $pendingAiCount); ?>
</button> </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> </div>
<?php endif; ?> <?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>
@@ -55,6 +74,17 @@
<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>
+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.43.2</version> <version>1.43.7</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>