AI Powered NPC: How to Build One (With JavaScript Code)

By Arron R.11 min read
An AI powered NPC is a game character whose dialogue or choices come from a language model at runtime instead of a fixed script. The reliable recipe: a characte

An AI powered NPC is a non-player character whose lines, and sometimes whose choices, come from a language model while the game is running, instead of being picked from a dialogue tree a writer finished months earlier. You type or speak a question, the character answers in its own voice, and the conversation can go places nobody scripted. This guide explains how that works, which games already do it well, where it falls apart, and how to build one yourself with a short JavaScript example and an AI game engine that writes most of the plumbing for you.

What is an AI powered NPC?

An NPC (non-player character) is any character in a game that the player does not control: shopkeepers, quest givers, guards, enemies, companions. Games have had “AI” for decades, but it rarely meant anything like a thinking person. In game development, game AI usually refers to the systems that control NPC behaviour, built from techniques like state machines and pathfinding rather than true machine intelligence. Pac-Man’s ghosts are the classic example: each ghost chases you with its own targeting rule, and they switch between chasing and retreating to their corners.

When people say “AI powered NPC” today, they almost always mean something newer: a character connected to a large language model (LLM), the kind of AI that reads text and writes text back. The LLM gives the character open-ended conversation. You are no longer limited to the three dialogue options on screen; you can ask the blacksmith about her childhood, bargain over a sword, or try to trick her into revealing a secret.

That freedom is the whole appeal, and also the whole problem. A scripted NPC can never say something wrong because a human wrote every line. An AI powered NPC can say anything, including spoilers, nonsense, or lines that break the tone of your game. Building a good one is mostly about putting walls around that freedom.

How do AI NPCs work under the hood?

Every working AI NPC runs the same loop, whether it lives in a big studio game or a weekend jam project:

  1. Player input. The player types a line, or speaks one that a speech-to-text system turns into text.
  2. Context assembly. Your code builds a prompt: who the character is, what they know, what is happening in the game right now, and the last few lines of conversation.
  3. Model call. The prompt goes to a language model, which writes a reply.
  4. Validation. Your code checks the reply: is it the right length, the right format, and does it ask for an action the game allows?
  5. Game acts. The game shows the line, optionally plays it through text-to-speech, and runs any approved action such as opening a shop or starting a quest.

It helps to think of the character as having two halves. The “mouth” is the language model: it handles conversation. The “body” is ordinary game code: movement, combat, pathfinding, a finite-state machine (a simple system where the character is always in one named state, such as idle, talking or fleeing, with rules for switching). Most good designs keep the body fully under your control and let the model influence it only through a small menu of allowed actions.

That split is the single most useful idea in this article. The model talks; the game decides.

Diagram of the AI NPC loop from player input through context, model, validation and game action
The model writes the line; your game code decides what actually happens.

Games with AI NPCs you can play today

Before building one, it is worth seeing what already works. A few patterns show up across the games and mods doing this well.

  • Sandbox simulations. AI People from GoodAI is a sandbox where you set up scenarios and talk to NPCs by microphone or keyboard, while the NPCs also interact with each other on their own. The fun is emergent: you watch what the characters do.
  • Survival and RPG experiments. Hunter Moonstrike is a survival game built around AI NPCs, where each character has its own story you can uncover by talking to them.
  • Interrogation and mystery games. A growing number of titles let you question suspects in your own words. This is the cleanest fit for language models, because asking the right question is the gameplay.
  • Mods for existing games. Skyrim AI NPC mods connect the game’s existing characters to language models and synthetic voices, so you can chat with characters who originally had a few fixed lines. Police roleplay communities around mods like LSPDFR experiment with the same idea for traffic stops and witnesses.
  • Big releases. Some large commercial games, such as Where Winds Meet, include chat-style conversations with NPCs, and there is plenty of speculation about what future blockbusters will do. Judge any game with AI NPC features by what actually ships, not by trailers.

The idea is older than LLMs. Façade, released in 2005, let players type freely to two characters in an interactive drama, long before modern models existed.

Here is how AI conversation compares with classic scripting for common NPC jobs:

NPC jobAI conversationClassic script
Suspect in a mysteryExcellent: free questioning is the gameLimited to pre-written questions
Companion small talkStrong: varied, reactive chatterRepeats quickly
Critical quest giverRisky: may skip or garble key infoReliable: always says the right thing
Shopkeeper bargainingFun if prices are enforced in codePredictable menus
Combat enemyRarely useful: too slow per decisionBest choice: state machines, behaviour trees

The pattern: use language models where words are the gameplay, and keep scripts where correctness matters.

How to build an AI powered NPC, step by step

Here is the practical recipe, using a village blacksmith called Mara as the running example.

Step 1: Give the NPC a job in the game loop

Decide what talking to this character changes. Mara can open her shop, offer a quest, or do nothing. If the conversation cannot change anything, players will notice quickly and stop talking. The job also tells you which actions to allow later.

Step 2: Write a short character sheet

Give the model a name, a role, a personality in one line, a list of facts the character knows, and a list of things the character must never do. Keep it short. Long, flowery backstories make the model ramble and drift.

Step 3: Feed it game state, not the whole world

Pass only what this NPC should know right now: the current quest stage, the player’s gold, the time of day. If you dump the whole world into the prompt, the NPC will happily spoil the ending.

Step 4: Force structured output

Ask the model to reply only in JSON with fixed fields: the line to say and one action from a fixed list. Structured output is what turns a chatbot into a game system, because your code can check it.

Step 5: Keep the API key on a server

Never put a model API key in browser code; anyone can read it. Send the prompt to your own small server endpoint, which adds the key and calls the model.

Step 6: Add a timeout and a fallback

Models are sometimes slow, sometimes down and sometimes return broken JSON. Every AI powered NPC needs a hand-written fallback line so the game never freezes or crashes mid-conversation.

Here is the whole recipe in plain JavaScript, ready to drop into a browser game built with Phaser, Three.js or plain canvas:

const mara = {
  name: "Mara",
  role: "village blacksmith",
  personality: "gruff, honest, secretly proud of her work",
  knows: ["the north bridge collapsed last week", "iron is scarce this season"],
  never: ["mention the modern world", "reveal who broke the bridge"],
};

const ALLOWED_ACTIONS = new Set(["none", "open_shop", "give_quest"]);

function buildPrompt(npc, state, history, playerLine) {
  return [
    `You are ${npc.name}, the ${npc.role}. Personality: ${npc.personality}.`,
    `You only know these facts: ${npc.knows.join("; ")}.`,
    `Never: ${npc.never.join("; ")}.`,
    `Game state: quest=${state.quest}, playerGold=${state.gold}, time=${state.time}.`,
    `Recent conversation:\n${history.slice(-6).join("\n")}`,
    `Reply ONLY with JSON: {"say": "under 40 words", "action": "none" | "open_shop" | "give_quest"}`,
    `Player says: "${playerLine}"`,
  ].join("\n");
}

async function talkToNpc(npc, state, history, playerLine) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 4000);
  try {
    const res = await fetch("/api/npc", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ prompt: buildPrompt(npc, state, history, playerLine) }),
      signal: controller.signal,
    });
    if (!res.ok) throw new Error("HTTP " + res.status);
    const data = await res.json(); // your server returns { text: "..." }
    const reply = JSON.parse(data.text);
    const words = typeof reply.say === "string" ? reply.say.split(/\s+/).length : 0;
    if (words === 0 || words > 60 || !ALLOWED_ACTIONS.has(reply.action)) {
      throw new Error("Invalid reply shape");
    }
    return reply;
  } catch (err) {
    console.warn("NPC fallback:", err.message);
    return { say: "Hm. Ask me again when the forge is quiet.", action: "none" };
  } finally {
    clearTimeout(timer);
  }
}

// The game, not the model, decides what actually happens.
async function onPlayerSays(line, state, history) {
  const reply = await talkToNpc(mara, state, history, line);
  history.push(`Player: ${line}`, `${mara.name}: ${reply.say}`);
  showDialogue(mara.name, reply.say);
  if (reply.action === "open_shop") openShop("blacksmith");
  if (reply.action === "give_quest" && state.quest === "none") startQuest("fix_bridge");
}

Notice the last two lines. The model can ask to give a quest, but the game only starts it if the quest has not already begun. That one check prevents a whole class of bugs. Swap showDialogue, openShop and startQuest for your own functions.

Keeping an AI powered NPC on script: guardrails, cost and latency

A demo NPC takes an afternoon. A shippable one takes guardrails. These are the issues that separate the two.

Guardrails

  • Knowledge limits. The character sheet’s “knows” list is a ceiling, not a hint. Repeat in the prompt that the character does not know anything else and should say so in character.
  • Length limits. Players skim. Cap replies at a sentence or two and enforce the cap in code, not just in the prompt.
  • Action whitelists. The model picks from a menu; it never invents actions or item IDs.
  • Content filtering. If players can type anything, some will try to make your NPC say awful things. Filter player input and model output, and keep a polite in-character deflection ready.

Memory

Sending the full conversation every turn gets slow and expensive. Keep the last few exchanges, plus a short summary of anything important (“the player insulted Mara’s work”). Store that summary in your save file so the character remembers across sessions.

Latency

Waiting a few seconds for a reply feels long in a game. Hide it: play a short “thinking” animation, show a quick scripted bark (“Hmph…”) immediately, or stream the reply word by word if your setup supports it.

Cost and offline play

Cloud models charge per use, so cost grows with every player and every line. That is fine for a jam game or a small audience, and something to plan for if your game takes off. Small local models avoid per-use charges and work offline, but they are usually weaker at staying in character and need decent hardware on the player’s side.

Quality

Players have become sharp at spotting generic machine-written text, the kind of low-effort output now widely called AI slop. A narrow, well-written character with a strong voice beats an NPC that can talk about anything blandly. Write sample lines into the character sheet so the model has a voice to copy.

Character sheet and validated JSON reply used to keep an AI NPC on script
A tight character sheet plus strict output checks keeps the NPC in character.

Building an AI powered NPC with WizardGenie

Everything above is a fair amount of plumbing: a dialogue UI, a prompt builder, a server proxy, validation, fallbacks, save data. That is where WizardGenie, the AI game engine inside Sorceress, does the heavy lifting. You describe the game you want in plain language, and WizardGenie writes the code, runs it and iterates on it with you. It is a game engine you steer by conversation rather than by menus, which makes it a natural fit for vibe coding an NPC system without hand-writing every function.

WizardGenie runs on the web with nothing to install, and as a Windows desktop app with an auto-updater that gives you native file access and longer agent sessions, which helps on bigger projects. It works with the leading AI coding models, and you can switch models with your own API key.

A good first request reads like a design brief, not a wish:

Make a top-down village game. Add a blacksmith NPC called Mara with a typed chat box. Build her prompt from a character sheet (knows / never lists) and the current quest state. She must reply in JSON with a “say” line under 40 words and an action from: none, open_shop, give_quest. Validate every reply, use a fallback line on errors or after a 4 second timeout, and keep the model API key on a small server endpoint, not in the browser.

From there you iterate the way you would with a senior developer: “Mara forgets the player insulted her, add a memory summary to the save file,” or “show a hammering animation while she thinks.” Because you wrote the rules into the brief, the guardrails end up in the code instead of being bolted on later.

A talking character also needs a face and a voice. The rest of Sorceress covers that:

  • Auto-Sprite v2 (Pro) generates game-ready 2D characters with any animation in any art style, so Mara can idle, hammer and react.
  • 3D Studio turns a typed idea into a fully rigged, animated, game-ready 3D character if your game is 3D. A rig is the internal skeleton that lets a model move.
  • Sound Studio handles music, sound effects and text-to-speech with lifelike AI voices and voice cloning, plus an editor for trimming, so your NPC’s generated lines can be spoken aloud.
  • The Sorceress API gives WizardGenie or another coding agent one key to generate sprites, 3D models, rigs, animation, music and SFX from inside your workflow.

When the game is ready, export the build and host it wherever you like. For a full map of what each tool does, see the Sorceress tools guide. If you want a companion-style character rather than a quest NPC, the guide to building an NPC girlfriend AI covers memory and personality in more depth.

Common mistakes when making AI NPCs

  • Letting the model run the game. If the model decides whether a quest is complete or how much gold to give, players will talk their way into anything. Keep rules in code.
  • Giving every NPC a language model. One or two conversational characters with real jobs beat a town of chatty extras who all sound alike. Script the rest.
  • No fallback. The first time the API times out at a game jam presentation, you will wish you had written one line of backup dialogue.
  • Exposing the API key. Anything in browser JavaScript is public. Always proxy through a server.
  • Overlong prompts. More backstory does not mean better acting. Short sheets with sample lines keep the voice sharp.
  • Testing only polite questions. Players will try to break your NPC on minute one. Test rude, off-topic and manipulative inputs before anyone else does.
  • Critical info behind free chat. If a player must learn where the key is, show it in a scripted line or quest log too. Do not trust the model to mention it.

The workflow at a glance

  1. Pick one NPC whose conversation is the gameplay: a suspect, a merchant, a companion.
  2. Write a short character sheet with what they know, what they never say and a few sample lines.
  3. Pass trimmed game state and recent conversation into the prompt.
  4. Force JSON output with a fixed list of actions, and validate every reply in code.
  5. Keep the API key on a server, add a timeout and a hand-written fallback.
  6. Hide latency with animation or a quick bark, and save a memory summary between sessions.
  7. Build it fast with WizardGenie, give the character art with Auto-Sprite v2 or 3D Studio, and a voice with Sound Studio.

An AI powered NPC is not magic; it is a language model inside a cage your game code builds. Get the cage right and you get characters players remember. If you are planning to try one under time pressure, the guide to finishing a game at the Global Game Jam is a good companion read.

Frequently Asked Questions

What is an AI powered NPC?

It is a non-player character whose dialogue, and sometimes whose decisions, are generated by a language model while the game runs. Instead of choosing from a fixed dialogue tree, the player types or speaks freely and the character answers in its own voice. The best versions still let the game code control quests, items and combat, and use the model only for what the character says.

Which games have AI NPCs?

AI People from GoodAI is a sandbox where you set up scenarios and talk to autonomous NPCs by microphone or keyboard. Hunter Moonstrike is a survival game where every NPC has its own story. There are also community mods for older games, such as Skyrim AI NPC mods, that connect existing characters to language models and synthetic voices. Many indie and game-jam projects use the idea too.

Can an AI NPC work offline?

Yes, if you run a small language model locally on the player’s machine instead of calling a cloud API. The trade-off is quality and hardware: local models are usually weaker at staying in character and need a decent GPU or CPU budget. Many developers prototype with a cloud model, then decide later whether a local model is good enough for their game.

How do you stop an AI NPC from breaking character?

Give it a short character sheet with what it knows and what it must never say, pass only the game state it needs, cap reply length, and ask for structured JSON output. Then validate every reply in code: reject unknown actions, enforce word limits and fall back to a hand-written line if anything fails. The model suggests; the game decides.

Do I need to code to make an AI NPC?

Not necessarily. An AI game engine such as WizardGenie lets you describe the game and the NPC system in plain language, then writes and runs the code for you. You still need to understand the design: what the NPC knows, what it is allowed to do, and what happens when the model is slow or wrong. That design work is where good AI NPCs come from.

Sources

  1. Artificial intelligence in video games — Wikipedia
  2. Game engine — Wikipedia
  3. AI slop — Wikipedia
  4. Vibe coding — Wikipedia
Written by Arron R.·2,702 words·11 min read

Related posts