Calling ChatGPT from Joomla is ten lines of code. Calling it so that the site stays fast, the key stays secret, a provider outage doesn't break pages, and the bill doesn't surprise anyone takes some structure. This is the structure we use in Joomla extensions that talk to LLM APIs, from a one-off field generator to scheduled batch jobs.
Rule 1: never in the page request if you can avoid it
An LLM call takes one to thirty seconds and fails now and then. Put that in onContentPrepare or a module, and every visitor waits for it, and every outage becomes your outage. Where the call lives decides most of the design:
| Need | Where the call goes |
|---|---|
| Batch work: summaries, tags, descriptions, translations | a Scheduler task plugin or a console command |
| An editor clicks "suggest" in the back end | an AJAX request (com_ajax plugin) with a spinner; never on save |
| Visitor-facing answers (chat, search) | a separate endpoint with rate limiting and a cache, called from the browser |
Rule 2: one small client class, provider-agnostic
Most providers offer an OpenAI-compatible /chat/completions endpoint, so one class covers OpenAI, Azure OpenAI, Mistral, local models via Ollama or vLLM, and others. Keep the base URL and model configurable:
// administrator/components/com_example/src/Service/LlmClient.php
namespace Example\Component\Example\Administrator\Service;
use Joomla\CMS\Http\HttpFactory;
final class LlmClient
{
public function __construct(
private string $baseUrl, // https://api.openai.com/v1
private string $apiKey,
private string $model,
private int $timeout = 60,
) {}
public function complete(string $system, string $user, int $maxTokens = 500): string
{
$response = HttpFactory::getHttp()->post(
rtrim($this->baseUrl, '/') . '/chat/completions',
json_encode([
'model' => $this->model,
'max_tokens' => $maxTokens,
'messages' => [
['role' => 'system', 'content' => $system],
['role' => 'user', 'content' => $user],
],
], JSON_THROW_ON_ERROR),
['Authorization' => 'Bearer ' . $this->apiKey, 'Content-Type' => 'application/json'],
$this->timeout
);
$status = $response->getStatusCode();
if ($status === 429 || $status >= 500) {
throw new LlmRetryableException("LLM API $status"); // rate limit or provider outage: try again later
}
if ($status !== 200) {
throw new \RuntimeException("LLM API $status: " . substr((string) $response->getBody(), 0, 300));
}
$data = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
return trim($data['choices'][0]['message']['content'] ?? '');
}
}
Joomla's HttpFactory picks an available transport (cURL or streams) and returns a PSR-7 response, so this works on any host without extra Composer packages. Anthropic's API has a different shape (/v1/messages, an x-api-key header, content[0].text in the response). Give it its own small class behind the same method, and nothing else in the extension changes.
Rule 3: the API key is not a plugin parameter
Plugin and component parameters are stored as plain JSON in #__extensions.params, so they show up in every database backup and every staging copy. A type="password" field only hides it in the form. Better options, in order:
- An environment variable of the PHP-FPM pool or the cron user (
getenv('OPENAI_API_KEY')). - A file outside the web root that only the PHP user can read.
- If it must be in the back end: a parameter, plus a documented decision that the database is now a secret too.
Whatever you choose, give each site its own key with a spending limit set at the provider. A leaked key with a limit is an incident. One without is a bill.
Rule 4: batch work belongs in a task plugin
Joomla's Scheduler (System → Scheduled Tasks) runs task plugins on a schedule, logs each run, and lets an admin see failures. That's the right home for "summarise new articles every hour":
// plugins/task/aisummary/src/Extension/AiSummary.php
final class AiSummary extends CMSPlugin implements SubscriberInterface
{
use DatabaseAwareTrait;
use TaskPluginTrait;
private const TASKS_MAP = [
'aisummary.articles' => [
'langConstPrefix' => 'PLG_TASK_AISUMMARY_ARTICLES',
'method' => 'summarise',
'form' => 'summariseForm',
],
];
protected $autoloadLanguage = true;
public static function getSubscribedEvents(): array
{
return [
'onTaskOptionsList' => 'advertiseRoutines',
'onExecuteTask' => 'standardRoutineHandler',
'onContentPrepareForm' => 'enhanceTaskItemForm',
];
}
private function summarise(ExecuteTaskEvent $event): int
{
$params = $event->getArgument('params');
$llm = new LlmClient($params->base_url, (string) getenv('OPENAI_API_KEY'), $params->model);
$db = $this->getDatabase();
$query = $db->createQuery()
->select($db->quoteName(['id', 'title', 'introtext']))
->from($db->quoteName('#__content'))
->where($db->quoteName('state') . ' = 1')
->where($db->quoteName('note') . " = ''") // not summarised yet
->setLimit((int) ($params->batch ?? 10)); // small batches: bounded time and cost
foreach ($db->setQuery($query)->loadObjectList() as $article) {
try {
$summary = $llm->complete(
'You summarise web articles in one plain sentence for an internal editor note.',
$article->title . "\n\n" . mb_substr(strip_tags($article->introtext), 0, 4000),
120
);
} catch (LlmRetryableException $e) {
$this->logTask($e->getMessage() . ' – stopping, next run continues', 'warning');
return Status::WILL_RESUME;
}
// … save $summary for $article->id with a prepared UPDATE
$this->logTask("Summarised #{$article->id}");
}
return Status::OK;
}
}
Two habits from production: small batches (a run that takes 20 minutes holds the Scheduler's lock and gets killed by PHP's time limit), and stop on rate limits instead of retrying in a loop. The next run continues where this one stopped, because the query only picks unprocessed rows.
Rule 5: cache what you can, store what you paid for
- Store results in the database, not just in the page cache. You paid for every token, and you shouldn't pay again because someone cleared the cache.
- Cache identical requests with Joomla's callback cache, keyed by a hash of model + prompt + input, when the same question repeats (FAQ answers, translations of a fixed string).
- Log usage: the response's
usageblock has token counts. A daily sum in the task log catches a runaway job before the invoice does.
Rule 6: personal data needs a decision, not a default
Sending user-generated content, form submissions or member data to an external API is a data transfer. Decide what may leave the site, strip personal data before the call where you can, check the provider's data-processing terms, and document it in the privacy policy. For anything sensitive, a self-hosted model behind the same OpenAI-compatible interface is a real option. Only the base URL changes.
Rule 7: output is untrusted input
Model output goes into your site like user input: escape it for HTML (htmlspecialchars, or InputFilter if you allow some HTML), validate lengths and formats, and never execute it or use it in SQL without binding. If the input came from visitors, the output may carry their instructions too.
For a complete, small example of this structure, see generating meta descriptions with a console command.
