Skip to content

Translation and memory

Updated

These components shape what an agent shows and what it keeps. AI Translation lets each visitor read and hear the answers in their own language. AI Memory names where the agent’s memory is stored so it outlives the page. AI Summarizer gives each visitor a personal summary of their conversation to download. Finally, the AI Model’s Context methods let a script start a fresh private conversation or switch between saved ones.

  • You have an agent with a dialog; see Creating an agent and Dialog and captions.
  • Context is the agent’s record of a conversation: the messages exchanged, plus what its Speech To Text observed. Each visitor has a private Context with each agent, and the agent can also have a shared one.
  • Lasting memory uses a Persistable record, described in Multiplayer.

AI Translation (comp-ai-translation, AITranslatorComponent) lists the languages a visitor may choose for this agent’s output. Translation is presentation only: the instructions, the conversation history and the stored Context stay in the original language, and only what the visitor sees and hears is translated.

Prop Type Default Description
languages array of 'en', 'es', 'pt', 'de', 'it', 'fr' ['en'] One to six different languages, in fallback order. The first is used when the visitor’s choice is not allowed.

The visitor’s choice is a run-time setting, never saved into the scene. It has two parts: whether translation is enabled (off by default, so the dialog shows “Original”), and the preferred language, which is kept while translation is off. With translation on:

  • The dialog waits for each finished reply to be translated before showing it, and speaks it in that language.
  • Captions translate finished lines.
  • Changing language cancels translations in flight.
Member What it does
translate(text, { language?, signal? }) Translate any text; resolves the translation. Works even while the visitor’s translation is off. language defaults to the effective language and must be one of languages.
getOutputLanguage() The current selection: { translationEnabled, preferredLanguage, effectiveLanguage, allowedLanguages }.
setOutputLanguage(language) Set the preferred language. Throws when this agent does not allow it.
setTranslationEnabled(enabled) Switch translation on or off, keeping the language.
subscribeOutputLanguage(listener) Call listener(selection) on each change. Returns the stop function.
translatesTo(language) Whether languages includes it.
getSnapshot(), subscribe(listener) { phase }, idle or translating, across the dialog, captions and scripts of this agent, and its changes.

The output-language methods throw when the agent has no enabled AI Translation or the application offers no AI.

Each translation sends events to the agent’s Signal Emitters:

Event Data
AIAgent::translation-requested outputLanguage, translationSource
AIAgent::translation-completed text: the translation; canonicalText: the original
AIAgent::translation-failed text: a message safe to show
AIAgent::translation-cancelled —

All four also carry operationId to tell translations apart.

AI Memory (comp-ai-memory, AIMemoryComponent) gives the agent a memory that outlives the page. It names the persistable record that keeps it.

Prop Type Default Description
persistable string '' Id of the persistable record that holds this agent’s memory. Empty keeps none.

Memory reads and writes during a turn are reported as activity events (AIAgent::memory-read, AIAgent::memory-written and their companions); see Scripting AI.

AI Summarizer (comp-ai-summarizer, AISummarizerComponent) gives each visitor a personal summary of what they and the agent discussed, to read and download.

Prop Type Default Description
limit integer 1024 The longest summary, in tokens (pieces of words), from 256 to 4096.

Generating and downloading are separate steps:

Member What it does
getSummaryAvailability() { access, available, reason? }, with access one of allowed, denied, unknown. Reading it starts nothing.
generateSummary({ signal? }) Prepare a summary and wait for it. Resolves { jobId, text, capturedAt, generatedAt, expiresAt }, or { status: 'empty', jobId } when there is nothing to summarize yet. Rejects when it fails. getSummary is the same call.
downloadSummary({ jobId?, format?, signal? }) Save the prepared summary as 'pdf' (default), 'txt' or 'md'. Generates nothing new. Resolves { status }: saved, initiated, missing or cancelled.
getSummaryJob() The latest job: { jobId, state, … }, with state one of queued, running, ready, empty, failed, cancelled, expired.
subscribeSummary(listener) Call listener() when this agent’s job or availability changes. Returns the stop function.

Call downloadSummary directly from a user action, such as a button press, so the browser can open its save dialog.

The AI Model manages the visitor’s private Contexts. Switching Context is how a script starts a fresh conversation without losing the old one.

Method What it does
listContexts({ limit?, cursor?, signal? }) Resolves { items: [{ id, updatedAt }], nextCursor? }. limit is 1 to 50, 20 by default. Creates and selects nothing.
createContext({ signal? }) Resolves a new Context. It does not select it.
setContext(context, { signal? }) Select a Context: the conversation and dialog now show it.
getContext(id?, { signal? }) Resolves the selected Context, or checks an explicit id without selecting it.
clearContext(id?, { signal? }) Remove the messages, observations and latest summary of a Context. Its id and selection stay.
getGlobalContext({ signal? }) Resolves the agent’s shared Context, a separate read-only reference.

getConversation() always shows the selected Context. A turn keeps running in the Context it started in, even if you switch while it runs, and its reply never appears in the other one.

SummaryButton.jx
#pragma lifecycle(startup)
let summarizer;
let status;
async function makeSummary() {
const availability = summarizer.getSummaryAvailability();
if (!availability.available) {
status.setProps({ text: availability.reason || 'Summaries are not available.' });
return;
}
status.setProps({ text: 'Preparing your summary…' });
try {
const result = await summarizer.generateSummary();
if (result.status === 'empty') {
status.setProps({ text: 'Talk to the guide first, then try again.' });
return;
}
status.setProps({ text: 'Your summary is ready.' });
await summarizer.downloadSummary({ jobId: result.jobId, format: 'pdf' });
} catch (error) {
status.setProps({ text: 'The summary failed. Please try again.' });
}
}
function startup() {
summarizer = findEntity('Guide').getComponent(AISummarizerComponent);
status = findEntity('Summary Status').getComponent(UILabelComponent);
on('summary/make', (event) => {
if (event.eventType === EventType.UIButton.Press) makeSummary();
});
}
  • Availability is checked first: reading it starts nothing and gives a reason to show when summaries are off.
  • An empty result is not an error; it means there is nothing to summarize yet.
  • The download follows straight from the button press, so the browser can show its save dialog.

A keyboard shortcut for the language menu: each press of L picks the next language the agent allows, and after the last one goes back to the original.

LanguageCycle.jx
#pragma lifecycle(startup, update, dispose)
let translator;
let stopWatching;
let index = -1; // -1 is the original language
function startup() {
translator = findEntity('Guide').getComponent(AITranslatorComponent);
try {
const selection = translator.getOutputLanguage();
log('Allowed:', selection.allowedLanguages.join(', '), '· translation', selection.translationEnabled ? 'on' : 'off');
stopWatching = translator.subscribeOutputLanguage((now) => {
log('Showing', now.translationEnabled ? now.effectiveLanguage : 'the original');
});
} catch (error) {
log('No translation here:', error.message);
translator = undefined;
}
}
function update() {
if (!translator || !Input.keyboard.isKeyReleased(Key.L)) return;
const languages = translator.getOutputLanguage().allowedLanguages;
index = index + 1 < languages.length ? index + 1 : -1;
if (index === -1) {
translator.setTranslationEnabled(false);
return;
}
translator.setOutputLanguage(languages[index]);
translator.setTranslationEnabled(true);
}
function dispose() {
if (stopWatching) stopWatching();
}
  • getOutputLanguage() gives the allowed languages in the AI Translation’s order, so the script never hard-codes them and setOutputLanguage never throws for a language the agent does not allow.
  • The output-language methods throw when the agent has no enabled AI Translation or the application offers no AI, so startup reads them inside try.
  • subscribeOutputLanguage reports every change, including those made from the dialog’s own language button.
  • Choosing the language is local. Translating the replies the dialog shows needs the AI service.
LanguageMenu.jx
#pragma lifecycle(startup, dispose)
// Scene: an AI Agent named "Guide" with an AI Translation allowing ['en', 'es', 'fr'],
// and a UI List whose UI List Items have the values 'original', 'en', 'es' and 'fr',
// with a Signal Emitter on 'guide/language'.
let translator;
let stopWatching;
function startup() {
translator = findEntity('Guide').getComponent(AITranslatorComponent);
on('guide/language', (event) => {
if (event.eventType !== EventType.UIList.Select) return;
const choice = event.data.value;
if (choice === 'original') {
translator.setTranslationEnabled(false);
} else if (translator.translatesTo(choice)) {
translator.setOutputLanguage(choice);
translator.setTranslationEnabled(true);
}
});
stopWatching = translator.subscribeOutputLanguage((selection) => {
log('Showing', selection.translationEnabled ? selection.effectiveLanguage : 'the original');
});
}
function dispose() {
if (stopWatching) stopWatching();
}
  • translatesTo checks the choice before setOutputLanguage, which throws for a language the agent does not allow.
  • Switching translation off keeps the preferred language, so turning it back on restores the last choice.
  • The subscription is released in dispose, so it does not outlive the script.
TranslatedSign.jx
#pragma lifecycle(startup)
// Scene: an AI Agent named "Guide" with an AI Translation,
// and a UI Label named "Sign".
async function startup() {
const translator = findEntity('Guide').getComponent(AITranslatorComponent);
const sign = findEntity('Sign').getComponent(UILabelComponent);
const original = 'Please do not touch the sculptures.';
sign.setProps({ text: original });
const selection = translator.getOutputLanguage();
if (!selection.translationEnabled) return;
try {
const text = await translator.translate(original);
sign.setProps({ text });
} catch (error) {
log('Keeping the original sign:', error.message);
}
}
  • translate works on any text, not only replies, so the same component localizes the scene’s own signs.
  • Without a language, it translates into the visitor’s effective language.
  • On failure the original text stays, so the sign is never empty.
NewConversation.jx
#pragma lifecycle(startup)
// Scene: an AI Agent named "Guide", and a UI Button "New chat"
// with a Signal Emitter on 'guide/new-chat'.
let model;
async function newChat() {
const conversation = model.getConversation();
if (conversation && conversation.getSnapshot().activeTurnId) conversation.cancel();
const fresh = await model.createContext();
await model.setContext(fresh);
log('New conversation', fresh.id);
const page = await model.listContexts({ limit: 5 });
log('Recent conversations:', page.items.map((item) => item.id).join(', '));
}
function startup() {
model = findEntity('Guide').getComponent(AIModelComponent);
on('guide/new-chat', (event) => {
if (event.eventType !== EventType.UIButton.Press) return;
newChat().catch((error) => log('Could not start a new chat:', error.message));
});
}
  • createContext makes a Context without selecting it; setContext switches the conversation and dialog to it. The old Context stays and appears in listContexts.
  • Cancelling the running turn first is optional: a turn would finish in the Context it started in anyway, but the visitor expects a clean start.
  • Expecting translation to change the conversation. The history, the Context and the model’s instructions stay in the original language. Read canonicalText on translation-completed for the original.
  • Setting a language the agent does not allow. setOutputLanguage throws. Check translatesTo first.
  • Downloading later. Call downloadSummary from the button press itself, not after a long delay, or the browser may skip the save dialog.
  • Treating an empty summary as an error. { status: 'empty' } only means nothing has been said yet.
  • Forgetting that createContext does not switch. Call setContext with the new Context.