Skip to content

muk0644/langchain-mongodb-chat

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ’¬ AI Chat Assistant with Message History

A modern, intelligent chat application built with Streamlit, LangChain, and MongoDB. This app uses Google's Gemini 2.5 Flash model to provide AI-powered conversations while maintaining persistent chat history across sessions.

πŸ”— Live Demo App: https://langchain-app-chat-with-history.streamlit.app/


✨ Features

  • AI-Powered Conversations: Uses Google Gemini 2.5 Flash for intelligent responses
  • Persistent Message History: All chat messages are saved in MongoDB for future reference
  • Multi-User Support: Different users can maintain separate chat sessions
  • Beautiful UI: Modern, responsive Streamlit interface with chat bubbles and status indicators
  • Session Management: Each user has their own isolated conversation history
  • Real-time Responses: Instant AI responses with loading indicators

πŸ—οΈ Project Structure

.
β”œβ”€β”€ app.py                          # Main Streamlit application
β”œβ”€β”€ requirements.txt                # Python dependencies
β”œβ”€β”€ .env                           # Environment variables (gitignored)
β”œβ”€β”€ .gitignore                     # Git ignore files & folders
β”œβ”€β”€ README.md                      # Project documentation
└── venv/                          # Virtual environment (gitignored)

πŸš€ Quick Start

Prerequisites

  • Python 3.8+
  • MongoDB Atlas account
  • Google API key for Gemini

1. Clone & Setup

# Clone the repository
git clone <repository-url>
cd <project-directory>

# Create virtual environment
python -m venv venv
source venv/Scripts/activate  # Windows
# or
source venv/bin/activate  # Mac/Linux

2. Install Dependencies

pip install -r requirements.txt

3. Configure Environment Variables

Create a .env file in the project root:

GOOGLE_API_KEY=your-google-api-key-here

Get your Google API key from: Google AI Studio

4. Run the Application

streamlit run app.py

The app will open in your browser at http://localhost:8501


πŸ“‹ Configuration

MongoDB Setup

  1. Go to MongoDB Atlas
  2. Create a free cluster
  3. Get your connection string
  4. The app uses:
    • Database: langchain_practice
    • Collection: chat_history_collection

MongoDB Atlas is a fully-managed, cloud-hosted database service. For this project you can use the free tier to create a cluster, create a database user with a strong password, and configure Network Access (IP whitelist) so your machine or server can connect. After creating a cluster, copy the connection string and store it in your .env as MONGODB_CONNECTION_STRING (do not commit credentials).

Environment Variables

Update the MongoDB connection string in app.py or move it to .env:

connection_string = os.getenv("MONGODB_CONNECTION_STRING")

πŸ”§ How It Works

  1. User Login: User enters their username in the sidebar
  2. Message Input: User types their question in the input field
  3. AI Processing: Gemini 2.5 Flash model processes the request
  4. History Storage: Both user message and AI response are saved to MongoDB
  5. Display: Previous chat history is shown on the page
  6. Persistence: All messages remain accessible across sessions

πŸ“¦ Dependencies

  • streamlit - Web app framework
  • langchain-google-genai - LangChain integration with Google Gemini
  • langchain-mongodb - MongoDB message history storage
  • pymongo - MongoDB Python driver
  • python-dotenv - Environment variable management

See requirements.txt for complete list.


πŸ—„οΈ MongoDB Commands (for debugging)

Connect to MongoDB and manage your data:

# Connect to Redis (if applicable)
redis-cli -p 6379

# List all keys
KEYS *

# Get string values
GET key_name

# Get list values
LRANGE key_name 0 -1

# Delete all keys in current database
FLUSHDB

# Delete all keys in all databases
FLUSHALL

πŸ“ File Naming Convention

  • app.py: Main application file (changed from main.py for better convention with Streamlit)
  • requirements.txt: Python package dependencies
  • .env: Sensitive environment variables (never commit)
  • .gitignore: Files to exclude from git

ℹ️ About app.py

app.py is the Streamlit entrypoint for this project. It:

  • Initializes the LLM client (ChatGoogleGenerativeAI) using the GOOGLE_API_KEY from the environment
  • Creates a MongoDBChatMessageHistory instance to read/write messages to the configured database and collection
  • Renders the UI and handles user input, saving both user and AI messages to the history

To change the database or model, update the corresponding variables in app.py or move them into the .env and read with python-dotenv.

πŸ” Security Notes

  • Never commit .env file to git
  • Keep your API keys and MongoDB connection strings private
  • Use environment variables for all sensitive data
  • Don't hardcode credentials in your code

πŸ› οΈ Development

Modify the MongoDB Connection

Update these lines in app.py if needed:

chat_with_history=MongoDBChatMessageHistory(
    session_id=user,
    connection_string="your-mongodb-uri",
    database_name="langchain_practice",
    collection_name="chat_history_collection"
)

Change the AI Model

To use a different model, update the LLM initialization:

llm = ChatGoogleGenerativeAI(model="gemini-pro", api_key=os.getenv("GOOGLE_API_KEY"))

πŸ› Troubleshooting

API Key Error

  • Ensure .env file is in the project root
  • Check that GOOGLE_API_KEY is set correctly
  • Restart the Streamlit app after updating .env

MongoDB Connection Error

  • Verify MongoDB Atlas cluster is active
  • Check connection string is correct
  • Ensure IP whitelist includes your machine (or use 0.0.0.0/0)

Rate Limiting


πŸ“š Resources


πŸ“„ License

This project is open source and available under the MIT License.


πŸ‘¨β€πŸ’»Note of Author

Created for learning and demonstrating LangChain + MongoDB integration with Streamlit.


About

Simple AI-powered chat application using Streamlit, LangChain, and MongoDB for persistent message history with Gemini 2.5 Flash

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages