Back to Blog
·Summer Team

How to Build AI NPCs with Memory and Personality in Godot 4

Learn how to create NPCs that remember players, stay in character, and react dynamically using AI in Godot 4.

NPCs in most games are state machines. They patrol a path, detect the player, switch to attack mode, and loop back. That works for enemies, but it falls apart for characters that are supposed to feel alive.

A shopkeeper who says the same three lines no matter what you have done in the game. A quest giver who does not acknowledge that you saved their village last week. A companion who forgets every conversation the moment it ends.

AI changes what is possible here. Not by replacing game design with chatbots, but by adding layers of memory, personality, and dynamic response on top of traditional NPC systems.

What AI NPCs Actually Are

An AI NPC is not a chatbot pasted into a game world. That is the most common misconception, and it leads to NPCs that feel disconnected from the game they exist in.

A well-built AI NPC combines language models with game systems. It has:

  • A personality prompt that defines how it speaks, what it cares about, and how it reacts to different situations. A gruff blacksmith talks differently than a nervous apprentice.
  • A memory system that tracks interactions with the player. What was said, what was traded, what quests were given and completed.
  • Goals and motivations that influence behavior. A merchant wants to make money. A guard wants to protect the town. A thief wants to avoid getting caught.
  • Game world awareness so it can reference actual events, items, locations, and other characters. "I heard you cleared the bandits from the eastern road" only works if the NPC can query the game state.

The result is a character that stays consistent, remembers context, and responds to the player in ways that feel natural and grounded in the game world.

The Three Layers of an AI NPC

Every AI NPC can be broken down into three distinct layers. You can implement all three, or start with just one or two.

Layer 1: Behavior

This is traditional game AI. Patrol routes, reaction triggers, combat logic, daily schedules. A behavior tree or state machine handles the NPC's physical actions in the world.

This layer runs locally with no internet connection needed. It is deterministic and predictable. The blacksmith stands at the forge during the day and goes home at night. The guard patrols the walls. The merchant opens the shop at dawn.

In Godot 4, you would typically implement this with an AnimationTree for state transitions, Area3D nodes for detection zones, and a script that manages the state machine or behavior tree.

enum State { IDLE, WORKING, SLEEPING, TALKING }
var current_state: State = State.IDLE
var schedule: Dictionary = {
    6: State.WORKING,
    20: State.IDLE,
    22: State.SLEEPING
}

This layer is the foundation. Even if you add AI conversation and memory, the behavior layer keeps the NPC grounded in the game world with consistent, reliable actions.

Layer 2: Conversation

This is where LLMs come in. Instead of selecting from pre-written dialogue lines, the NPC generates responses based on its personality, the current context, and the conversation history.

The personality prompt is the most important piece. It defines the character's voice, knowledge, and boundaries:

You are Tormund, a blacksmith in the village of Ashford.
You are gruff but fair. You take pride in your craft.
You charge reasonable prices and give discounts to repeat customers.
You have a side quest: you need rare ore from the northern mines
to forge a legendary blade. You will ask trusted customers for help.
You know about: village gossip, weapon quality, mining locations.
You do not know about: magic, politics, events outside Ashford.

The conversation layer needs an AI model. This can be a cloud API (OpenAI, Anthropic, Google) or a local model running through Ollama. Local models have higher latency but zero ongoing cost and complete privacy.

A key design decision: the NPC's responses must be bounded. An unconstrained chatbot will hallucinate locations that do not exist, reference items the game does not have, or break character entirely. The personality prompt, combined with a system that injects current game state, keeps responses grounded.

Layer 3: Memory

Memory is what separates a convincing AI NPC from a novelty. Without memory, every conversation starts fresh. The NPC has no idea who the player is or what happened before.

A memory system tracks:

  • Interaction history: What the player said, what the NPC responded, and when it happened.
  • Relationship state: Does the NPC trust the player? Are they friendly, neutral, or hostile?
  • Key events: The player completed a quest for this NPC. The player stole from their shop. The player saved their child from danger.
  • Shared knowledge: Information the player revealed. "I am looking for the lost temple" becomes something the NPC can reference later.

Memory storage can be simple. A JSON file or a SQLite database works fine for most games. The critical part is how memories are retrieved and injected into the conversation context.

var memories: Array[Dictionary] = []

func add_memory(event: String, importance: float) -> void:
    memories.append({
        "event": event,
        "importance": importance,
        "timestamp": Time.get_unix_time_from_system(),
    })

func get_relevant_memories(context: String, limit: int = 5) -> Array:
    # Sort by importance and recency, return top memories
    var sorted = memories.duplicate()
    sorted.sort_custom(func(a, b):
        return a.importance * _recency_weight(a.timestamp) > \
               b.importance * _recency_weight(b.timestamp)
    )
    return sorted.slice(0, limit)

When the player talks to the NPC, relevant memories get pulled and included in the prompt. "The player helped you find rare ore three days ago. You are grateful and offered a discount." The LLM uses this context to generate a response that acknowledges the shared history.

Memory persists across sessions. When the player loads their save, the NPC still remembers everything. This is what makes AI NPCs feel genuinely different from scripted ones.

Building AI NPCs in Summer Engine

Summer Engine makes this process conversational. Instead of wiring up each layer manually, you describe the NPC you want:

"Add a blacksmith NPC named Tormund. He is gruff but fair, charges reasonable prices, and has a side quest about finding rare ore in the northern mines. He remembers past transactions and gives discounts to repeat customers."

The engine creates:

  • The NPC node with a CharacterBody3D, collision shape, and mesh
  • A behavior tree with daily schedule (works at forge during day, goes home at night)
  • A conversation system with personality prompt based on your description
  • A memory store that tracks player interactions and transaction history
  • A shop interface with pricing logic that factors in relationship status

You can refine any of these components through conversation. "Make Tormund more suspicious of strangers" adjusts the personality prompt and initial relationship state. "Add a combat reaction so he fights back if attacked" extends the behavior tree.

Because Summer Engine is compatible with Godot 4, the generated systems use standard Godot nodes and GDScript. You can inspect and modify everything the engine creates. The AI NPC is not a black box; it is a collection of nodes, scripts, and resources that you own.

AI NPCs vs Scripted NPCs

Both approaches have legitimate uses. The right choice depends on your game.

Scripted NPCs:

  • Completely predictable. You control every word they say.
  • Work offline with zero runtime cost.
  • Easier to test and QA since behavior is deterministic.
  • Scale well. A hundred scripted NPCs cost the same as one.
  • Limited by the content you write. Players exhaust dialogue quickly.

AI NPCs:

  • Dynamic and responsive. Every conversation is unique.
  • Remember context across interactions.
  • Can handle unexpected player input gracefully.
  • Higher runtime cost (API calls or local model inference).
  • Harder to test since responses vary.
  • Risk of breaking character or generating inappropriate content without proper guardrails.

The hybrid approach works best for most games. Use scripted behavior for the base layer: patrol routes, combat logic, daily schedules, and critical story moments. Use AI for the conversation and memory layers, where dynamic responses add the most value.

A quest-critical NPC might have scripted dialogue for key story beats but AI-powered responses for everything else. The player always gets the information they need to progress, while also having the freedom to ask questions and build a relationship with the character.

Getting Started

The RPG templates in Summer Engine come with AI NPC systems ready to customize. Describe the characters you want and the engine builds them with personality, memory, and game world awareness.

If you want to explore AI NPC generation, check out the AI NPC generator or download Summer Engine to build your first AI-powered characters.