Skip to content

Logic and AI

Updated

The Logic and AI entities give a world memory and a voice. They draw little or nothing themselves: a Persistable keeps data that outlives the session, shared by every visitor, and an AI Agent is a character visitors talk to. Both are driven from Behavior scripts and report what happens to them as events.

An AI agent is an entity in your scene that people talk to: a museum guide who answers questions, a shopkeeper who explains the rules of a game, a receptionist who greets each visitor. It answers through a language model, and it can show its answers in a chat panel, speak them aloud, listen to a microphone, translate, remember, and call functions you write. Behavior scripts send it prompts, read its replies and react to every step of a conversation, so an agent can take part in your game logic instead of just sitting in a corner.

  • Persistable. A Persistable entity (ent-persistable) keeps data across reloads and sessions, shared by every visitor: a counter, a guest book, a high score, a puzzle’s state. See Persistence.
  • Agent. An AI Agent entity (ent-ai-agent). It is assembled from components: an AI Model that answers (always present) and any capabilities you add when the agent needs them. An agent carries only what it uses, and an unused capability costs nothing.
  • Conversation. Each agent has one shared conversation: the list of messages and replies that its dialog panel shows and that every script sees. A script gets it from the AI Model with getConversation().
  • Turn. One exchange: a prompt goes in, the agent thinks, writes and finishes a reply. Only one turn runs at a time in a conversation.
  • Prompt. The text that starts a turn. A message is ordinary visitor input and appears in the chat. A command is hidden input from your application, such as “The visitor just arrived; greet them”, that shows only the agent’s reply.
  • Response and streaming chunks. A reply arrives in pieces while the model writes it. Each piece is a chunk of new text, sent as an AIAgent::writing event; the full text arrives once at the end, as AIAgent::response.
  • Persona. The agent’s display name and standing instructions, sent to the model with every turn.
  • Proximity. A box around the agent that notices when the player’s camera walks in or out. It can open the dialog and send a greeting automatically.
  • Context and memory. The record of what a visitor and the agent said and observed. An agent can keep a private Context per visitor and, with AI Memory, keep it beyond the page.
  • Tool. A small script with functions the model may call while it answers, such as looking up opening hours or loading another scene.
  • Skill. A Markdown document of instructions the model can load when a situation calls for it, such as how to run a guided tour.

Asynchronous by nature. Both entities talk to a service outside the scene, so their scripting calls return promises: values that arrive later. Call them from an async function, wait with await, and wrap them in try/catch, because a service can be busy or unreachable. A Persistable’s writes reject when the service refuses them; an agent’s send throws while another turn is still running.

Events through a Signal Emitter. Neither entity sends anything to scripts on its own. Add a Signal Emitter to it, set its signal, and listen with on(signal, handler): a Persistable reports Persistable::change, cleared and error, including changes other visitors make, and an agent reports each step of a turn, from AIAgent::prompt to AIAgent::idle. See Events and signals.

The rest of this page is about agents.

An agent is an ordinary entity: it has a Transform, it lives in a scene, and you find it with findEntity. What makes it an agent is its components.

Component What it adds Read
AI Model Which model answers. Required, and the source of the conversation and of every agent event. Creating an agent
AI Persona A display name and standing instructions. Creating an agent
AI Dialog, AI Caption, AI Proximity The chat panel, live subtitles, and the walk-up box. Dialog and captions
AI Text To Speech, AI Speech To Text, AI Speech Capture A voice, speech recognition, and the choice of which scene audio is transcribed. Speech
AI Translation, AI Memory, AI Summarizer Answers in the visitor’s language, lasting memory, and a downloadable summary. Translation and memory
AI Tool Functions the model can call. Tools
AI Skill Instruction packs the model can load. Skills

A turn moves through the same steps whoever starts it:

  1. A prompt arrives. It comes from the dialog’s text field, from the microphone through Speech To Text, from a Proximity greeting, or from a script calling conversation.send(text).
  2. The agent thinks. The model receives the persona’s instructions, the conversation so far, and the skills and tools it may use. The agent sends AIAgent::thinking.
  3. The reply streams. Each chunk sends AIAgent::writing with just that chunk’s text. The dialog grows the reply as the chunks come in.
  4. The reply is complete. The agent sends AIAgent::response with the whole text, then AIAgent::idle: nothing is in flight and a new prompt can go in.
  5. Presentation follows. With translation on, the visitor sees the reply in their language. With a voice and Auto Speak, the reply is spoken and the agent sends AIAgent::talking when the audio starts.

A cancelled turn sends AIAgent::cancelled instead of a response, and a failed one sends AIAgent::error with a message safe to show the visitor. Both end with AIAgent::idle.

The agent sends these events to the Signal Emitters on its own entity, like every other component event. Add a Signal Emitter with a signal to the agent, then listen with on(signal, …) and compare event.eventType with the EventType.AIAgent constants.

This walkthrough builds a guide who greets the player when the scene starts, and logs the reply as it streams in.

  1. Add an AI Agent entity to the scene and name it Guide. It comes with an AI Model, which uses the application’s default model.

  2. Add an AI Persona to it. Set its name to Guide and its instructions to: You are the friendly guide of this gallery. Answer in two or three sentences.

  3. Add an AI Dialog to it. Leave presentation on always so the panel shows from the start, and turn on billboard so it faces the player.

  4. Add a Signal Emitter to the agent and set its signal to guide:ai. Without it, scripts hear nothing from the agent.

  5. Add a Behavior entity anywhere in the scene with this script:

    FirstAgent.jx
    #pragma lifecycle(startup)
    let reply = '';
    async function startup() {
    const guide = findEntity('Guide');
    const conversation = guide.getComponent(AIModelComponent).getConversation();
    if (!conversation) {
    log('The guide is not available here.');
    return;
    }
    on('guide:ai', (event) => {
    if (event.eventType === EventType.AIAgent.Thinking) reply = '';
    if (event.eventType === EventType.AIAgent.Writing) reply += event.data.text;
    if (event.eventType === EventType.AIAgent.Response) log('Guide said:', event.data.text);
    if (event.eventType === EventType.AIAgent.Error) log('Problem:', event.data.text);
    });
    try {
    await conversation.send('Hello! Who are you, and what can I see here?');
    } catch (error) {
    log('Could not ask the guide:', error.message);
    }
    }
  6. Enter play. The prompt appears in the dialog, the reply streams in under it, and the script log shows the finished answer. Type into the dialog’s field to keep talking.

What the script does:

  • getComponent(AIModelComponent).getConversation() returns the agent’s shared conversation, or undefined when the agent cannot run (in the editor, or with its AI Model switched off). Always check it.
  • The on('guide:ai', …) listener is registered before the prompt is sent, so it hears every step of the turn. Writing chunks are appended to reply: each carries only its own slice of text.
  • conversation.send(text) sends an ordinary message, exactly as if the visitor had typed it. It resolves when the turn ends and throws when a turn is already running or the agent is unavailable, so it sits in a try/catch.
If you want … Use … Read
To keep data across reloads and sessions, shared by every visitor: a counter, a guest book, a high score, a puzzle’s state Persistable Persistence
A character that answers visitors in its own words, with an optional chat panel, voice, subtitles, translation, memory and tools; one the player can type to AI Agent with AI Persona and AI Dialog Creating an agent
The panel to open when the player walks up AI Proximity, Dialog presentation: 'proximity' Dialog and captions
Subtitles of what is said AI Caption with AI Speech To Text Dialog and captions
The agent to speak its answers AI Text To Speech, Dialog autoSpeak Speech
Voice input from the microphone AI Speech To Text with the microphone source Speech
Answers in the visitor’s language AI Translation Translation and memory
Memory that outlives the page AI Memory Translation and memory
The agent to act in the world or fetch data AI Tool Tools
Detailed instructions for one kind of task AI Skill Skills
Your game logic to prompt the agent and react to replies The conversation and EventType.AIAgent Scripting AI
To keep working with a chat panel that an older scene placed on its own entity AI Dialog (new dialogs are an AI Dialog component on the agent) Dialog and captions

Each type has a page of its components, props, events and a first script:

EntityTypeWhat it is
AI Agentent-ai-agentWhich AI model answers for the agent; every agent needs one.
AI Dialogent-ai-dialogThe visible conversation interface of the agent.
Persistableent-persistableSaves the entity's state so it is kept between sessions.

Every Persistable and AI component and entity class is a script global, so you reach a component with agent.getComponent(AIModelComponent) and create one with new AIPersonaComponent({ … }).

GlobalWhat it is
PersistableComponentMarks an entity as persistable, and is the entity's handle on its stored state.
AIAgentEntityAn AI agent placed in the scene.
AIDialogEntityPresentation-only dialog. Its conversation comes from a separately referenced AI agent.
AIModelComponentWhich model answers for this agent.
AIPersonaComponentWho the agent is and how it should behave.
AIDialogComponentAI Dialog is presentation; its nodes are private, derived component resources.
AICaptionComponent
AIProximityComponentCamera-to-box membership with optional Agent prompts on entry and exit.
AITextToSpeechComponentOptional speech capability. Private audio never enters authored components or hierarchy.
AISpeechToTextComponentOptional microphone/VAD capability. Activation never requests microphone permission.
AISpeechCaptureComponentMarks audio through registration changes only; it never captures audio.
AITranslatorComponent
AIMemoryComponentWhere the agent's memory is kept.
AISummarizerComponentUser-requested personal summary; the host queues and authorizes its generation.
AIToolComponentA script exposing one or more tools an agent can call by name. Data only: in play mode the scripting runtime compiles it in a scope of its own and registers it in scripting.ai.tools. Switched off (this component, or its entity or an ancestor) it stays registered and does nothing when run; detached or unloaded with its scene, it is removed. Tools and behaviors never see each other.
AISkillComponentA unit of instruction an agent can draw on, written in Markdown. Markdown identity and description stay in content; the separate component name is only an authoring label. Bodies load on demand through the host.
AIFlowComponentAn optional editor view marker. Graphs remain derived; Player has no Flow work.
EventTypeEvery event type a script can hear, by who sends it: compare them rather than typing the strings.
ComponentTypeWhat it does
AI Captioncomp-ai-captionShows the owning Agent’s Speech To Text output as transient text.
AI Dialogcomp-ai-dialogThe visible conversation interface of the agent.
AI Flowcomp-ai-flowVisualize how your Agent’s AI components connect and work together.
AI Memorycomp-ai-memoryWhere the agent's memory is kept.
AI Modelcomp-ai-modelWhich AI model answers for the agent; every agent needs one.
AI Personacomp-ai-personaThe agent's name, personality and instructions.
AI Proximitycomp-ai-proximityDetects when the active camera enters or leaves this box.
AI Skillcomp-ai-skillA Markdown instruction pack the agent can use.
AI Speech Capturecomp-ai-speech-captureMarks this entity’s audio for Runtime Audio Speech To Text.
AI Speech To Textcomp-ai-speech-to-textUnderstands spoken input and detects when a person starts and stops talking.
AI Summarizercomp-ai-summarizerGenerates a personal summary of this Agent’s public and visitor Context on request.
AI Text To Speechcomp-ai-text-to-speechSpeaks the answers aloud.
AI Toolcomp-ai-toolA script with functions the agent can call.
AI Translationcomp-ai-translationAllowed visitor-local output languages, in fallback order.
Persistablecomp-persistableSaves the entity's state so it is kept between sessions.
Topic Description
Creating an agent The AI Agent entity, its model and persona, step by step and from a script.
Dialog and captions The chat panel, live subtitles, and the proximity box that opens them.
Speech A voice for the agent, speech recognition, and which scene audio is transcribed.
Translation and memory Output languages, lasting memory, visitor summaries and private Contexts.
Tools Functions the model can call, written with #pragma tool.
Skills Markdown instruction packs the model loads when they apply.
Scripting AI The conversation API, prompts and commands, and every agent event.
Persistence The Persistable: data that survives reloads and sessions, and how it differs from networking.