Set up the runtime side of a Mendix GenAI app (Agents Kit 2): register a Mendix Cloud GenAI key or an OpenAI-compatible endpoint, seed AgentCommons agents from JSON, open and resume Conversational UI chats, load PgVector or Mendix Cloud knowledge bases, and turn on traces. Covers the startup-code gotchas (the encryption key, the vector extension, indexing delay, the collapsed chat). For the Agent Editor documents themselves, see the agents skill.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Genai Runtime?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/mendixlabs-genai-runtime)
---
name: genai-runtime
description: "Set up the runtime side of a Mendix GenAI app (Agents Kit 2): register a Mendix Cloud GenAI key or an OpenAI-compatible endpoint, seed AgentCommons agents from JSON, open and resume Conversational UI chats, load PgVector or Mendix Cloud knowledge bases, and turn on traces. Covers the startup-code gotchas (the encryption key, the vector extension, indexing delay, the collapsed chat). For the Agent Editor documents themselves, see the agents skill."
---
<!-- skill-index: generated by scripts/skill-index.py; make check-skill-index -->
## Find it fast
`sed -n '<from>,<to>p' SKILL.md` one section rather than reading the file;
`./mxcli syntax <topic>` answers *how do I write this* for a fraction of either.
| lines | section |
|---|---|
| 37-47 | Startup code must not throw |
| 48-131 | Models |
| 132-174 | Runtime agents (AgentCommons) |
| 175-231 | Chat (Conversational UI) |
| 232-273 | Knowledge bases |
| 274-285 | Agents attached to knowledge bases |
| 286-300 | Traces and token usage |
| 301-312 | Gotchas, in one place |
<!-- /skill-index -->
# GenAI at Runtime (Agents Kit 2)
The `agents` skill covers the **documents** (Model, Knowledge Base, Consumed MCP
Service, Agent) and calling an agent from a microflow. This skill covers what an
app does with the Marketplace modules **at runtime**: the startup microflows that
register models, seed agents and load knowledge bases, and the chat pages. All of
it is ordinary microflow logic, so `describe microflow`, `check --references` and
`exec` apply as usual.
Measured against the Agent Builder Starter App modules: AgentCommons 4.4.0,
ConversationalUI 7.4.0, GenAICommons 7.3.0, MxGenAIConnector 7.4.0,
OpenAIConnector 9.4.0, PgVectorKnowledgeBase 7.1.0 (Mendix 11.16). Check the
installed versions with `list modules` before copying a signature.
## Startup code must not throw
Every setup step below that stores a secret (an OpenAI key, a PgVector password)
goes through `Encryption.Encrypt`, which **raises an error when
`Encryption.EncryptionKey` is empty or not 32 characters**. The constant's
default is empty, so a run configuration without it (a new environment, or
`mxcli run --local` / `test --local` on a model that sets it only in `Default`)
throws there. Unhandled in an after-startup microflow, that stops the runtime.
Give each such call an `on error` handler, as below, and set the key per
environment.
## Models
### Mendix Cloud GenAI
The key string from the Mendix Cloud GenAI portal registers the resource and its
models in one call. It overwrites a configuration with the same ID, so calling it
on every startup is safe:
```sql
mdl 1;
create constant MyModule.GenAIKey ( Type: String, DefaultValue: '' );
create microflow MyModule.GenAI_Register ()
returns Boolean
begin
$Configuration = call microflow MxGenAIConnector.Configuration_RegisterByString(ConfigurationStringImport = @MyModule.GenAIKey);
if $Configuration = empty then
log error node 'GenAI' 'MyModule.GenAIKey holds no valid Mendix Cloud GenAI key';
return false;
end if;
return true;
end;
```
### An OpenAI-compatible endpoint
The plain key goes on the non-persistent `OpenAIConnector.ApiKey` helper, never
on `Configuration/ApiKey` (which holds the encrypted value);
`Configuration_Commit` encrypts it. Set `IsNativeOpenAI = false` for an API that
only imitates OpenAI (Mistral, a local server). `OpenAIDeployedModel_Create`
already sets the model's execution microflow for its modality, so
`OpenAIDeployedModel_SetMicroflow` (the UI's path) is not needed after it.
```sql
mdl 1;
create constant MyModule.LlmEndpoint ( Type: String, DefaultValue: 'https://api.openai.com/v1' );
create constant MyModule.LlmApiKey ( Type: String, DefaultValue: '' );
create microflow MyModule.Llm_Register ()
returns Boolean
begin
retrieve $Existing from OpenAIConnector.Configuration
where DisplayName = 'Assistant LLM'
first;
if $Existing != empty then
return true;
end if;
$Configuration = call microflow OpenAIConnector.Configuration_Create();
change $Configuration (DisplayName = 'Assistant LLM', ApiType = OpenAIConnector.ENUM_ApiType.OpenAI, Endpoint = @MyModule.LlmEndpoint, IsNativeOpenAI = true);
$ApiKey = call microflow OpenAIConnector.ApiKey_GetCreate_Configuration(Configuration = $Configuration);
change $ApiKey (ApiKey = @MyModule.LlmApiKey);
call microflow OpenAIConnector.Configuration_Commit(Configuration = $Configuration)
on error without rollback begin
log error node 'GenAI' 'Could not store the LLM key: is Encryption.EncryptionKey set?';
return false;
end error;
$InputModalities = create list of GenAICommons.InputModality;
$Model = call microflow OpenAIConnector.OpenAIDeployedModel_Create(
Configuration = $Configuration,
Model = 'gpt-4o-mini',
Architecture = 'OpenAI',
OutputModality = GenAICommons.ENUM_ModelModality.Text,
ApiVersion = empty,
DisplayName = 'GPT-4o mini',
SupportsSystemPrompt = GenAICommons.ENUM_ModelSupport._True,
SupportsFunctionCalling = GenAICommons.ENUM_ModelSupport._True,
SupportsConversationHistory = GenAICommons.ENUM_ModelSupport._True,
InputModalityList = $InputModalities,
SupportsStreaming = GenAICommons.ENUM_ModelSupport._True
);
if $Model = empty then
return false;
end if;
call microflow GenAICommons.DeployedModel_Commit(DeployedModel = $Model);
return true;
end;
```
An embeddings model is the same call with
`OutputModality = GenAICommons.ENUM_ModelModality.Embeddings`. Video, Audio,
Document and Other are refused (logged, `empty` returned).
## Runtime agents (AgentCommons)
A runtime agent is an `AgentCommons.Agent` object, not a document. Seed one from
the JSON the Agents page exports, with `AgentCommons.Agent_GetCreate_Json`, the
way the module's own templates do (`AgentCommons.ProductDescriptionGeneratorAgent`
is a complete example: `describe microflow` it).
```sql
$Agent = call microflow AgentCommons.Agent_GetCreate_Json(AgentTitle = 'Support agent', AgentJson = @MyModule.SupportAgentJson);
```
What the import does, which decides how to seed:
- **It matches on `Title` only, and then returns the stored agent without
reading the JSON.** It is idempotent, but a changed JSON never reaches an agent
that exists. To roll out a new prompt, change the title, or delete the agent
first, or use an Agent Editor document instead (the `agents` skill), which
`ASU_AgentEditor` re-imports on every start.
- **The models and knowledge bases must exist, committed, before the call.** Each
version's `DeployedModel {Architecture, Model}` is looked up among the existing
`GenAICommons.DeployedModel` objects (`Architecture` `Mendix Cloud` for Mendix
Cloud GenAI); a knowledge base's `ConsumedKnowledgeBase {DisplayName,
Architecture}` the same way (`Architecture` `PgVector` for PgVector). A miss
leaves the version without one; chat then fails with "Select a model on the
agent version in use". So register models first, then seed agents.
- `Version_InUse {UUID}` picks the version the agent runs.
- `UUID` and `Title` are required; without them the import logs and returns empty.
- A tool's `UserAccessApproval` takes the `GenAICommons.ENUM_UserAccessApproval`
keys: `UserConfirmationRequired`, `VisibleForUser` or `HiddenForUser`. (The
module's sample JSON writes `Hidden`, which is not one.)
The JSON's keys: `Title`, `Description`, `UsageType`, `UUID`, `Entity`,
`DeployedModel`, `Version_InUse`, `Variables[{Key}]`, `TestCases`, and
`Versions[]` with `SystemPrompt`, `UserPrompt`, `UUID`, the generation settings,
`DeployedModel`, `Tools[{Name, Description, Microflow, UserAccessApproval,
IsEnabled, UUID}]`, `MCPs[]`, `SingleMCPTools[]` and `KnowledgeBases[{Name,
Description, Collection, MaxNumberOfResults, MinimumSimilarity, IsEnabled,
ConsumedKnowledgeBase{DisplayName, Architecture}}]`. Export one from the Agents
page rather than writing it from scratch.
Calling it is the `agents` skill's *Calling Agents from Microflows*
(`Agent_Call_WithoutHistory`, `Agent_Call_WithHistory`).
## Chat (Conversational UI)
`AgentCommons.ChatContext_Create_ForAgent` creates a `ConversationalUI.ChatContext`
for the agent. It needs the agent's in-use version to have a model, **returns
empty instead of throwing** on any problem, and does not commit. Its action
microflow takes one `ChatContext` and returns Boolean;
`ConversationalUI.ChatContext_ChatWithHistory_ActionMicroflow_Agent_Runtime` is
the ready-made one.
`ChatContext` is persistent, owned by the user who created it (its `User` access
is limited to `System.owner`). Creating one on every page visit fills the user's
history with empty chats. Resume instead; this is the starter app's
`MyFirstSupportAgent.ChatContext_GetCreate`, which reuses the user's chat that
has no messages yet:
```sql
mdl 1;
create microflow MyModule.SupportChat_GetCreate (
$Agent: AgentCommons.Agent
)
returns ConversationalUI.ChatContext
begin
retrieve $ChatContext from ConversationalUI.ChatContext
where [System.owner = $currentUser]
[not(ConversationalUI.Message_ChatContext/ConversationalUI.Message)]
[ConversationalUI.ChatContext_Agent = $Agent]
first;
if $ChatContext != empty then
return $ChatContext;
end if;
$NewChatContext = call java action AgentCommons.ChatContext_Create_ForAgent(
Agent = $Agent,
ActionMicroflow = 'ConversationalUI.ChatContext_ChatWithHistory_ActionMicroflow_Agent_Runtime',
ContextObject = empty,
OverwritingDeployedModel = empty
);
return $NewChatContext;
end;
```
- **Topics.** `ConversationalUI.ChatContext_Preprocessing` sets the chat's
`Topic` from the first 200 characters of the first prompt, only while the topic
is empty. It changes the object without committing it.
- **History.** `ConversationalUI.Snippet_ChatContext_HistorySideBar` is one row
(the topic and a delete button) for one `ChatContext`. The list around it is
yours: a list view over the user's `ConversationalUI.ChatContext` objects,
calling that snippet per row.
- **The chat collapses outside its page.** `Snippet_ChatContext_ConversationalUI`
is a flex column whose message list is `flex: 1 1 0`. It needs a parent with a
real height, which `ConversationalUI.ConversationalUI_FullScreenChat` gives it
(`chat-page--fullheight`). Placed in an ordinary container, the message list has
zero height and only the input box shows. The messages are still in the DOM, so
a text-based check passes; check it with a screenshot (`verify-in-runtime`).
Open the full-screen page with the chat as its parameter, or give the parent a
height.
## Knowledge bases
Both connectors take a `GenAICommons.ChunkCollection`. Build it with
`GenAICommons.ChunkCollection_Create` and add one chunk per source object with
the Java action `GenAICommons.ChunkCollection_AddKnowledgeBaseChunk`
(`InputText`, `HumanReadableID`, `MxObject`, optional `MetadataCollection`).
Pass the `MxObject`: `Replace` deletes and re-inserts by it, and PgVector
refuses a chunk without one. Knowledge base and collection names may not contain
spaces (both connectors log and return empty).
### PgVector
1. **The database needs the `vector` extension.** The module creates it
(`CREATE EXTENSION IF NOT EXISTS vector`) only from the *Test* button on its
configuration page. Seeding from code does not, so install it on the server,
or give the database user the right to create it and press *Test* once.
2. **Configuration.** Create a `PgVectorKnowledgeBase.DatabaseConfiguration` with
`DisplayName`, `JdbcURL` and `Username`. Set the password on the helper from
`PgVectorKnowledgeBase.DatabasePassword_GetCreate` (`$Helper/Password`), then
call `PgVectorKnowledgeBase.DatabaseConfiguration_Commit`. That encrypts the
password (**the encryption-key rule above applies**), sets `Architecture` to
`PgVector` and the retrieval microflows, and commits. Its `DisplayName` is what
an agent's JSON names in `ConsumedKnowledgeBase`.
3. **Load.** Embed first, then store: `GenAICommons.Embeddings_ChunkCollection`
(a Java action; `DeployedModel` must be an Embeddings model, and it writes the
vectors onto the chunks), then
`PgVectorKnowledgeBase.PgVectorKnowledgeBase_GetOrCreate($DatabaseConfiguration,
$KnowledgeBaseName)`, then `PgVectorKnowledgeBase.ChunkCollection_Replace`.
`ChunkCollection_Replace` does not embed, and returns `false` (logged, not
thrown) for an empty collection, a chunk without `MxObject`, an `InputText`
over 4000 characters, or an unconfigured database. Check the result.
### Mendix Cloud GenAI
`MxGenAIConnector.Collection_GetCreate($MxCloudKnowledgeBaseResource,
$CollectionName)` returns the collection; `MxGenAIConnector.ChunkCollection_Embed_Replace`
embeds with the resource's own model and stores. **Chunks become searchable 60
to 120 seconds later** (the module documents it; measured on a live resource:
none at 30 s, found at about 90 s), and replacing the same objects within that
window can leave the knowledge base out of sync. A test that loads and then
queries at once finds nothing: wait, or poll.
## Agents attached to knowledge bases
On a runtime agent, a knowledge base is an `AgentCommons.KnowledgeBase` object
on the version (association `AgentCommons.KnowledgeBase_Version`), pointing at the
consumed knowledge base through the association
`AgentCommons.KnowledgeBase_ConsumedKnowledgeBase`. `CollectionIdentifier` holds
the collection or knowledge base name. `AgentCommons.KnowledgeBase_Create($Version)`
starts one (enabled, with a UUID, not committed); `KnowledgeBase_Save` commits.
Its `Name` must match `[a-zA-Z_][a-zA-Z0-9_]+`, at most 64 characters, and not
clash with an enabled tool on the same version. Seeding through the JSON's
`KnowledgeBases[]` does the same.
## Traces and token usage
- **`GenAICommons.StoreTraces` defaults to false**, so the Traces page stays empty
until a run configuration sets it. Setting it also stores token usage.
`GenAICommons.StoreUsageMetrics` (default true) records usage for chat
completions and embeddings only.
- `Trace_CleanUpAfterDays` and `Usage_CleanUpAfterDays` default to 0, never
delete; the scheduled event `GenAICommons.ScE_Usage_Cleanup` applies them.
- The pages are `ConversationalUI.Trace_Overview` (module role
`ConversationalUI.TraceMonitoring`), `ConversationalUI.TokenConsumptionMonitor`
(`ConversationalUI.UsageMonitoring`) and `AgentCommons.Agent_Overview`. They
size themselves in `vw` (91 to 95), so beside an open sidebar their right edge
is clipped. Give them a layout without the sidebar, or override the width in
the theme.
## Gotchas, in one place
| Symptom | Cause |
|---|---|
| Runtime stops at startup after a model or PgVector setup | `Encryption.EncryptionKey` empty in that run configuration; the commit raises |
| A changed agent JSON has no effect | `Agent_GetCreate_Json` returns the stored agent by `Title` |
| "Select a model on the agent version in use" | The JSON's `DeployedModel` matched no committed `GenAICommons.DeployedModel` at import |
| A new chat per visit, history full of empty chats | `ChatContext` is persistent; resume one (above) |
| Only the chat's input box shows | The chat snippet's parent has no height |
| PgVector load returns false | No `MxObject` on a chunk, text over 4000 characters, not embedded first, or no `vector` extension |
| Mendix Cloud knowledge base finds nothing right after loading | 60 to 120 s indexing delay |
| Traces page empty | `GenAICommons.StoreTraces` is false by default |