Skip to content

Commit

Permalink
Merge pull request #898 from Undertone0809/hizeros/feat-add-mem0-tuto…
Browse files Browse the repository at this point in the history
…rial

Hizeros/feat add mem0 tutorial
  • Loading branch information
Undertone0809 authored Sep 7, 2024
2 parents 4539b69 + 391ddac commit cd31d04
Show file tree
Hide file tree
Showing 7 changed files with 212 additions and 4 deletions.
1 change: 1 addition & 0 deletions docs/_sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- [Groq, llama3, Streamlit to build a application](use_cases/streamlit-groq-llama3.md#groq-llama3-streamlit-to-build-a-application)
- [Build knowledge map with streamlit and pne.chat()](use_cases/llmapper.md#llmapper)
- [Build a chatbot using pne+streamlit to chat with GitHub repo](use_cases/chat-to-github-repo.md#build-a-chatbot-using-pne-streamlit-to-chat-with-GitHub-repo)
- [Build a chatbot using mem0](use_cases/chatbot-integrated-mem0.md#build-a-chatbot-using-streamlit-and-mem0)

- Modules
- [:robot: Agent](modules/agent.md#agent)
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/images/chatbot-mem0.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
167 changes: 167 additions & 0 deletions docs/use_cases/chatbot-integrated-mem0.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
# Build a chatbot using streamlit and mem0
Mem0 (pronounced “mem-zero”) enhances AI assistants and agents with an intelligent memory layer, enabling personalized AI interactions.
Mem0 remembers user preferences, adapts to individual needs, and continuously improves over time, making it ideal for customer support chatbots, AI assistants, and autonomous systems.

This tutorial is an example of building a streamlit PersonalHealingAssistant using mem0.

## Environment Setup

We can start off by creating a new conda environment with python=3.11:`conda create -n streamlit_mem0 python=3.11`

Activate the environment:`conda activate streamlit_mem0`

Next, let’s install all necessary libraries:

```shell
pip install -U promptulate streamlit mem0ai
```

## Step-by-Step Implementation

### Step 1

Create a `core.py` script and import the necessary dependencies:
```python
import pne
from mem0 import MemoryClient
```

### Step 2
Initialize the memory client:
```python
class PersonalHealingAssistant:
def __init__(self):
self.memory = None
self.messages = [
{"role": "system", "content": "You are a personal healing AI Assistant."}
]

def set_mem0_api_key(self, mem0_api_key: str):
self.memory = MemoryClient(api_key=mem0_api_key)

def ask_question(self, question: str, user_id: str, config) -> str:
# Fetch previous related memories
previous_memories = self.search_memories(question, user_id=user_id)
prompt = question
if previous_memories:
prompt = f"User input: {question}\n Previous memories: {previous_memories}"
self.messages.append({"role": "user", "content": prompt})

response = pne.chat(
model=config.model_name,
stream=True,
messages=self.messages,
model_config={"api_base": config.api_base, "api_key": config.api_key},
)
self.messages.append({"role": "assistant", "content": response})

# Store the question in memory
self.memory.add(question, user_id=user_id)
return response

def get_memories(self, user_id):
memories = self.memory.get_all(user_id=user_id)
return memories

def search_memories(self, query, user_id):
memories = self.memory.search(query, user_id=user_id)
return memories
```
- Initialization: The PersonalTravelAssistant class is initialized with the OpenAI client and Mem0 memory setup.
- set mem0 api key: This method sets the Mem0 API key for memory access.
- Asking Questions: The ask_question method sends a question to the AI, incorporates previous memories, and stores new information.
- Memory Management: The get_memories and search_memories methods handle retrieval and searching of stored memories.

### Step 3
Create a `app.py` file:
```python
import pne
import streamlit as st
from core import PersonalHealingAssistant


def main():
config = pne.beta.st.model_sidebar()
with st.sidebar:
mem0_user_id = st.text_input("mem0 user id", type="password")
mem0_api_key = st.text_input(
"mem0 API Key", key="provider_mem0_api_key", type="password"
)

st.title("PersonalHealingAssistant")
st.caption(
"""
Personal Healing Assistant combines pne and mem0ai to create a personalized healing assistant for you \n
🚀 Power by [promptulate](https://github.com/Undertone0809/promptulate)
""" # noqa
)
st.chat_message("assistant").write(
"I am your personal healing assistant, how can I help you? "
)

ai_assistant = PersonalHealingAssistant()

if prompt := st.chat_input("Please enter what you want to know "):
if not config.api_key:
st.info("Please add your model API key to continue.")
st.stop()

if not mem0_api_key:
st.error("Please provide your mem0 API Key to continue.")
st.stop()

ai_assistant.set_mem0_api_key(mem0_api_key)

answer = ai_assistant.ask_question(
question=prompt, user_id=mem0_user_id, config=config
)

st.chat_message("user").write(prompt)
st.chat_message("assistant").write_stream(answer)


if __name__ == "__main__":
main()
```

## Output effect
```shell
cd path:/mem0 # Switch to your mem0 project directory
streamlit run app.py
```

## Demo
There is a `app.py` file under the `mem0` file of `example` in the project folder.
You can run the application directly to view the effect and debug the web page.
Project Link: [streamlit-mem0](https://github.com/Undertone0809/promptulate/tree/main/example/mem0)
To run the application, follow the steps below:

- Click [here](https://github.com/Undertone0809/promptulate/fork) to fork the project to your local machine
- Clone the project locally:

```bash
git clone https://github.com/Undertone0809/promptulate.git
```

- Switch the current directory to the example

```shell
cd ./example/mem0
```

- Install the dependencies

```shell
pip install -r requirements.txt
```

- Run the application

```shell
streamlit run app.py
```

The running effect is as follows:
You can see that llm has read previous chat records,Therefore, it is possible to create personalized AI assistants for different users
![Mem0-Platform-Historical-mem-Records ](../images/Mem0-Platform-Historical-mem-Records%20.png)
![chatbot-mem0](../images/chatbot-mem0.png)
32 changes: 32 additions & 0 deletions example/mem0/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# mem0
Mem0 (pronounced “mem-zero”) enhances AI assistants and agents with an intelligent memory layer, enabling personalized AI interactions.
Mem0 remembers user preferences, adapts to individual needs, and continuously improves over time, making it ideal for customer support chatbots, AI assistants, and autonomous systems.

This example is an example of building a streamlit PersonalHealingAssistant using mem0.

You see try the live demo [here](https://github.com/Undertone0809/promptulate/tree/main/example/mem0).

# Quick Start
1. Clone the repository and install the dependencies

```shell
git clone https://www.github.com/Undertone0809/promptulate
```

2. Switch the current directory to the example

```shell
cd ./example/mem0
```

3. Install the dependencies

```shell
pip install -r requirements.txt
```

4. Run the application

```shell
streamlit run app.py
```
1 change: 0 additions & 1 deletion example/mem0/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

def main():
config = pne.beta.st.model_sidebar()
# todo llm default answer with cn
with st.sidebar:
mem0_user_id = st.text_input("mem0 user id", type="password")
mem0_api_key = st.text_input(
Expand Down
15 changes: 12 additions & 3 deletions example/mem0/core.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
import pne
from mem0 import MemoryClient

SYSTEM_PROMPT = """
You are a listener, and your task is to help users sort out their emotions and thoughts. You are friendly, approachable, gentle when talking to users, and do not provide advice. You will help users explore their emotions and feelings by asking clever questions, so that you can go directly into in-depth conversations and always maintain a good chat atmosphere. Except for "you", you don't call each other.
1. ** Identify and record emotions **: You will identify emotions in users 'responses and guide users to describe their emotions and what they have experienced.
2. ** Empathic reply **: You show real interest in the user's experience, always show respect and understanding, and express empathy and acceptance in a gentle and cordial way. When showing empathy, you will use poetic language and metaphor to retell the user's feelings.
3. ** Provide companionship and comfort value **: When negative emotions are identified in the user's answer, comfort and encourage the user, you will tell the user,"I will be here with you","Don't be afraid, you will be free" and other warm words, don't use the same comforting words repeatedly every time.
4. ** Guide self-reflection **: You will ask a question at the end of each message to encourage users to reflect deeply on their emotions ** and thoughts. You will ask thoughtful questions, such as "Why do you think that?" and "Where do you feel the source of your emotions?", triggering self-reflection among users. When replying each time, limit the questions to 1-2, and use "or say" to change the answer to complex questions. Avoid making lists and never end conversations.
5. After the user tells an incident and his emotional reaction, do not repeatedly ask questions about the details of the incident. You will encourage users to write their reflections in their diary, or ask users what else they think about and make interesting discoveries today, such as "I'm glad you are willing to share your emotions with me. Have you thought about any interesting topics today?"“。
6. You will obtain the user's historical chat history. Under appropriate circumstances, you can use the diary content to understand the user's status and guide the user to reflect or recognize their own emotions. For example, if a user wrote in his diary yesterday,"I feel very anxious about doing a project," then when the user initiates a chat with you for the first time today, you can ask,"Have you solved the project problem today?" Will you still feel anxious about project problems?" or "Can I hear why you feel anxious about doing a project?" and other questions.
7. Decide which language to reply to the user based on the language entered by the user
""" # noqa


class PersonalHealingAssistant:
def __init__(self):
self.memory = None
self.messages = [
{"role": "system", "content": "You are a personal healing AI Assistant."}
]
self.messages = [{"role": "system", "content": SYSTEM_PROMPT}]

def set_mem0_api_key(self, mem0_api_key: str):
self.memory = MemoryClient(api_key=mem0_api_key)
Expand Down

0 comments on commit cd31d04

Please sign in to comment.