Thanks to visit codestin.com
Credit goes to github.com

Skip to content

shuojiafu/cs224w

Repository files navigation

Water Consumption Persuasive Chatbot

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.

Overview

This chatbot combines:

  1. Local Knowledge Database - Comprehensive water consumption facts and health information
  2. Information Retrieval - Semantic search to find relevant information for each conversation
  3. LLM-Based Strategy Selection - Dynamically selects the most effective persuasion strategy
  4. Persuasive Response Generation - Creates personalized, engaging responses

Architecture

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

Features

  • 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

Installation

  1. Clone the repository
cd cs224w
  1. Install dependencies
pip install -r requirements.txt
  1. Set up environment variables
cp .env.example .env
# Edit .env and add your OpenAI API key

Quick Start

Interactive Mode

python water_chatbot.py interactive

This launches an interactive chat session where you can converse with the bot.

Programmatic Usage

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 response

Example with Custom Configuration

from 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")

Components

1. Knowledge Database (water_knowledge_db.py)

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

2. Information Retrieval (information_retrieval.py)

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 search
  • retrieve_by_category(query, category, top_k) - Category-filtered search
  • retrieve_diverse(query, top_k) - Diversity-aware retrieval
  • get_context_string(query) - Formatted context for LLM

3. Persuasion Strategies (persuasion_strategies.py)

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

4. Main Chatbot (water_chatbot.py)

Orchestrates the full pipeline:

  1. Receives user message
  2. Retrieves relevant knowledge
  3. Selects persuasion strategy via LLM
  4. Generates persuasive response
  5. Tracks conversation and strategies

API Reference

WaterConsumptionChatbot

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
)

Methods

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

Example Conversations

Example 1: Forgetting to Drink Water

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?

Example 2: Feeling Tired

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?

Example 3: Asking for Recommendations

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?

Testing the System

Run the information retrieval test:

python information_retrieval.py

Run demo conversations:

python water_chatbot.py

Run interactive mode:

python water_chatbot.py interactive

Commands in Interactive Mode

  • Type normally to chat
  • verbose [message] - See detailed process (retrieval, strategy, etc.)
  • stats - View conversation statistics
  • save - Save conversation to JSON
  • reset - Start fresh conversation
  • quit - Exit

Customization

Adding Knowledge Entries

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.

Adding Persuasion Strategies

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..."
}

Adjusting Retrieval

# 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)

Technical Details

Information Retrieval

  • Model: all-MiniLM-L6-v2 (sentence transformers)
  • Similarity: Cosine similarity
  • Caching: Embeddings cached for faster loading

LLM Usage

  • Strategy Selection: Low temperature (0.3) for consistency
  • Response Generation: Higher temperature (0.7) for natural conversation
  • Format: JSON mode for strategy selection

Performance

  • First run: ~10-15 seconds (computing embeddings)
  • Subsequent runs: ~1-2 seconds (using cache)
  • Per-message: ~2-5 seconds (retrieval + LLM calls)

Project Structure

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

Requirements

  • Python 3.8+
  • OpenAI API key
  • Dependencies in requirements.txt

Future Enhancements

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

Citation

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

License

MIT License - Feel free to use and modify for your projects!

Contributing

Contributions welcome! Areas for improvement:

  • Additional knowledge entries
  • New persuasion strategies
  • Better evaluation metrics
  • UI/UX enhancements

Support

For issues or questions, please open a GitHub issue.


Stay Hydrated! 💧

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published