Create intelligent, memorable NPCs with personality, memory, and dynamic quest generation powered by LLMs
An advanced AI-powered NPC system that brings RPG characters to life with intelligent dialogue, persistent memory, distinct personalities, and dynamic quest generation. Built with FastAPI, Redis, and LLM integration (OpenAI/Ollama).
- Natural language processing via OpenAI GPT or local Ollama models
- Context-aware responses based on conversation history
- NPCs remember previous interactions with players
- 6 Distinct Personality Types:
- ๐ Friendly - Warm, helpful, and enthusiastic
- ๐ Aggressive - Hostile and confrontational
- ๐ฎ Mysterious - Cryptic and enigmatic
- ๐ฐ Merchant - Business-minded and persuasive
- ๐ง Wise - Knowledgeable and mentor-like
- ๐ Comedic - Humorous and witty
- Redis-powered memory storage
- Conversation history tracking (last 50 messages)
- Player reputation system (-100 to +100)
- NPC statistics and interaction counts
- AI-generated quests tailored to NPC personality
- Customizable difficulty levels
- Context-aware quest creation
- Structured quest objectives and rewards
- Docker containerization
- Docker Compose for easy deployment
- Scalable architecture
- RESTful API design
- Docker & Docker Compose
- OpenAI API key (or Ollama for local LLM)
git clone https://github.com/EchoSingh/NPC.git
cd NPC
# Create environment file
cp .env.example .env
# Add your OpenAI API key to .env
nano .envEdit .env file:
# For OpenAI (Cloud)
OPENAI_API_KEY=your_openai_key_here
OPENAI_MODEL=gpt-3.5-turbo
# For Ollama (Local) - Alternative
USE_OLLAMA=false
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=llama2Option A: Using Docker Compose (Recommended)
# Build and start services
docker-compose up --build -d
# View logs
docker-compose logs -fOption B: Using Pre-built Docker Image
# Pull from Docker Hub
docker pull aditya26062003/ai-npc-system:latest
# Run with docker-compose
docker-compose up -dThe API will be available at: http://localhost:8000
curl http://localhost:8000Expected response:
{
"status": "online",
"message": "AI NPC System is running",
"version": "1.0.0"
}- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- API Reference - Complete API documentation
- Examples & Usage - Ready-to-use NPC examples
- Contributing Guide - How to contribute
POST /npcExample Request:
{
"npc_id": "blacksmith_01",
"name": "Thorin Ironforge",
"personality": "friendly",
"background": "A master blacksmith who has crafted weapons for heroes across the realm. Loves sharing stories of legendary battles.",
"location": "Town Forge"
}Response:
{
"npc_id": "blacksmith_01",
"name": "Thorin Ironforge",
"personality": "friendly",
"background": "A master blacksmith...",
"location": "Town Forge",
"conversation_count": 0
}POST /chatExample Request:
{
"player_id": "player_123",
"npc_id": "blacksmith_01",
"message": "Hello! Can you repair my sword?"
}Response:
{
"npc_response": "Ah, greetings friend! Of course I can repair your sword! Let me take a look at it. I've been smithing for over 30 years, and I haven't seen a blade I couldn't fix yet!",
"npc_emotion": "friendly",
"quest_offered": false
}POST /quest/generateExample Request:
{
"player_id": "player_123",
"npc_id": "blacksmith_01",
"context": "Player needs a legendary weapon"
}Response:
{
"quest_id": "a7b3c9d1-e4f5-6789-g0h1-i2j3k4l5m6n7",
"title": "The Lost Mithril Ore",
"description": "Deep in the Shadowmount Mines lies a vein of pure mithril ore. Bring it back and I'll forge you a weapon of legend.",
"difficulty": "hard",
"reward": "Legendary Weapon + 500 Gold",
"objectives": [
"Travel to Shadowmount Mines",
"Defeat the mine guardians",
"Extract pure mithril ore",
"Return to Thorin Ironforge"
]
}GET /reputation/{player_id}/{npc_id}Response:
{
"player_id": "player_123",
"npc_id": "blacksmith_01",
"reputation": 15,
"level": "Friendly"
}GET /history/{player_id}/{npc_id}?limit=10โโโโโโโโโโโโโโโโโโโ
โ Game Client โ
โโโโโโโโโโฌโโโโโโโโโ
โ HTTP/REST
โผ
โโโโโโโโโโโโโโโโโโโ
โ FastAPI Server โ
โ (Port 8000) โ
โโโโโโฌโโโโโโโโฌโโโโโ
โ โ
โ โโโโโโโโโโโโโโโโ
โผ โผ
โโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
โ Redis โ โ LLM Service โ
โ (Memory) โ โ OpenAI/Ollamaโ
โโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
| Component | Technology | Purpose |
|---|---|---|
| API Server | FastAPI | RESTful endpoints, request handling |
| Memory Store | Redis | Persistent NPC memory & conversations |
| LLM Engine | OpenAI/Ollama | Natural language generation |
| Personality Engine | Python | Character trait management |
| Quest Generator | LLM-powered | Dynamic quest creation |
# Create merchant
curl -X POST http://localhost:8000/npc \
-H "Content-Type: application/json" \
-d '{
"npc_id": "merchant_01",
"name": "Sly Pete",
"personality": "merchant",
"background": "A cunning trader who always has rare items... for the right price.",
"location": "Market Square"
}'
# Chat with merchant
curl -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{
"player_id": "player_456",
"npc_id": "merchant_01",
"message": "What rare items do you have?"
}'# Create guard
curl -X POST http://localhost:8000/npc \
-H "Content-Type: application/json" \
-d '{
"npc_id": "guard_01",
"name": "Captain Brutus",
"personality": "aggressive",
"background": "A battle-hardened guard who doesn'\''t tolerate nonsense.",
"location": "City Gates"
}'# Create wizard
curl -X POST http://localhost:8000/npc \
-H "Content-Type: application/json" \
-d '{
"npc_id": "wizard_01",
"name": "Eldrin the Ancient",
"personality": "wise",
"background": "An ancient wizard with centuries of magical knowledge.",
"location": "Tower of Mysteries"
}'
# Generate quest from wizard
curl -X POST http://localhost:8000/quest/generate \
-H "Content-Type: application/json" \
-d '{
"player_id": "player_789",
"npc_id": "wizard_01",
"context": "Player seeks magical training"
}'NPC/
โโโ app/ # Application source code
โ โโโ main.py # FastAPI routes & endpoints
โ โโโ models.py # Pydantic data models
โ โโโ memory.py # Redis memory manager
โ โโโ personality.py # NPC personality engine
โ โโโ llm_service.py # LLM integration
โ โโโ config.py # Configuration management
โโโ docs/ # Documentation
โ โโโ API.md # Complete API reference
โ โโโ EXAMPLES.md # Usage examples
โ โโโ CONTRIBUTING.md # Contribution guidelines
โโโ scripts/ # Helper scripts
โ โโโ create_examples.sh # Create sample NPCs
โ โโโ setup.sh # Quick setup script
โโโ docker-compose.yml # Docker orchestration
โโโ Dockerfile # Container image
โโโ requirements.txt # Python dependencies
โโโ README.md # This file
# Create virtual environment
python -m venv venv
source venv/bin/activate # Linux/Mac
# or
venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt
# Start Redis (separate terminal)
redis-server
# Configure environment
cp .env.example .env
# Edit .env with your settings
# Run development server
python -m app.main
# or
uvicorn app.main:app --reload# Install Ollama
curl https://ollama.ai/install.sh | sh
# Pull a model
ollama pull llama2
# Update .env
USE_OLLAMA=true
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=llama2
# Run the application
docker-compose upNPC/
โโโ app/
โ โโโ main.py # FastAPI application & routes
โ โโโ config.py # Configuration management
โ โโโ models.py # Pydantic models
โ โโโ memory.py # Redis memory manager
โ โโโ personality.py # Personality engine
โ โโโ llm_service.py # LLM integration
โโโ docker-compose.yml # Docker orchestration
โโโ Dockerfile # Container image
โโโ requirements.txt # Python dependencies
โโโ .env.example # Environment template
โโโ README.md # Documentation
- Best for: Shopkeepers, innkeepers, helpful villagers
- Traits: Warm, enthusiastic, helpful
- Example NPC: Friendly tavern owner, village healer
- Best for: Guards, bandits, rival warriors
- Traits: Hostile, confrontational, intimidating
- Example NPC: Gate guard, enemy faction leader
- Best for: Prophets, fortune tellers, shadowy figures
- Traits: Cryptic, enigmatic, philosophical
- Example NPC: Oracle, mysterious stranger
- Best for: Traders, shop owners, negotiators
- Traits: Business-minded, persuasive, opportunistic
- Example NPC: Traveling merchant, auction house owner
- Best for: Mentors, scholars, elders
- Traits: Knowledgeable, patient, thoughtful
- Example NPC: Master wizard, village elder
- Best for: Jesters, comic relief characters
- Traits: Humorous, witty, playful
- Example NPC: Town jester, quirky inventor
- Duration: 7 days
- Capacity: Last 50 messages per player-NPC pair
- Format: Timestamped with context
- Range: -100 (Enemy) to +100 (Trusted Ally)
- Levels:
- 51-100: Trusted Ally
- 1-50: Friendly
- 0: Neutral
- -1 to -50: Disliked
- -51 to -100: Enemy
- Polite language: +2 per positive keyword
- Rude language: -3 per negative keyword
- Personality modifiers applied
- Impacts NPC responses and quest availability
| Variable | Description | Default |
|---|---|---|
OPENAI_API_KEY |
OpenAI API key | - |
OPENAI_MODEL |
OpenAI model name | gpt-3.5-turbo |
USE_OLLAMA |
Use Ollama instead of OpenAI | false |
OLLAMA_BASE_URL |
Ollama server URL | http://localhost:11434 |
OLLAMA_MODEL |
Ollama model name | llama2 |
REDIS_HOST |
Redis hostname | redis |
REDIS_PORT |
Redis port | 6379 |
API_HOST |
API server host | 0.0.0.0 |
API_PORT |
API server port | 8000 |
Pull the image:
docker pull aditya26062003/ai-npc-system:latestView on Docker Hub: https://hub.docker.com/r/aditya26062003/ai-npc-system
Available tags:
latest- Most recent build1.0.0- Stable release
# Build and start
docker-compose up --build
# Run in background
docker-compose up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down
# Stop and remove volumes (clears Redis data)
docker-compose down -v
# Restart specific service
docker-compose restart apiVisit http://localhost:8000/docs for interactive API testing
Friendly Blacksmith:
Player: "Hello! I need a new sword."
NPC: "Ah, welcome friend! You've come to the right place! I have the finest blades in all the kingdom. What kind of sword are you looking for?"
Aggressive Guard:
Player: "Can I pass through the gate?"
NPC: "Halt! State your business quickly, and it better be legitimate. I don't have time for troublemakers."
Mysterious Oracle:
Player: "What do you see in my future?"
NPC: "The threads of fate are tangled around you... darkness approaches, yet within it lies opportunity. Will you be ready when the moment comes?"
Contributions are welcome! Here's how:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
GitHub: @EchoSingh Docker Hub: aditya26062003
- Voice synthesis integration
- Multi-language support
- NPC-to-NPC conversations
- Advanced quest chains
- Emotion detection in player messages
- WebSocket support for real-time chat
- Unity/Unreal Engine integration examples
- Use Redis persistence for production
- Enable OpenAI streaming for faster responses
- Implement rate limiting for API endpoints
- Use connection pooling for Redis
- Cache frequently accessed NPCs in memory
# Check Redis is running
docker-compose ps
# Restart Redis
docker-compose restart redis# Verify API key in .env
cat .env | grep OPENAI_API_KEY
# Test API key
curl https://api.openai.com/v1/models \
-H "Authorization: Bearer $OPENAI_API_KEY"# Clean rebuild
docker-compose down -v
docker-compose build --no-cache
docker-compose up