🎮✨ NPC Genie: AI-Powered Character Generator for Game Devs


Google Generative AI Capstone Blog
"80% of indie game developers struggle with NPC diversity... and players notice."
🧠 The Problem: Flat NPCs Ruin Immersion
Creating compelling NPCs is a time-consuming task, especially for small teams or solo developers. Most games suffer from:
😴 Repetitive Characters: Same archetypes reused across worlds
⚖️ Unbalanced Stats: Leads to broken or unfair gameplay
📜 Weak Backstories: Generic or cliché lore that breaks immersion
🚀 Our Solution: NPC Genie
NPC Genie is an AI-powered toolkit that lets game devs instantly generate diverse, lore-rich, and stat-balanced characters with minimal input.
All you need to do is describe your game world, and we’ll give you:
🧬 2-3 Sentence Backstories
⚔️ Balanced RPG Stats (in JSON)
💬 Signature Dialogue Styles
🔍 RAG-based Similarity Search (WIP)
⚙️ Tech Stack
🧠 Google GenAI (Gemini 2.0 Flash)
🧱 LangChain + Pydantic
🧰 FAISS for similarity search
🔐 Kaggle Secrets + Python for API calls
📦 Step 1: Install Dependencies
!pip uninstall -qqy kfp
!pip install -qU "google-genai==1.7.0" "langchain" "pydantic" "faiss-cpu" "python-dotenv" "pandas" "langchain-core" "langchain-google-genai" "langchain_community"
🔐 Step 2: Setup API Key (Kaggle)
from kaggle_secrets import UserSecretsClient
GOOGLE_API_KEY = UserSecretsClient().get_secret("GOOGLE_API_KEY")
🧙 Step 3: Generate NPCs with Gemini
🧪 Few-Shot Prompting
We use a few-shot system to teach Gemini how good characters look:
few_shot_examples = """
Game World: Steampunk Metropolis
NPC 1:
- Name: Viktoria Gearspark
- Race: Human (Cyborg)
- Role: Inventor
- Stats: {"int":18, "dex":14}
- Backstory: "Lost her legs in an airship accident, now builds prosthetics for the poor."
- Dialogue: Technical but compassionate
- Secret: "Actually designs weapons for the underground resistance."
"""
🎯 Output Enforcement via Pydantic
from pydantic import BaseModel, Field
from typing import List, Dict
class NPC(BaseModel):
name: str
race: str
role: str
stats: Dict[str, int]
backstory: str
dialogue_style: str
secret: str
class NPCList(BaseModel):
npcs: List[NPC]
🧪 Structured Prompt + Error Handling
def generate_npcs(world_description: str, npc_count: int = 3) -> NPCList:
prompt = f"""
You are an RPG character generator.
Generate {npc_count} NPCs for the game world:
"{world_description}"
Output structured JSON with fields: name, race, role, stats (1-20), backstory, dialogue_style, secret.
Examples:
{few_shot_examples}
"""
response = model.generate_content(prompt)
cleaned_text = re.sub(r"^```json\s*|```$", "", response.text.strip(), flags=re.MULTILINE).strip()
parsed_json = json.loads(cleaned_text)
try:
return NPCList(**parsed_json)
except ValidationError:
print("🛑 Invalid NPC data! Retrying...")
return generate_npcs(world_description, npc_count)
💡 Example Use Case
world_desc = "Cyberpunk slum with hacker clans"
npc_count = 3
npcs = generate_npcs(world_desc, npc_count)
Output (sample):
{
"npcs": [
{
"name": "Echo Burn",
"race": "Modified Human",
"role": "Signal Sniper",
"stats": {"dex": 17, "int": 15},
"backstory": "Former radio DJ turned sniper after the towers fell.",
"dialogue_style": "Sarcastic, poetic",
"secret": "Still broadcasts secret messages to rebels."
},
...
]
}
🖼️ Bonus: Portrait Generation
Using image prompts from the generated traits, we feed Gemini’s image model to create stylized NPC art:
def generate_npc_portrait(npc: NPC):
contents = f"""
Create a 4K fantasy portrait for this character:
- Name: {npc.name}
- Race: {npc.race}
- Role: {npc.role}
- Dialogue Style: {npc.dialogue_style}
- Secret (hint only): {npc.secret[:50]}...
"""
⚖️ Limitations
While NPC Genie saves hours of manual work, there are some known issues:
- 🔁 Hallucinations: Rarely returns non-JSON or invalid characters
- 📊 Stat Inconsistency: Slight imbalance in stat distribution over many runs
- 🧠 World Consistency: Gemini sometimes mixes genres if world prompt is vague
🔮 Future Possibilities
We’ve already explored RAG-powered lore embedding and NPC similarity search — but there’s still so much more to build:
🧩 Multi-turn Character Refinement
🧠 Interactive World Expansion
🎮 Game Engine Integration
🌐 Collaborative NPC Worlds
👤 Author & Resources
Seif Khaled
AI enthusiast & software engineer passionate about blending storytelling with tech.
Subscribe to my newsletter
Read articles from Seif Khaled directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
