Compare commits

...
1 Commits
Author SHA1 Message Date
Wojtek 8045698072 Add Groq API as an AI provider 2026-10-16 22:00:28 +02:00
13 changed files with 99 additions and 33 deletions
+1 -1
View File
@@ -30,6 +30,6 @@ Szkielet komponentu Joomla 6 do gromadzenia pytań testowych.
## Instalacja
W Joomla wybierz **System → Install → Install from Folder** i wskaż ten katalog. Manifestem instalacyjnym jest `com_testquestions.xml` (wersja 1.43.26).
W Joomla wybierz **System → Install → Install from Folder** i wskaż ten katalog. Manifestem instalacyjnym jest `com_testquestions.xml` (wersja 1.43.27).
Po instalacji komponent jest dostępny w panelu administratora jako **Pytania testowe**.
@@ -5,6 +5,7 @@
<field name="ai_provider" type="list" label="COM_TESTQUESTIONS_AI_PROVIDER">
<option value="openai">OpenAI</option>
<option value="grok">Grok</option>
<option value="groq">Groq</option>
</field>
<field name="ai_api_key" type="aiapikey" addfieldprefix="Komponent\Component\Testquestions\Administrator\Field" label="COM_TESTQUESTIONS_AI_API_KEY" filter="raw" autocomplete="off" size="120" class="w-100" />
</fieldset>
@@ -71,8 +71,10 @@ COM_TESTQUESTIONS_AI_PROVIDER="Dostawca AI"
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_GROQ_KEY="Klucz API Groq"
COM_TESTQUESTIONS_AI_OPENAI_MODEL="Model OpenAI"
COM_TESTQUESTIONS_AI_GROK_MODEL="Model Grok"
COM_TESTQUESTIONS_AI_GROQ_MODEL="Model Groq API"
COM_TESTQUESTIONS_AI_MODEL_INVALID="Wybierz prawidłowy model dla każdego dostawcy AI."
COM_TESTQUESTIONS_AI_TOKEN_USAGE="Wykorzystanie tokenów API"
COM_TESTQUESTIONS_AI_TOKEN_USAGE_INFO="Suma użycia zapisanego przy ocenach AI we wszystkich wynikach testów. Powtórne oceny są zliczane, jeśli zostały wykonane po tej aktualizacji."
@@ -0,0 +1 @@
-- Wydanie 1.43.27: dodano dostawcę Groq API.
@@ -36,14 +36,14 @@ class AiController extends BaseController
$input = Factory::getApplication()->getInput();
$provider = strtolower($input->post->getCmd('ai_provider', ''));
if (!in_array($provider, ['openai', 'grok'], true)) {
if (!in_array($provider, ['openai', 'grok', 'groq'], true)) {
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', '');
foreach (['openai', 'grok', 'groq'] as $modelProvider) {
$model = trim($input->post->getString('ai_' . $modelProvider . '_model', ''));
if (!isset($models[$modelProvider][$model])) {
throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_MODEL_INVALID'));
}
@@ -71,7 +71,7 @@ class AiController extends BaseController
$settings['ai_' . $modelProvider . '_model'] = $model;
}
foreach (['openai', 'grok'] as $keyProvider) {
foreach (['openai', 'grok', 'groq'] as $keyProvider) {
$fieldName = 'ai_' . $keyProvider . '_api_key';
$apiKey = trim((string) $input->post->get($fieldName, '', 'RAW'));
if ($apiKey !== '') {
@@ -96,7 +96,7 @@ class ResultModel extends BaseDatabaseModel
$keyName = 'ai_' . $provider . '_api_key';
$apiKey = trim((string) $params->get($keyName, $params->get('ai_api_key', '')));
$componentKeyLength = mb_strlen($apiKey);
$defaultModels = ['openai' => 'gpt-4.1-mini', 'grok' => 'grok-4.7'];
$defaultModels = ['openai' => 'gpt-4.1-mini', 'grok' => 'grok-4.7', 'groq' => 'openai/gpt-oss-120b'];
$model = trim((string) $params->get('ai_' . $provider . '_model', $defaultModels[$provider] ?? ''));
// Odczytaj zapisane parametry bezpośrednio z bazy. Dzięki temu nie użyjemy
@@ -18,7 +18,7 @@ class ResultsModel extends ListModel
$item->ai_output_tokens = 0;
$item->ai_total_tokens = 0;
$item->ai_cost_usd = 0.0;
$item->ai_tokens_by_provider = ['openai' => 0, 'grok' => 0];
$item->ai_tokens_by_provider = ['openai' => 0, 'grok' => 0, 'groq' => 0];
$answers = json_decode((string) ($item->answers ?? ''), true);
if (!is_array($answers)) {
@@ -68,7 +68,7 @@ class ResultsModel extends ListModel
'output_tokens' => 0,
'total_tokens' => 0,
'cost_usd' => 0.0,
'providers' => ['openai' => $emptyProviderTotals, 'grok' => $emptyProviderTotals],
'providers' => ['openai' => $emptyProviderTotals, 'grok' => $emptyProviderTotals, 'groq' => $emptyProviderTotals],
];
foreach ($answersRows as $answersJson) {
@@ -23,6 +23,11 @@ class AiService
'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',
],
];
}
@@ -30,15 +35,17 @@ class AiService
{
$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'];
$config = match ($provider) {
'grok' => ['url' => 'https://api.x.ai/v1/responses'],
'groq' => ['url' => 'https://api.groq.com/openai/v1/chat/completions'],
default => ['url' => 'https://api.openai.com/v1/responses'],
};
if (trim($apiKey) === '') {
throw new \RuntimeException('AI_NOT_CONFIGURED');
}
if (!in_array($provider, ['openai', 'grok'], true)) {
if (!in_array($provider, ['openai', 'grok', 'groq'], true)) {
throw new \RuntimeException('Nieprawidłowy dostawca AI: ' . $provider);
}
@@ -54,12 +61,18 @@ class AiService
. "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,
];
$requestData = $provider === 'groq'
? [
'model' => $model,
'messages' => [['role' => 'user', 'content' => $input]],
'temperature' => 0.1,
]
: [
'model' => $model,
'input' => $input,
];
// GPT-5.x reasoning models do not accept a custom temperature.
if ($provider === 'grok' || $model === 'gpt-4.1-mini') {
if ($provider === 'grok' || ($provider === 'openai' && $model === 'gpt-4.1-mini')) {
$requestData['temperature'] = 0.1;
}
$payload = json_encode($requestData, JSON_UNESCAPED_UNICODE);
@@ -115,12 +128,16 @@ class AiService
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'])) {
if (!is_array($usage)) {
return null;
}
$inputTokens = max(0, (int) $usage['input_tokens']);
$outputTokens = max(0, (int) $usage['output_tokens']);
$inputTokens = max(0, (int) ($usage['input_tokens'] ?? $usage['prompt_tokens'] ?? 0));
$outputTokens = max(0, (int) ($usage['output_tokens'] ?? $usage['completion_tokens'] ?? 0));
if ((!isset($usage['input_tokens']) && !isset($usage['prompt_tokens']))
|| (!isset($usage['output_tokens']) && !isset($usage['completion_tokens']))) {
return null;
}
$cachedTokens = min($inputTokens, max(0, (int) ($usage['input_tokens_details']['cached_tokens'] ?? 0)));
$cost = null;
$costSource = '';
@@ -162,6 +179,10 @@ class AiService
private function extractText(array $body): string
{
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']);
}
@@ -28,6 +28,7 @@ class HtmlView extends BaseHtmlView
$this->usageTotals = [
'openai' => ['calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'cost_calls' => 0],
'grok' => ['calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'cost_calls' => 0],
'groq' => ['calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'cost_calls' => 0],
];
$usageRows = $db->setQuery(
@@ -7,8 +7,10 @@
<?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 $groqKey = (string) ($this->settings['ai_groq_api_key'] ?? ($provider === 'groq' ? $legacyKey : '')); ?>
<?php $openaiModel = (string) ($this->settings['ai_openai_model'] ?? 'gpt-4.1-mini'); ?>
<?php $grokModel = (string) ($this->settings['ai_grok_model'] ?? 'grok-4.7'); ?>
<?php $groqModel = (string) ($this->settings['ai_groq_model'] ?? 'openai/gpt-oss-120b'); ?>
<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-body">
@@ -17,9 +19,10 @@
<select id="ai-provider" name="ai_provider" class="form-select" required>
<option value="openai" <?php echo $provider === 'openai' ? 'selected' : ''; ?>>OpenAI</option>
<option value="grok" <?php echo $provider === 'grok' ? 'selected' : ''; ?>>Grok</option>
<option value="groq" <?php echo $provider === 'groq' ? 'selected' : ''; ?>>Groq</option>
</select>
</div>
<div class="mb-3">
<div class="mb-3" data-ai-provider-section="openai">
<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) : ?>
@@ -27,7 +30,7 @@
<?php endforeach; ?>
</select>
</div>
<div class="mb-3">
<div class="mb-3" data-ai-provider-section="openai">
<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">
<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">
@@ -37,7 +40,7 @@
<?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">
<div class="mb-3" data-ai-provider-section="grok">
<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">
@@ -47,7 +50,7 @@
<?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">
<div class="mb-3" data-ai-provider-section="grok">
<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) : ?>
@@ -55,6 +58,24 @@
<?php endforeach; ?>
</select>
</div>
<div class="mb-3" data-ai-provider-section="groq">
<label for="ai-groq-api-key" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROQ_KEY'); ?></label>
<div class="input-group">
<input type="password" id="ai-groq-api-key" name="ai_groq_api_key" value="<?php echo htmlspecialchars($groqKey, 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-groq-api-key">Pokaż</button>
</div>
<small class="form-text text-muted">
<?php echo $groqKey !== '' ? 'Zapisany klucz: ' . mb_strlen($groqKey) . ' znaków. Pozostaw pole bez zmian, aby go zachować.' : 'Nie zapisano klucza Groq.'; ?>
</small>
</div>
<div class="mb-3" data-ai-provider-section="groq">
<label for="ai-groq-model" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROQ_MODEL'); ?></label>
<select id="ai-groq-model" name="ai_groq_model" class="form-select" required>
<?php foreach ($availableModels['groq'] as $modelId => $modelLabel) : ?>
<option value="<?php echo htmlspecialchars($modelId, ENT_QUOTES, 'UTF-8'); ?>" <?php echo $groqModel === $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_TOKEN_USAGE'); ?></h3>
<p class="text-muted"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_TOKEN_USAGE_INFO'); ?></p>
@@ -71,7 +92,7 @@
</tr>
</thead>
<tbody>
<?php foreach (['openai' => 'OpenAI', 'grok' => 'Grok'] as $usageProvider => $usageProviderLabel) : ?>
<?php foreach (['openai' => 'OpenAI', 'grok' => 'Grok', 'groq' => 'Groq'] as $usageProvider => $usageProviderLabel) : ?>
<?php $providerUsage = $usageTotals[$usageProvider]; ?>
<tr>
<th><?php echo $usageProviderLabel; ?></th>
@@ -106,4 +127,12 @@ document.querySelectorAll('[data-ai-key-toggle]').forEach(function (button) {
this.textContent = visible ? 'Pokaż' : 'Ukryj';
});
});
const providerSelect = document.getElementById('ai-provider');
const updateProviderFields = function () {
document.querySelectorAll('[data-ai-provider-section]').forEach(function (section) {
section.hidden = section.dataset.aiProviderSection !== providerSelect.value;
});
};
providerSelect.addEventListener('change', updateProviderFields);
updateProviderFields();
</script>
@@ -49,22 +49,26 @@ $resolveImageUrl = static function ($path) {
<?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' => []];
$usageTotals = ['input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'cost_calls' => 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 (is_numeric($usage['cost_usd'] ?? null)) {
$usageTotals['cost_usd'] += (float) $usage['cost_usd'];
$usageTotals['cost_calls']++;
}
if (!empty($usage['provider'])) $usageTotals['providers'][(string) $usage['provider']] = true;
}
?>
<?php if ($usageTotals['total_tokens'] > 0) : ?>
<?php $usageProviderLabels = array_map(static function ($usageProvider) { return ['openai' => 'OpenAI', 'grok' => 'Grok', 'groq' => 'Groq'][$usageProvider] ?? $usageProvider; }, array_keys($usageTotals['providers'])); ?>
<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 implode(' + ', array_map('htmlspecialchars', $usageProviderLabels)); ?>:
<?php echo number_format($usageTotals['total_tokens'], 0, ',', ' '); ?> tokenów,
<?php echo number_format($usageTotals['cost_usd'], 8, ',', ' '); ?> USD
<?php echo $usageTotals['cost_calls'] > 0 ? number_format($usageTotals['cost_usd'], 8, ',', ' ') . ' USD' : 'koszt niedostępny'; ?>
</span>
<?php endif; ?>
</div>
@@ -92,8 +96,8 @@ $resolveImageUrl = static function ($path) {
<?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'; ?> ·
<span class="badge text-bg-light border ms-2" title="<?php echo $usageProvider === 'grok' ? 'Koszt zwrócony przez dostawcę' : ($usageProvider === 'groq' ? 'Groq zwrócił wykorzystane tokeny; koszt nie jest zwracany przez to API' : 'Koszt obliczony z faktycznie wykorzystanych tokenów i stawek modelu'); ?>">
<?php echo $usageProvider === 'grok' ? '✦ Grok' : ($usageProvider === 'groq' ? '⚡ Groq' : '◉ 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'; ?>
@@ -50,6 +50,12 @@ HTMLHelper::_('behavior.multiselect');
<?php echo number_format((int) $this->aiUsageTotals['providers']['grok']['output_tokens'], 0, ',', ' '); ?> wyj.)
<?php if ($this->aiUsageTotals['providers']['grok']['cost_usd'] > 0) : ?> · <?php echo number_format((float) $this->aiUsageTotals['providers']['grok']['cost_usd'], 8, ',', ' '); ?> USD<?php endif; ?>
</span>
<span class="d-block">
<strong>Groq:</strong>
<?php echo number_format((int) $this->aiUsageTotals['providers']['groq']['total_tokens'], 0, ',', ' '); ?> tokenów
(<?php echo number_format((int) $this->aiUsageTotals['providers']['groq']['input_tokens'], 0, ',', ' '); ?> wej. /
<?php echo number_format((int) $this->aiUsageTotals['providers']['groq']['output_tokens'], 0, ',', ' '); ?> wyj.)
</span>
<span class="d-block"><strong>Łącznie:</strong> <?php echo number_format((int) $this->aiUsageTotals['total_tokens'], 0, ',', ' '); ?> tokenów</span>
</div>
<table class="table table-striped">
@@ -84,7 +90,8 @@ HTMLHelper::_('behavior.multiselect');
<?php if ($item->ai_total_tokens > 0) : ?>
<small class="d-block text-muted">
OpenAI: <?php echo number_format((int) $item->ai_tokens_by_provider['openai'], 0, ',', ' '); ?> ·
Grok: <?php echo number_format((int) $item->ai_tokens_by_provider['grok'], 0, ',', ' '); ?>
Grok: <?php echo number_format((int) $item->ai_tokens_by_provider['grok'], 0, ',', ' '); ?> ·
Groq: <?php echo number_format((int) $item->ai_tokens_by_provider['groq'], 0, ',', ' '); ?>
</small>
<small class="d-block text-muted">
<?php echo number_format((int) $item->ai_total_tokens, 0, ',', ' '); ?> łącznie
+1 -1
View File
@@ -4,7 +4,7 @@
<creationDate>2026-10-14</creationDate>
<author>Komponent</author>
<license>GNU General Public License version 2 or later</license>
<version>1.43.26</version>
<version>1.43.27</version>
<description>COM_TESTQUESTIONS_DESCRIPTION</description>
<element>com_testquestions</element>
<namespace path="src">Komponent\Component\Testquestions</namespace>