A zero-shot persuasive chatbot that encourages people to drink more water, based on the approach from "Zero-shot Persuasive Chatbots with LLM-Generated Strategies and Information Retrieval" but adapted to the water domain.
This chatbot combines:
- Local Knowledge Database - Comprehensive water consumption facts and health information
- Information Retrieval - Semantic search to find relevant information for each conversation
- LLM-Based Strategy Selection - Dynamically selects the most effective persuasion strategy
- Persuasive Response Generation - Creates personalized, engaging responses
User Message
↓
[1] Information Retrieval
- Semantic search over water knowledge database
- Returns top-k most relevant facts
↓
[2] Strategy Selection
- LLM analyzes conversation context
- Selects optimal persuasion strategy
↓
[3] Response Generation
- LLM generates response using selected strategy
- Incorporates retrieved information naturally
↓
Persuasive Response
- 30+ Knowledge Entries covering health benefits, recommendations, tips, myths, and special situations
- 12 Persuasion Strategies including authority, social proof, narrative, practical tips, and more
- Semantic Search using sentence transformers for accurate information retrieval
- Conversation Tracking with strategy logging and statistics
- Interactive & Programmatic Modes for different use cases
- Clone the repository
cd cs224w- Install dependencies
pip install -r requirements.txt- Set up environment variables
cp .env.example .env
# Edit .env and add your OpenAI API keypython water_chatbot.py interactiveThis launches an interactive chat session where you can converse with the bot.
from water_chatbot import WaterConsumptionChatbot
# Initialize chatbot
chatbot = WaterConsumptionChatbot()
# Have a conversation
result = chatbot.chat("I feel tired all the time")
print(result['response'])
# Verbose mode for debugging
result = chatbot.chat("How much water should I drink?", verbose=True)
# Shows: retrieved info, selected strategy, and responsefrom water_chatbot import WaterConsumptionChatbot
chatbot = WaterConsumptionChatbot(
model="gpt-4-turbo-preview",
retrieval_top_k=5, # Retrieve more context
enable_logging=True
)
# Multi-turn conversation
chatbot.chat("Hi, I want to drink more water")
chatbot.chat("But I always forget during the day")
chatbot.chat("What can I do?")
# Get statistics
stats = chatbot.get_statistics()
print(stats)
# Save conversation
chatbot.save_conversation("my_conversation.json")Contains 30 curated entries across categories:
- health_benefits: Brain function, physical performance, weight management, etc.
- recommendations: Daily intake, exercise hydration, climate considerations
- dehydration_signs: Symptoms and warning signs
- tips: Practical strategies for drinking more water
- myths: Common misconceptions debunked
- environment: Sustainability considerations
- special_situations: Illness, pregnancy, age-specific needs
Each entry includes:
- Title and detailed content
- Category and tags
- Searchable metadata
Uses sentence transformers for semantic search:
- Embeds knowledge base entries
- Computes similarity with user queries
- Returns top-k most relevant entries
- Supports category-specific and diversity-based retrieval
Methods:
retrieve(query, top_k)- Standard semantic searchretrieve_by_category(query, category, top_k)- Category-filtered searchretrieve_diverse(query, top_k)- Diversity-aware retrievalget_context_string(query)- Formatted context for LLM
Implements 12 persuasion strategies:
| Strategy | Description | When to Use |
|---|---|---|
| Authority | Use expert knowledge and scientific facts | User asks for facts or seems skeptical |
| Social Proof | Reference what others are doing | User influenced by peers or trends |
| Scarcity | Emphasize what user stands to lose | User motivated by avoiding negatives |
| Reciprocity | Offer value first | Building rapport |
| Consistency | Remind of stated goals | User has expressed commitments |
| Liking | Build rapport and empathy | User shares personal challenges |
| Unity | Create shared identity | User identifies with a group |
| Narrative | Use stories and examples | Make abstract benefits concrete |
| Education | Provide clear information | User asks direct questions |
| Practical Tips | Focus on actionable steps | User ready to take action |
| Self-Monitoring | Encourage tracking | User benefits from awareness |
| Positive Framing | Emphasize benefits | User responds to positive motivation |
Orchestrates the full pipeline:
- Receives user message
- Retrieves relevant knowledge
- Selects persuasion strategy via LLM
- Generates persuasive response
- Tracks conversation and strategies
chatbot = WaterConsumptionChatbot(
api_key=None, # OpenAI API key (uses env var if None)
model="gpt-4-turbo-preview", # LLM model to use
retrieval_top_k=3, # Number of knowledge entries to retrieve
enable_logging=True # Track conversation history
)chat(user_message, verbose=False)
- Process user message and generate response
- Returns dict with 'response' (and debug info if verbose=True)
get_conversation_history()
- Returns full conversation history
get_strategy_history()
- Returns history of strategies used
get_statistics()
- Returns conversation statistics (turns, strategies used, etc.)
save_conversation(filename)
- Save conversation to JSON file
load_conversation(filename)
- Load previous conversation from JSON
reset_conversation()
- Clear conversation history
User: I always forget to drink water during the day
[Retrieval finds: "Set Hydration Reminders", "Carry a Water Bottle"]
[Strategy Selected: "practical_tips" (confidence: 0.85)]
Bot: I totally get it - when you're busy, hydration can slip your mind!
Try setting phone reminders every 2 hours, or keep a water bottle at
your desk as a visual cue. Many people find that having water in sight
makes it much easier to remember. What does your typical day look like?
User: I feel exhausted all the time
[Retrieval finds: "Brain Function and Hydration", "Physical Performance"]
[Strategy Selected: "authority" (confidence: 0.92)]
Bot: That's tough! Did you know that even mild dehydration can
significantly impact your energy levels? Your brain is 75% water, and
losing just 1-3% of body water can lead to fatigue and reduced alertness.
How much water are you currently drinking each day?
User: How much water should I actually drink?
[Retrieval finds: "General Daily Intake", "Exercise Hydration"]
[Strategy Selected: "education" (confidence: 0.95)]
Bot: Great question! The National Academies of Sciences recommends about
15.5 cups (3.7 liters) for men and 11.5 cups (2.7 liters) for women daily.
This includes all fluids from water, beverages, and food. Your individual
needs may vary based on activity level, climate, and overall health. Are
you very active, or in a hot climate?
Run the information retrieval test:
python information_retrieval.pyRun demo conversations:
python water_chatbot.pyRun interactive mode:
python water_chatbot.py interactive- Type normally to chat
verbose [message]- See detailed process (retrieval, strategy, etc.)stats- View conversation statisticssave- Save conversation to JSONreset- Start fresh conversationquit- Exit
Edit water_knowledge_db.py and add entries to WATER_KNOWLEDGE_BASE:
{
"id": 31,
"category": "your_category",
"title": "Your Title",
"content": "Your detailed content here...",
"tags": ["tag1", "tag2", "tag3"]
}After adding entries, delete embeddings_cache.pkl to recompute embeddings.
Edit persuasion_strategies.py and add to PERSUASION_STRATEGIES:
"your_strategy": {
"name": "Strategy Name",
"description": "When and how to use this strategy...",
"example": "Example of the strategy in action...",
"when_to_use": "Specific situations where this works best..."
}# Retrieve more context
chatbot = WaterConsumptionChatbot(retrieval_top_k=5)
# Use diverse retrieval
from information_retrieval import WaterKnowledgeRetriever
retriever = WaterKnowledgeRetriever()
results = retriever.retrieve_diverse(query, top_k=3, diversity_threshold=0.7)- Model: all-MiniLM-L6-v2 (sentence transformers)
- Similarity: Cosine similarity
- Caching: Embeddings cached for faster loading
- Strategy Selection: Low temperature (0.3) for consistency
- Response Generation: Higher temperature (0.7) for natural conversation
- Format: JSON mode for strategy selection
- First run: ~10-15 seconds (computing embeddings)
- Subsequent runs: ~1-2 seconds (using cache)
- Per-message: ~2-5 seconds (retrieval + LLM calls)
cs224w/
├── water_knowledge_db.py # Knowledge database
├── information_retrieval.py # Semantic search
├── persuasion_strategies.py # Strategy selection & response generation
├── water_chatbot.py # Main chatbot interface
├── requirements.txt # Dependencies
├── .env.example # Environment template
├── README.md # This file
└── embeddings_cache.pkl # (Generated) Cached embeddings
- Python 3.8+
- OpenAI API key
- Dependencies in requirements.txt
Possible extensions:
- User profiling for personalized strategies
- Multi-turn strategy planning
- A/B testing different strategies
- Integration with hydration tracking apps
- Voice interface
- Multilingual support
- Reinforcement learning for strategy selection
- Web/mobile interface
This implementation is inspired by:
Zero-shot Persuasive Chatbots with LLM-Generated Strategies and Information Retrieval
Adapted to the water consumption domain with:
- Domain-specific knowledge base
- Health-focused persuasion strategies
- Practical hydration advice
MIT License - Feel free to use and modify for your projects!
Contributions welcome! Areas for improvement:
- Additional knowledge entries
- New persuasion strategies
- Better evaluation metrics
- UI/UX enhancements
For issues or questions, please open a GitHub issue.
Stay Hydrated! 💧