AI Hub

BYOK (bring your own key) broker for Moodle — full documentation.

English | Português

View on GitHub Download .zip

Moodle License Status Latest Release PlayerGames Ecosystem Role Author

Moodle Plugin CI MDL Shield Last Commit Open Issues

AI Hub is a small BYOK (bring your own key) broker for Moodle. It lets the institution’s own plugins generate text through shared AI API keys, without each plugin reimplementing the HTTP transport, the SSRF guard, the provider ladder or a key store.

👈 Use the sidebar to jump to any section on this page.


✨ Features

🧩 How consumers use it

A sibling plugin consumes the hub through a runtime guard and keeps its own core_ai fallback:

// Availability: hub keys first, then the consumer's own core_ai fallback.
public static function has_ai(): bool {
    if (class_exists(\local_aihub\ai::class) && \local_aihub\ai::is_available()) {
        return true;                       // BYOK via the hub
    }
    return self::has_core_ai();            // works without the hub
}

// Generation.
$result = \local_aihub\ai::generate_text(
    '',                    // system prompt (optional)
    $prompt,               // user prompt
    false,                 // JSON mode
    'your_frankenstyle',   // 4th arg: caller component, for the usage log
    'Short label'          // 5th arg: what is being generated, shown in the admin report
);
if ($result['success']) {
    // $result['data'] is RAW, untrusted text — validate and format_text() it.
}

The returned text is raw and untrusted: validate its structure and pass it through format_text() before displaying or persisting it.

Two notes on the return value. The generated text is under data, and the reason for a failure under message — reading the array as an object returns null without erroring, which turns every success into a silent fallback. And one call can log several rows: the hub records each provider it tried, under the component and label you passed, so a request that fell through to a second provider appears twice in the report, once failed and once succeeded.

🔗 Key resolution (BYOK ladder)

The hub tries the keys group by group: first the user’s personal keys, then the site’s. If no provider in the first group answers, the next group is tried.

Tier Source
1 Personal key — the user’s own key, when personal keys are enabled and the user has local/aihub:usepersonalkey
2 Site key — the admin key set in the hub settings

Within each group, providers are tried in this order:

  1. the user’s own order, dragged on My AI keys (if any);
  2. the site’s order, dragged by the administrator on the Provider order page (if any);
  3. whatever is still missing, in the built-in order Gemini → Groq → DeepSeek → OpenAI-compatible.

A provider without a key is skipped. The order arranges the providers inside a group; it never puts the site keys ahead of the user’s personal ones. With nothing chosen the order is the built-in one. When no group holds a key, generate_text() returns success = false — the hub never falls back to core_ai; that decision belongs to the consumer.

Providers that failed recently

Each request starts from scratch, so a provider that times out would otherwise cost its full timeout on every request. The hub therefore remembers, for a few minutes (setting Minutes to remember a failing provider, 5 by default, 0 turns it off), that a provider failed, and tries it last the next time.

Failure Remembered?
No answer (timeout, connection), HTTP 5xx, HTTP 429 (quota) Yes
HTTP 401, 403, 404 (key or endpoint refused) Yes, until the settings or the user’s keys change
HTTP 400, 413, 422 and other 4xx; an answer with no text No — they depend on the request, not on the provider

📦 Requirements

Component Version
Moodle 4.5+
PHP 8.1+

No bundled third-party libraries. The AI providers are external services, declared in the Privacy provider — not in thirdpartylibs.xml.

🛠️ Installation & Configuration

  1. Download the .zip file or clone this repository.
  2. Extract the folder into your Moodle local/ directory.
  3. Rename the folder to aihub (if necessary). Final path: your-moodle/local/aihub/
  4. Visit Site administration → Notifications to complete installation.

Configuring a provider key is optional — the plugin installs and works without one. See Usage below for setting site keys and enabling personal keys.

📖 Usage

  1. Configure site keys (admin): Site administration → Plugins → Local plugins → AI Hub → Settings. Set any of the Gemini, Groq, DeepSeek or OpenAI-compatible keys, and (optionally) enable personal API keys.
  2. Add a personal key (user): users who have the local/aihub:usepersonalkey capability get a My AI keys entry in their preferences, where they store their own key (write-only) and see their recent usage.
  3. Review site-key usage (admin): the AI usage report (under the AI Hub category, capability local/aihub:viewusage) lists every provider call served by the site keys across all users, with CSV and Excel download. Each attempt gets its own row, carrying the outcome and the reason when it failed, and filters for failures only or successes only answer whether a provider has stopped responding, or narrow the list back to what was actually generated.
  4. Consume from a plugin (developer): call \local_aihub\ai::generate_text() behind a class_exists() guard, keeping your own core_ai fallback (see How consumers use it).

🧪 Automated Tests

The hub ships with a PHPUnit and Behat suite; every CI push runs against the matrix (Moodle 4.5 → 5.x, PostgreSQL & MariaDB).

PHPUnit — Unit & Integration Tests

Test file Cases What is covered
tests/local/keys_test.php 23 OpenAI base-URL/model defaults, including the fallback reached only when an admin blanks the setting; personal-key get/save/clear roundtrip; personal OpenAI-compatible URL/model roundtrip; personal_keys_allowed honouring the toggle and the capability; key resolution personal → site; has_any_key across personal and site keys; the provider order (the user’s own order, then the site’s, then what is missing in the built-in order, with no repeated or made-up provider, any provider placeable anywhere) and the saved orders accepting only the four providers
tests/local/client_test.php 54 is_safe_url SSRF cases (http, loopback, private range, missing host, public IP); DNS-rebinding branch stubbed via dns_stub_client; resolve_openai_url appends /chat/completions; personal tier wins over site; provider fall-through within a tier (Gemini → Groq → DeepSeek); attempts are reported back, including a failure covered by a later success and attempts spanning both tiers; the request each provider assembles — Gemini’s own system-instruction and JSON-mode fields versus the chat-completions shape, per-provider endpoint and model; the OpenAI leg resolving personal-then-site URL and model field by field; response parsing per provider, error unwrapping, transport failure, and an unexpected body; the failure memory — a provider that failed is tried last on the next request and the one that answers is the only one asked, every provider is still asked when all of them failed, the window ending, a failure that depends on the request not being remembered, an answer clearing the mark, personal and site keys remembered apart, the site’s order and each user’s own order deciding who is asked first, and the whole order being followed when the first providers fail, without ever putting the site keys ahead of the personal ones, and which HTTP statuses count as the provider’s own failure; a personal key that cannot be decrypted is skipped for the site key
tests/local/health_test.php 10 The failure memory: a failure counting only inside its window, the window read from the setting within zero and an hour, zero turning it off, failures kept apart by group of keys, user and provider, failing providers moved to the end without removing any, and clearing one failure, the site’s or one user’s
tests/local/usage_log_test.php 11 Record insert (with keysource, empty model nulled); a failed attempt keeping its reason; the outcome filter narrowing both readers in either direction; site-scoped readers excluding personal/untagged rows; the export reader returning every row past the screen’s cap; display_name naming a person, the system or an unresolved id
tests/local/export_test.php 5 Personal usage export (all rows, every column); a failed attempt exporting its outcome and reason; site-keys report export including the user column and excluding personal usage
tests/ai_test.php 6 is_available states; a successful generation logs the calling component, the description and the key tier; no provider called logs nothing; every attempt is logged, so a failure covered by a later success leaves two rows; report_usage() writing a row for a consumer that resolved its own key, success or failure
tests/db_upgrade_test.php 7 The upgrade step adds the column with the type, length and nullability install.xml declares; existing rows keep their data and read as successes; a second run is a no-op; the 2026112900 step encrypts the stored keys, repeats as a no-op, and writes nothing from a command line without an encryption key; the frozen copy of the key sealing step does its work, repeats as a no-op, leaves the endpoint, model, provider order and other plugins alone, and writes nothing from a command line without an encryption key
tests/lib_test.php 7 The navigation entry is added on the user’s own preferences page, and not on someone else’s, not without the capability, and not when personal keys are disabled site-wide; the security checks callback returns the key check
tests/privacy_provider_test.php 12 Metadata declaration; context/user discovery; export_user_data (log rows + redacted key value); the saved provider order declared and exported with its value; the readers refusing a non-user context and a user with no rows; per-user deletion, whole-context deletion and approved-user-list deletion, each with isolation
tests/output/mykeys_test.php 10 The provider order list showing the effective order and sending only the saved one, with the way back to automatic offered only to someone who chose an order; per-provider personal-key status (set/unset) with no key value ever placed in the template context; usage rows carrying the right provider icon, including the fallback for an unrecognised provider; a failed attempt showing its reason; the page rendering end to end with no stored key in the markup; each provider shows one of three states, a key that cannot be read can still be removed, no stored value reaches the page, and the notice about where the keys go is shown; a saved key that cannot be used shows the warning and can be removed
tests/output/provider_order_test.php 4 The sortable list: items in the order shown with a name for each drag handle, the hidden field carrying only the saved order, providers without a site key marked only when asked, and the list named by a heading
tests/output/report_test.php 9 Site-keys report rows carry the requesting user’s name and correct provider icon, excluding personal-key rows; empty state; failed rows carrying their reason; each of the three filters narrowing to its own outcome, with exactly one reading as active and an unrecognised one falling back to the full list; the per-filter empty wording; a request with no user attributed to the system; a row written before the failure columns existed still reading as a success; the page rendering end to end
tests/settings_test.php 6 Where the plugin’s pages land for a report viewer and a site admin; the provider order page (administrators only) and its link on the settings page; the failure-memory setting, with its default; changing a site key, the endpoint or the model forgetting the site’s failures, and saving the same value again not doing so
tests/admin/setting_endpoint_test.php 4 An endpoint a request would refuse is not saved; a public HTTPS endpoint is; a value that is not a web address is not saved; the default is saved without a DNS lookup
tests/uninstall_test.php 2 Uninstalling deletes only the plugin’s own prefixed user preferences, and is a no-op when there are none
tests/task/purge_old_logs_test.php 3 Rows older than the configured retention are deleted, newer rows are kept; a retention of 0 keeps every row indefinitely; the task names itself from a language string
tests/local/secret_test.php 9 The stored format: round trip, empty value, idempotent and randomised sealing, plain text passed through, damaged or foreign-key values unreadable, and on a command line without an encryption key nothing is encrypted and no key file is created, even when opening
tests/local/keys_encryption_test.php 21 Keys stored sealed and read back; a plain personal or site key read and sealed in place, or left alone on a command line without an encryption key; an unreadable key counts as none and is never deleted; the storage report counts each state; deleting every personal key removes only the keys, endpoints and models, records the event and reaches a request that already loaded them; only visible ASCII keys up to 900 characters are accepted, the longest still fits once sealed, an invalid stored key is never used and is reported as unreadable, and the look through a teacher’s courses runs once per request
tests/admin/setting_secret_test.php 4 The encrypted site-key setting: saving stores the key sealed and trimmed, an empty value deletes it, and saving from the admin page logs both values masked, even an old one still in plain text; a value that is not a valid key is refused with a message and the saved key stays
tests/check/keys_encrypted_test.php 4 The security check: OK with nothing stored or everything encrypted, a warning with both counts for a plain or unreadable key, and its name, component and settings link
Total 211  
vendor/bin/phpunit --testsuite local_aihub

Line coverage by class (PHPUnit + Xdebug):

Class Line coverage
ai 95%
local\client 91%
local\export 86%
local\keys 100%
local\usage_log 100%
output\mykeys 100%
output\renderer 100%
output\report 100%
privacy\provider 100%
task\purge_old_logs 100%
lib.php 100%
Overall 96%

The transport layer used to sit outside the suite, on the grounds that it makes live HTTP calls. That reasoning covered more ground than it should have: building a request and parsing a response are not network operations, and leaving them to the mock meant the part of the plugin that talks to providers — including the code that turns an API refusal into the sentence an administrator reads — was the one part nothing checked. Two fixtures reach it now: recording_client runs the real call_* methods and captures what they assembled, and stub_transport_client answers from a canned transport so the parsing runs for real, through a single seam (make_curl()).

What is left uncovered is genuinely out of reach of a unit test:

Behat — Acceptance Tests

Feature file Scenarios What is covered
tests/behat/mykeys.feature 5 A provider starts unconfigured; saving a personal key marks it configured without revealing the stored value; a failed attempt of the user’s own showing its reason; the personal history downloading as CSV and as Excel
tests/behat/report.feature 7 Both attempts of one request listed with the reason the first failed; the failures filter hiding what worked, the successes filter hiding what failed, and returning to the full list; a request made outside a session attributed rather than shown as an id; the report downloading as CSV and as Excel
Total 12  
php admin/tool/behat/cli/init.php
vendor/bin/behat --tags=@local_aihub --profile=chrome

🔐 Security & Privacy

🔎 Third-party Service Disclosure

The hub transmits prompt text to a third-party AI provider only when a key is configured and a generation is requested.

Is an API key required?

No. The plugin installs and runs without any key — it simply reports that no source is available, and consumers fall back to their own core_ai integration. No external request is made until a site or personal key is set.

Supported providers

These services operate under their own terms of service and privacy policies.

Groq model choice

The Groq slot calls a single fixed model, openai/gpt-oss-120b. Groq periodically deprecates specific model IDs (e.g. llama-3.3-70b-versatile, decommissioned 2026-08-16) and expects migration to a named replacement. Among the free-tier options Groq recommended for this migration, openai/gpt-oss-120b was chosen over qwen/qwen3.6-27b for stronger instruction-following and more reliable JSON-mode output across the varied prompts sent by different consumer plugins.

How to obtain an API key

API keys are created directly on the provider’s official website. Gemini, Groq and DeepSeek currently offer free usage tiers or trial credits (pricing policies may change). The hub does not provide API keys.

Where keys are configured

  1. Personal key — set by each user in My AI keys (preferences), when personal keys are enabled and the user has the capability.
  2. Site key — set by the admin in Site administration → Plugins → Local plugins → AI Hub.

Data Transmission

When a key resolves to a provider, the prompt text is transmitted to that provider’s API to generate the response:

The hub stores a usage log (who requested, which component, a short label of what was generated, provider, model, key tier and time) but does not store prompts or AI responses. All external destinations are declared in the plugin’s Privacy provider.

Demo credentials

Not applicable — no credentials are required to install or use the hub. Every AI feature stays inert until a site or personal key is configured.

📄 License

This project is licensed under the GNU General Public License v3 (GPLv3).

Copyright: 2026 Jean Lúcio