diff --git a/roles/web-app-moodle/files/php/provision_ai_gateway.php b/roles/web-app-moodle/files/php/provision_ai_gateway.php new file mode 100644 index 0000000000..cfebaf1d8e --- /dev/null +++ b/roles/web-app-moodle/files/php/provision_ai_gateway.php @@ -0,0 +1,44 @@ +get_provider_instances(['provider' => $class, 'name' => $name]); +$provider = $instances + ? reset($instances) + : $manager->create_provider_instance(classname: $class, name: $name); + +$actionconfig = $provider->actionconfig; +foreach ($textactions as $action) { + $actionconfig[$action]['enabled'] = true; + $actionconfig[$action]['settings']['endpoint'] = (string) getenv('AI_CHAT_ENDPOINT'); + $actionconfig[$action]['settings']['model'] = (string) getenv('AI_CHAT_MODEL'); +} +$actionconfig[$imageaction]['enabled'] = false; +$actionconfig[$imageaction]['settings']['endpoint'] = (string) getenv('AI_IMAGE_ENDPOINT'); + +$provider = $manager->update_provider_instance( + provider: $provider, + config: array_merge($provider->config, ['apikey' => (string) getenv('AI_API_KEY')]), + actionconfig: $actionconfig, +); +$manager->enable_provider_instance($provider); + +$stored = $manager->get_provider_instances(['id' => $provider->id]); +echo json_encode([ + 'id' => (int) $provider->id, + 'endpoints' => array_map( + fn(array $action): string => (string) ($action['settings']['endpoint'] ?? ''), + reset($stored)->actionconfig, + ), +]), PHP_EOL; diff --git a/roles/web-app-moodle/files/playwright/test-litellm-gateway.js b/roles/web-app-moodle/files/playwright/test-litellm-gateway.js index 038d3c3c70..6c7cec5be5 100644 --- a/roles/web-app-moodle/files/playwright/test-litellm-gateway.js +++ b/roles/web-app-moodle/files/playwright/test-litellm-gateway.js @@ -5,7 +5,10 @@ const { skipUnlessServiceEnabled } = require("./service-gating"); const adminNativePassword = decodeDotenvQuotedValue(process.env.ADMIN_NATIVE_PASSWORD || ""); -const ENDPOINT_FIELD = "#id_s_aiprovider_openai_action_generate_text_endpoint"; +const providerName = decodeDotenvQuotedValue(process.env.MOODLE_AI_PROVIDER_NAME || ""); + +const ENDPOINT_FIELD = "#id_endpoint"; +const GENERATE_TEXT_ACTION = "core_ai\\aiactions\\generate_text"; const USER_MENU = ".usermenu, [data-region='user-menu-toggle'], a[href*='profile.php']"; const GATEWAY_PROMPT = "Reply with the single word: pong"; @@ -80,22 +83,47 @@ exports.register = function (shared) { await loginAsSiteAdmin(page, shared); + expect( + providerName, + "MOODLE_AI_PROVIDER_NAME must name the provider instance the deploy creates; without it the test cannot tell that instance from one an administrator added", + ).toBeTruthy(); + + await gotoOnion(page, `${shared.env.moodleBaseUrl}/admin/settings.php?section=aiprovider`, { + waitUntil: "domcontentloaded", + timeout: resolveTimeout(60_000), + }); + + const providerLink = page + .locator("tr", { hasText: providerName }) + .locator("a[href*='/ai/configure.php']") + .first(); + await expect( + providerLink, + `the AI providers page must list the instance "${providerName}"; its absence means the deploy created no provider instance or the session lacks moodle/site:config`, + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + + const providerId = new URL( + await providerLink.getAttribute("href"), + shared.env.moodleBaseUrl, + ).searchParams.get("id"); + await gotoOnion( page, - `${shared.env.moodleBaseUrl}/admin/settings.php?section=aiprovider_openai_generate_text`, + `${shared.env.moodleBaseUrl}/ai/configure_actions.php` + + `?provider=aiprovider_openai&action=${encodeURIComponent(GENERATE_TEXT_ACTION)}&providerid=${providerId}`, { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }, ); const endpointField = page.locator(ENDPOINT_FIELD); await expect( endpointField, - "the aiprovider_openai generate_text settings page must render its API endpoint field; its absence means the provider was never configured or the session lacks moodle/site:config", + "the generate_text settings page of the provider instance must render its API endpoint field; its absence means the instance carries no generate_text action", ).toBeVisible({ timeout: resolveTimeout(60_000) }); const configuredEndpoint = ((await endpointField.inputValue()) || "").trim(); expect( configuredEndpoint, - "aiprovider_openai/action_generate_text_endpoint must be an http(s) URL written by the deploy, not the upstream api.openai.com default", + "the generate_text endpoint of the provider instance must be an http(s) URL written by the deploy, not the upstream api.openai.com default", ).toMatch(/^https?:\/\/.+/i); const endpointHost = new URL(configuredEndpoint).hostname; diff --git a/roles/web-app-moodle/tasks/utils/ai_gateway.yml b/roles/web-app-moodle/tasks/utils/ai_gateway.yml index ef74562a9b..b7377a6bb9 100644 --- a/roles/web-app-moodle/tasks/utils/ai_gateway.yml +++ b/roles/web-app-moodle/tasks/utils/ai_gateway.yml @@ -2,18 +2,31 @@ - name: "๐Ÿ” Verify the gateway contract for {{ application_id }}" ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-litellm/tasks/utils/consumer_contract.yml') }}" -- name: "๐Ÿค– Point the Moodle AI subsystem at the platform gateway" +- name: "๐Ÿค– Point the Moodle AI provider instance at the platform gateway" + ansible.builtin.shell: > + container exec -i --user {{ MOODLE_RUNTIME_USER }} + -e MOODLE_CONFIG={{ MOODLE_CONFIG | quote }} + -e AI_PROVIDER_NAME={{ MOODLE_LITELLM_PROVIDER_NAME | quote }} + -e AI_API_KEY={{ MOODLE_LITELLM_API_KEY | quote }} + -e AI_CHAT_ENDPOINT={{ MOODLE_LITELLM_CHAT_ENDPOINT | quote }} + -e AI_CHAT_MODEL={{ LITELLM_CHAT_MODEL | quote }} + -e AI_IMAGE_ENDPOINT={{ MOODLE_LITELLM_IMAGE_ENDPOINT | quote }} + {{ MOODLE_CONTAINER_ADDRESS }} php + args: + stdin: "{{ lookup('file', 'php/provision_ai_gateway.php') }}" + register: moodle_ai_provider + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿค– Enable the Moodle AI placements" ansible.builtin.shell: > container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} php {{ [MOODLE_CLI_DIR, 'cfg.php'] | path_join }} - --component={{ item.component | quote }} - --name={{ item.name | quote }} - --set={{ item.value | quote }} - loop: "{{ MOODLE_LITELLM_SETTINGS }}" - loop_control: - label: "{{ item.component }}/{{ item.name }}" + --component={{ item | quote }} + --name=enabled + --set=1 + loop: "{{ MOODLE_LITELLM_PLACEMENTS }}" changed_when: false - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: "๐Ÿงน Purge Moodle caches so the provider picks up its endpoint" ansible.builtin.shell: > @@ -21,20 +34,14 @@ php {{ [MOODLE_CLI_DIR, 'purge_caches.php'] | path_join }} changed_when: false -- name: "๐Ÿ”Ž Read back the configured chat endpoint" - ansible.builtin.shell: > - container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} - php {{ [MOODLE_CLI_DIR, 'cfg.php'] | path_join }} - --component=aiprovider_openai - --name=action_generate_text_endpoint - register: moodle_ai_endpoint - changed_when: false - - name: "๐Ÿ›‘ Refuse a Moodle AI provider that does not answer through the gateway" ansible.builtin.assert: that: - - (moodle_ai_endpoint.stdout | trim) == MOODLE_LITELLM_CHAT_ENDPOINT + - moodle_ai_endpoints | length > 0 + - moodle_ai_endpoints | difference([MOODLE_LITELLM_CHAT_ENDPOINT, MOODLE_LITELLM_IMAGE_ENDPOINT]) | length == 0 fail_msg: >- - aiprovider_openai still resolves generate_text to - '{{ moodle_ai_endpoint.stdout | trim }}' instead of + The Moodle AI provider instance resolves actions to + {{ moodle_ai_endpoints | join(', ') }} instead of {{ MOODLE_LITELLM_CHAT_ENDPOINT }}, so prompts would leave the deployment. + vars: + moodle_ai_endpoints: "{{ (moodle_ai_provider.stdout_lines | last | from_json).endpoints.values() | unique | list }}" diff --git a/roles/web-app-moodle/templates/playwright.env.j2 b/roles/web-app-moodle/templates/playwright.env.j2 index 02eb6ebd3c..6fbea79405 100644 --- a/roles/web-app-moodle/templates/playwright.env.j2 +++ b/roles/web-app-moodle/templates/playwright.env.j2 @@ -21,6 +21,7 @@ PERSONA_ADMINISTRATOR_BLOCKED=true MATOMO_BASE_URL={{ lookup('tls', 'web-app-matomo', 'url.base') | dotenv_quote }} LITELLM_SERVICE_ENABLED={{ lookup('config', application_id, 'services.litellm.enabled') | string | lower }} +MOODLE_AI_PROVIDER_NAME={{ MOODLE_LITELLM_PROVIDER_NAME | dotenv_quote }} SSO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.sso.enabled') | string | lower }} LOGOUT_SERVICE_ENABLED={{ lookup('config', application_id, 'services.logout.enabled') | string | lower }} MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enabled') | string | lower }} diff --git a/roles/web-app-moodle/vars/main.yml b/roles/web-app-moodle/vars/main.yml index b674edd777..fffdb5f0db 100644 --- a/roles/web-app-moodle/vars/main.yml +++ b/roles/web-app-moodle/vars/main.yml @@ -63,17 +63,10 @@ MOODLE_LITELLM_ENABLED: "{{ lookup('config', application_id, 'services.litellm.e MOODLE_LITELLM_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.litellm_api_key') }}" MOODLE_LITELLM_CHAT_ENDPOINT: "{{ LITELLM_OPENAI_BASE_LOCAL_URL }}/chat/completions" MOODLE_LITELLM_IMAGE_ENDPOINT: "{{ LITELLM_OPENAI_BASE_LOCAL_URL }}/images/generations" -MOODLE_LITELLM_SETTINGS: - - { component: aiprovider_openai, name: enabled, value: "1" } - - { component: aiprovider_openai, name: apikey, value: "{{ MOODLE_LITELLM_API_KEY }}" } - - { component: aiprovider_openai, name: action_generate_text_endpoint, value: "{{ MOODLE_LITELLM_CHAT_ENDPOINT }}" } - - { component: aiprovider_openai, name: action_generate_text_model, value: "{{ LITELLM_CHAT_MODEL }}" } - - { component: aiprovider_openai, name: action_summarise_text_endpoint, value: "{{ MOODLE_LITELLM_CHAT_ENDPOINT }}" } - - { component: aiprovider_openai, name: action_summarise_text_model, value: "{{ LITELLM_CHAT_MODEL }}" } - - { component: aiprovider_openai, name: action_generate_image_endpoint, value: "{{ MOODLE_LITELLM_IMAGE_ENDPOINT }}" } - - { component: aiprovider_openai, name: generate_image, value: "0" } - - { component: aiplacement_courseassist, name: enabled, value: "1" } - - { component: aiplacement_editor, name: enabled, value: "1" } +MOODLE_LITELLM_PROVIDER_NAME: "LiteLLM gateway" +MOODLE_LITELLM_PLACEMENTS: + - aiplacement_courseassist + - aiplacement_editor MOODLE_EGRESS_BLOCKED_HOSTS: - "0.0.0.0" diff --git a/tests/unit/php/roles/web-app-moodle/files/ProvisionAiGatewayTest.php b/tests/unit/php/roles/web-app-moodle/files/ProvisionAiGatewayTest.php new file mode 100644 index 0000000000..aa3c36da1a --- /dev/null +++ b/tests/unit/php/roles/web-app-moodle/files/ProvisionAiGatewayTest.php @@ -0,0 +1,346 @@ + $value) { + $copy->$property = $value; + } + return $copy; + } + } + + class manager { + private function rows(): array { + $file = getenv('STUB_STATE'); + return is_file($file) ? json_decode(file_get_contents($file), true) : []; + } + + private function store(provider $provider): provider { + $rows = $this->rows(); + $rows[$provider->id] = [ + 'id' => $provider->id, + 'provider' => get_class($provider), + 'name' => $provider->name, + 'enabled' => $provider->enabled, + 'config' => $provider->config, + 'actionconfig' => $provider->actionconfig, + ]; + file_put_contents(getenv('STUB_STATE'), json_encode($rows)); + return $provider; + } + + public function get_provider_instances(?array $filter = null): array { + $found = []; + foreach ($this->rows() as $row) { + foreach ($filter ?? [] as $column => $value) { + if ($row[$column] != $value) { + continue 2; + } + } + $found[$row['id']] = new $row['provider']( + enabled: $row['enabled'], + name: $row['name'], + config: $row['config'], + actionconfig: $row['actionconfig'], + id: $row['id'], + ); + } + return $found; + } + + public function create_provider_instance( + string $classname, + string $name, + bool $enabled = false, + ?array $config = null, + ?array $actionconfig = null, + ): provider { + return $this->store(new $classname( + enabled: $enabled, + name: $name, + config: $config ?? [], + actionconfig: $actionconfig ?? $classname::initialise_action_settings(), + id: count($this->rows()) + 1, + )); + } + + public function update_provider_instance( + provider $provider, + ?array $config = null, + ?array $actionconfig = null, + ): provider { + return $this->store($provider->with( + config: $config ?? $provider->config, + actionconfig: $actionconfig ?? $provider->actionconfig, + )); + } + + public function enable_provider_instance(provider $provider): provider { + return $provider->enabled ? $provider : $this->store($provider->with(enabled: true)); + } + } + } + + namespace aiprovider_openai { + class provider extends \core_ai\provider { + public static function initialise_action_settings(): array { + $text = [ + 'enabled' => true, + 'settings' => [ + 'endpoint' => 'https://api.openai.com/v1/chat/completions', + 'model' => 'gpt-4o', + 'systeminstruction' => 'upstream default', + ], + ]; + return [ + \core_ai\aiactions\generate_text::class => $text, + \core_ai\aiactions\generate_image::class => [ + 'enabled' => true, + 'settings' => [ + 'endpoint' => 'https://api.openai.com/v1/images/generations', + 'model' => 'dall-e-3', + ], + ], + \core_ai\aiactions\summarise_text::class => $text, + \core_ai\aiactions\explain_text::class => $text, + ]; + } + } + } + + namespace core { + class di { + public static function get(string $class): object { + return new $class(); + } + } + } + PHP; + + private string $config; + + private string $state; + + protected function setUp(): void + { + $this->config = (string) tempnam(sys_get_temp_dir(), 'mdlcfg'); + $this->state = (string) tempnam(sys_get_temp_dir(), 'mdlai'); + file_put_contents($this->config, self::MOODLE); + unlink($this->state); + } + + protected function tearDown(): void + { + unlink($this->config); + if (is_file($this->state)) { + unlink($this->state); + } + } + + /** + * Store provider instances the way an earlier run or an administrator left them. + * + * @param list> $rows instances, each with its id + */ + private function seed(array $rows): void + { + file_put_contents($this->state, json_encode(array_column($rows, null, 'id'))); + } + + /** + * Run the script against the stubbed Moodle. + * + * @return array{0: array, 1: int, 2: array>} + * decoded last output line, exit code and the stored instances by id + */ + private function runScript(): array + { + $script = dirname(__DIR__, 6) . '/roles/web-app-moodle/files/php/provision_ai_gateway.php'; + $process = proc_open( + [PHP_BINARY, $script], + [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], + $pipes, + null, + [ + 'MOODLE_CONFIG' => $this->config, + 'STUB_STATE' => $this->state, + 'AI_PROVIDER_NAME' => self::NAME, + 'AI_API_KEY' => 'sk-gateway', + 'AI_CHAT_ENDPOINT' => self::CHAT, + 'AI_CHAT_MODEL' => self::MODEL, + 'AI_IMAGE_ENDPOINT' => self::IMAGE, + 'PATH' => (string) getenv('PATH'), + ] + ); + $stdout = trim((string) stream_get_contents($pipes[1])); + fclose($pipes[1]); + fclose($pipes[2]); + $code = proc_close($process); + + $lines = explode("\n", $stdout); + $stored = is_file($this->state) + ? json_decode((string) file_get_contents($this->state), true) + : []; + + return [(array) json_decode((string) end($lines), true), $code, $stored]; + } + + public function testAFreshMoodleGetsOneEnabledInstanceWithTheGatewayKey(): void + { + [, $code, $stored] = $this->runScript(); + + $this->assertSame(0, $code); + $this->assertCount(1, $stored); + $instance = reset($stored); + $this->assertSame(self::OPENAI, $instance['provider']); + $this->assertSame(self::NAME, $instance['name']); + $this->assertTrue($instance['enabled']); + $this->assertSame('sk-gateway', $instance['config']['apikey']); + } + + public function testEveryTextActionIsEnabledAndAnswersThroughTheGateway(): void + { + [, , $stored] = $this->runScript(); + + $actions = reset($stored)['actionconfig']; + foreach (self::TEXT_ACTIONS as $action) { + $this->assertTrue($actions[$action]['enabled'], $action); + $this->assertSame(self::CHAT, $actions[$action]['settings']['endpoint'], $action); + $this->assertSame(self::MODEL, $actions[$action]['settings']['model'], $action); + $this->assertSame( + 'upstream default', + $actions[$action]['settings']['systeminstruction'], + $action + ); + } + } + + public function testImageGenerationIsSwitchedOffAndStillPointsAtTheGateway(): void + { + [, , $stored] = $this->runScript(); + + $image = reset($stored)['actionconfig'][self::IMAGE_ACTION]; + $this->assertFalse($image['enabled']); + $this->assertSame(self::IMAGE, $image['settings']['endpoint']); + } + + public function testTheOutputNamesTheInstanceAndTheStoredEndpointOfEveryAction(): void + { + [$output, , $stored] = $this->runScript(); + + $this->assertSame(array_key_first($stored), $output['id']); + $this->assertSame( + [ + self::TEXT_ACTIONS[0] => self::CHAT, + self::IMAGE_ACTION => self::IMAGE, + self::TEXT_ACTIONS[1] => self::CHAT, + self::TEXT_ACTIONS[2] => self::CHAT, + ], + $output['endpoints'] + ); + } + + public function testAnInstanceOfThatNameIsReusedAndKeepsWhatTheScriptDoesNotSet(): void + { + $this->seed([[ + 'id' => 7, + 'provider' => self::OPENAI, + 'name' => self::NAME, + 'enabled' => false, + 'config' => ['apikey' => 'sk-stale', 'orgid' => 'org-1'], + 'actionconfig' => [ + self::TEXT_ACTIONS[0] => [ + 'enabled' => false, + 'settings' => [ + 'endpoint' => 'https://api.openai.com/v1/chat/completions', + 'model' => 'gpt-4o', + 'systeminstruction' => 'answer briefly', + ], + ], + ], + ]]); + + [$output, , $stored] = $this->runScript(); + + $this->assertSame([7], array_keys($stored)); + $this->assertSame(7, $output['id']); + $this->assertTrue($stored[7]['enabled']); + $this->assertSame(['apikey' => 'sk-gateway', 'orgid' => 'org-1'], $stored[7]['config']); + $settings = $stored[7]['actionconfig'][self::TEXT_ACTIONS[0]]['settings']; + $this->assertSame(self::CHAT, $settings['endpoint']); + $this->assertSame('answer briefly', $settings['systeminstruction']); + } + + public function testAnInstanceAnAdministratorAddedIsLeftAlone(): void + { + $own = [ + 'id' => 1, + 'provider' => self::OPENAI, + 'name' => 'Our own OpenAI account', + 'enabled' => true, + 'config' => ['apikey' => 'sk-own'], + 'actionconfig' => [], + ]; + $this->seed([$own]); + + [$output, , $stored] = $this->runScript(); + + $this->assertSame([1, 2], array_keys($stored)); + $this->assertSame($own, $stored[1]); + $this->assertSame(2, $output['id']); + $this->assertSame(self::NAME, $stored[2]['name']); + } + + public function testASecondRunChangesNothing(): void + { + [, , $first] = $this->runScript(); + [, $code, $second] = $this->runScript(); + + $this->assertSame(0, $code); + $this->assertSame($first, $second); + } +}