carlotamdeluna commited on
Commit
a4e99e6
1 Parent(s): 0533925

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -55
app.py CHANGED
@@ -1,21 +1,23 @@
1
  import subprocess
2
 
3
- # Install packages using pip from Python
4
- subprocess.check_call(["pip", "install", "langchain_community", "langchain"])
5
-
6
  # Import necessary libraries
7
  import streamlit as st
8
  from langchain.chains import ConversationChain
9
- from langchain_core.messages import AIMessage, HumanMessage
10
- from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
11
  import os
 
 
12
  from langchain_community.llms import HuggingFaceEndpoint
13
- from langchain.memory import ChatMessageHistory
 
 
14
 
15
  # Set Streamlit page configuration
16
  st.set_page_config(page_title='🧠MemoryBot🤖', layout='wide')
17
-
18
- # Initialize session states
19
  if "generated" not in st.session_state:
20
  st.session_state["generated"] = []
21
  if "past" not in st.session_state:
@@ -33,17 +35,19 @@ def get_text():
33
  (str): The text entered by the user
34
  """
35
  input_text = st.text_input("You: ", st.session_state["input"], key="input",
36
- placeholder="Your AI assistant here! Ask me anything ...",
37
- label_visibility='hidden')
38
  return input_text
39
 
40
- # Function to start a new chat
41
  def new_chat():
42
  """
43
  Clears session state and starts a new chat.
44
  """
45
- save = ["User: " + past for past in reversed(st.session_state["past"])]
46
- save.extend(["Bot: " + gen for gen in reversed(st.session_state["generated"])])
 
 
47
  st.session_state["stored_session"].append(save)
48
  st.session_state["generated"] = []
49
  st.session_state["past"] = []
@@ -52,70 +56,66 @@ def new_chat():
52
  st.session_state.entity_memory.buffer.clear()
53
 
54
  # Add a button to start a new chat
55
- st.sidebar.button("New Chat", on_click=new_chat, type='primary')
 
 
 
56
 
57
  # Move K outside of the sidebar expander
58
- K = st.sidebar.number_input('(#) Summary of prompts to consider', min_value=3, max_value=1000)
59
 
60
  # Set up the Streamlit app layout
61
  st.title("Personalized chatbot")
62
 
63
- # Create prompt
64
- prompt = ChatPromptTemplate.from_messages([
65
- ("system", "You are a helpful assistant. Answer all questions to the best of your ability."),
66
- MessagesPlaceholder(variable_name="messages"),
67
- ])
68
 
69
- # Create an instance of HuggingFaceEndpoint
70
- llm = HuggingFaceEndpoint(repo_id='google/gemma-7b',
71
- temperature=0.5,
72
- model_kwargs={"max_length": 128},
73
- huggingfacehub_api_token=os.environ.get("HUGGINGFACEHUB_API_TOKEN", ""))
74
 
75
- # Get the user input
76
- user_input = get_text()
 
 
 
 
 
77
 
78
- # Create a ChatMessageHistory object if not already created
79
- if 'entity_memory' not in st.session_state:
80
- st.session_state.entity_memory = ChatMessageHistory()
81
 
82
- # Create the ConversationChain object with the specified configuration
83
- conversation = ConversationChain(llm=llm,
84
- memory=st.session_state.entity_memory)
85
 
86
 
87
 
88
- #Create prompt
89
- prompt = ChatPromptTemplate.from_messages(
90
- [
91
- (
92
- "system",
93
- "You are a helpful assistant. Answer all questions to the best of your ability.",
94
- ),
95
- MessagesPlaceholder(variable_name="messages"),
96
- ]
97
- )
98
 
99
- chain = prompt | conversation
 
100
 
101
  # Generate the output using the ConversationChain object and the user input, and add the input/output to the session
102
  if user_input:
103
- output = chain.invoke({"messages": user_input})
104
- st.session_state["past"].append(user_input)
105
- st.session_state["generated"].append(output)
 
106
 
107
  # Display the conversation history using an expander, and allow the user to download it
108
  with st.expander("Conversation", expanded=True):
109
- for past, gen in zip(reversed(st.session_state["past"]), reversed(st.session_state["generated"])):
110
- st.info(f"User: {past}", icon="🧐")
111
- st.success(f"Bot: {gen}", icon="🤖")
 
 
112
 
113
  # Display stored conversation sessions in the sidebar
114
- for i, sublist in enumerate(st.session_state.get("stored_session", [])):
115
- with st.sidebar.expander(label=f"Conversation-Session:{i}"):
116
- st.write(sublist)
117
 
118
  # Allow the user to clear all stored conversation sessions
119
- if st.session_state.get("stored_session"):
120
  if st.sidebar.checkbox("Clear-all"):
121
- del st.session_state["stored_session"]
 
1
  import subprocess
2
 
3
+ # Instalar un paquete utilizando pip desde Python
4
+ subprocess.check_call(["pip", "install", "langchain_community","langchain"])
 
5
  # Import necessary libraries
6
  import streamlit as st
7
  from langchain.chains import ConversationChain
8
+ from langchain.chains.conversation.memory import ConversationEntityMemory
9
+ from langchain.chains.conversation.prompt import ENTITY_MEMORY_CONVERSATION_TEMPLATE
10
  import os
11
+ from getpass import getpass
12
+ from langchain import HuggingFaceHub
13
  from langchain_community.llms import HuggingFaceEndpoint
14
+
15
+
16
+
17
 
18
  # Set Streamlit page configuration
19
  st.set_page_config(page_title='🧠MemoryBot🤖', layout='wide')
20
+ # Initialize session states. Un session state es como un diccionario
 
21
  if "generated" not in st.session_state:
22
  st.session_state["generated"] = []
23
  if "past" not in st.session_state:
 
35
  (str): The text entered by the user
36
  """
37
  input_text = st.text_input("You: ", st.session_state["input"], key="input",
38
+ placeholder="Your AI assistant here! Ask me anything ...",
39
+ label_visibility='hidden')
40
  return input_text
41
 
42
+ # #parte para hacer un chat nuevo
43
  def new_chat():
44
  """
45
  Clears session state and starts a new chat.
46
  """
47
+ save = []
48
+ for i in range(len(st.session_state['generated'])-1, -1, -1):
49
+ save.append("User:" + st.session_state["past"][i])
50
+ save.append("Bot:" + st.session_state["generated"][i])
51
  st.session_state["stored_session"].append(save)
52
  st.session_state["generated"] = []
53
  st.session_state["past"] = []
 
56
  st.session_state.entity_memory.buffer.clear()
57
 
58
  # Add a button to start a new chat
59
+ st.sidebar.button("New Chat", on_click = new_chat, type='primary')
60
+
61
+
62
+
63
 
64
  # Move K outside of the sidebar expander
65
+ K = st.sidebar.number_input(' (#)Summary of prompts to consider', min_value=3, max_value=1000)
66
 
67
  # Set up the Streamlit app layout
68
  st.title("Personalized chatbot")
69
 
 
 
 
 
 
70
 
 
 
 
 
 
71
 
72
+ # Create an OpenAI instance
73
+ llm = HuggingFaceEndpoint(repo_id='mistral-community/Mixtral-8x22B-v0.1',
74
+ temperature=0.3,
75
+ model_kwargs = {"max_length":128},
76
+ huggingfacehub_api_token = os.environ["HUGGINGFACEHUB_API_TOKEN"])
77
+
78
+
79
 
 
 
 
80
 
 
 
 
81
 
82
 
83
 
84
+ # Create a ConversationEntityMemory object if not already created
85
+ if 'entity_memory' not in st.session_state:
86
+ st.session_state.entity_memory = ConversationEntityMemory(llm=llm, k=K )
87
+
88
+ # Create the ConversationChain object with the specified configuration
89
+ Conversation = ConversationChain(llm=llm,
90
+ prompt=ENTITY_MEMORY_CONVERSATION_TEMPLATE,
91
+ memory=st.session_state.entity_memory
92
+ )
93
+
94
 
95
+ # Get the user input
96
+ user_input = get_text()
97
 
98
  # Generate the output using the ConversationChain object and the user input, and add the input/output to the session
99
  if user_input:
100
+ output = Conversation.run(input=user_input)
101
+ st.session_state.past.append(user_input)
102
+ st.session_state.generated.append(output)
103
+
104
 
105
  # Display the conversation history using an expander, and allow the user to download it
106
  with st.expander("Conversation", expanded=True):
107
+ for i in range(len(st.session_state['generated'])-1, -1, -1):
108
+ st.info(st.session_state["past"][i],icon="🧐")
109
+ st.success(st.session_state["generated"][i], icon="🤖")
110
+
111
+
112
 
113
  # Display stored conversation sessions in the sidebar
114
+ for i, sublist in enumerate(st.session_state.stored_session):
115
+ with st.sidebar.expander(label= f"Conversation-Session:{i}"):
116
+ st.write(sublist)
117
 
118
  # Allow the user to clear all stored conversation sessions
119
+ if st.session_state.stored_session:
120
  if st.sidebar.checkbox("Clear-all"):
121
+ del st.session_state.stored_session