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.
Before you start
Section titled “Before you start”- 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
Section titled “AI Translation”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. |
get |
The current selection: { translation. |
set |
Set the preferred language. Throws when this agent does not allow it. |
set |
Switch translation on or off, keeping the language. |
subscribe |
Call listener(selection) on each change. Returns the stop function. |
translates |
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- |
output, translation |
AIAgent::translation- |
text: the translation; canonicalText: the original |
AIAgent::translation- |
text: a message safe to show |
AIAgent::translation- |
— |
All four also carry operationId to tell translations apart.
AI Memory
Section titled “AI Memory”AI Memory (comp-ai-memory, AIMemoryComponent) gives the agent a memory that outlives the page. It names the persistable record that keeps it.
An AI Memory names the record that keeps the guide's memory between visits: a UI Switch turns it on and off, and the agent's memory activity events update a label.
Flip Remember me: the label shows whether the guide keeps a memory, and in which record. Reading and writing memory happen during replies, which need the AI service; this preview does not have it, so a message you send shows a short error instead. Drag outside the panels to orbit the camera.
| 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
Section titled “AI Summarizer”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 |
|---|---|
get |
{ access, available, reason? }, with access one of allowed, denied, unknown. Reading it starts nothing. |
generate |
Prepare a summary and wait for it. Resolves { job, or { status: 'empty', job when there is nothing to summarize yet. Rejects when it fails. getSummary is the same call. |
download |
Save the prepared summary as 'pdf' (default), 'txt' or 'md'. Generates nothing new. Resolves { status }: saved, initiated, missing or cancelled. |
get |
The latest job: { job, with state one of queued, running, ready, empty, failed, cancelled, expired. |
subscribe |
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.
Private Contexts
Section titled “Private Contexts”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 |
|---|---|
list |
Resolves { items: [{ id, updated. limit is 1 to 50, 20 by default. Creates and selects nothing. |
create |
Resolves a new Context. It does not select it. |
set |
Select a Context: the conversation and dialog now show it. |
get |
Resolves the selected Context, or checks an explicit id without selecting it. |
clear |
Remove the messages, observations and latest summary of a Context. Its id and selection stay. |
get |
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.
Examples
Section titled “Examples”1. A summary button
Section titled “1. A summary button”#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(); });}A UI Button asks the guide's AI Summarizer for a summary of the visitor's chat: the script checks availability first, then generates and downloads it, reporting each step in a label.
Press Download summary: without the AI service the label explains that summaries are not available, which is the script's first check. With the service, chat with the guide first, then the button saves a PDF. Drag outside the panels to orbit the camera, scroll to zoom.
- 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.
2. Cycle the output language
Section titled “2. Cycle the output language”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.
#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();}Pressing L steps an AI agent's output language through the languages its AI Translation allows, then back to the original, and logs each change from subscribeOutputLanguage.
Click the scene, then press L to change the language. The dialog's language button follows. Translating replies needs the AI service; choosing the language does not.
getOutputLanguage()gives the allowed languages in the AI Translation’s order, so the script never hard-codes them andsetOutputLanguagenever 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. subscribeOutputLanguagereports 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.
Snippets
Section titled “Snippets”1. A language menu
Section titled “1. A language menu”#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();}translatesTochecks the choice beforesetOutputLanguage, 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.
2. Translate a sign once
Section titled “2. Translate a sign once”#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); }}translateworks 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.
3. Start a fresh conversation
Section titled “3. Start a fresh conversation”#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)); });}createContextmakes a Context without selecting it;setContextswitches the conversation and dialog to it. The old Context stays and appears inlistContexts.- 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.
Common mistakes
Section titled “Common mistakes”- Expecting translation to change the conversation. The history, the Context and the model’s instructions stay in the original language. Read
canonicalTextontranslation-completedfor the original. - Setting a language the agent does not allow.
setOutputLanguagethrows. ChecktranslatesTofirst. - Downloading later. Call
downloadSummaryfrom 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
createContextdoes not switch. CallsetContextwith the new Context.