This project demonstrates how to create a context-aware simple chatbot using LangGraph. Unlike many examples found on YouTube, Udemy, and Medium, which often repeat the same code pattern (an infinite while loop for collecting user input and directly invoking graph.invoke
or graph.stream
), this implementation is a true chatbot. It ensures context-aware responses by maintaining the entire message history throughout the conversation.
The main goal is to demonstrate how to build a basic chatbot that retains context using a structured graph-based approach. While there are many ways to implement chatbots, such as integrating human-in-the-loop workflows or multi-turn conversation branching, this project focuses on showcasing the fundamentals of a simple chatbot design.
- Stateful Conversations: The bot maintains context across multiple interactions using a message history.
- Context-Aware Responses: Generates seamless replies based on the entire conversation history, avoiding repetition or missed details.
To use this project, ensure you have the following:
- Python 3.9 or higher.
- Poetry for dependency management.
- A valid OpenAI API key.
Follow these steps to set up and run the chatbot:
-
Clone the repository:
git clone [email protected]:AllwynJesu/langgraph-simple-chatbot.git cd langgraph-simple-chatbot
-
Install dependencies using Poetry:
poetry install
-
Create a
.env
file in the project root directory and add your OpenAI API key:OPENAI_API_KEY=your_openai_api_key
-
Run the chatbot:
poetry run python bot.py
- Start the chatbot by running the script.
- Enter your messages at the
User:
prompt. - The chatbot will provide context-aware responses based on the conversation history.
- To exit, type
quit
,exit
, orq
.
The chatbot is designed using LangGraph's StateGraph
to manage the conversation flow efficiently. Here's an outline of the workflow:
- User Input: The program starts at the
USER_INPUT_NODE
, where it collects the user's input. - Decision Point: A conditional check determines if the conversation should continue or end.
- Bot Response: If continuing, the bot generates a response using OpenAI's GPT model by leveraging the entire message history.
- Loop: The response is displayed, and the flow returns to the
USER_INPUT_NODE
.
This project is open-source and licensed under the MIT License. Contributions are welcome!