ProfessorLeVesseur commited on
Commit
b30b8bf
·
verified ·
1 Parent(s): 60bba2b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +217 -45
app.py CHANGED
@@ -1,61 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
- import pinecone
3
- from langchain.embeddings.openai import OpenAIEmbeddings
4
- from langchain.vectorstores import Pinecone, Chroma
5
- from langchain.chains import RetrievalQA
6
- from langchain.chat_models import ChatOpenAI
7
- import tiktoken
8
  import random
9
 
10
  # Fetch the OpenAI API key from Streamlit secrets
11
  openai_api_key = st.secrets["openai_api_key"]
12
 
 
 
 
13
  # Fetch Pinecone API key and environment from Streamlit secrets
14
  pinecone_api_key = st.secrets["pinecone_api_key"]
15
  pinecone_environment = st.secrets["pinecone_environment"]
16
 
17
- # Initialize Pinecone
18
- pinecone.init(api_key=pinecone_api_key, environment=pinecone_environment)
 
19
 
20
  # Define the name of the Pinecone index
21
- index_name = 'mi-resource-qa'
22
-
23
- # Initialize the OpenAI embeddings object with the hardcoded API key
24
- embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)
25
 
26
- # Define functions
27
- def insert_or_fetch_embeddings(index_name):
28
- if index_name in pinecone.list_indexes():
29
- vector_store = Pinecone.from_existing_index(index_name, embeddings)
30
- return vector_store
31
- else:
32
- raise ValueError(f"Index {index_name} does not exist. Please create it before fetching.")
33
-
34
- # Initialize or fetch Pinecone vector store
35
- vector_store = insert_or_fetch_embeddings(index_name)
36
-
37
- # calculate embedding cost using tiktoken
38
- def calculate_embedding_cost(text):
39
- import tiktoken
40
- enc = tiktoken.encoding_for_model('text-embedding-ada-002')
41
- total_tokens = len(enc.encode(text))
42
- # print(f'Total Tokens: {total_tokens}')
43
- # print(f'Embedding Cost in USD: {total_tokens / 1000 * 0.0004:.6f}')
44
- return total_tokens, total_tokens / 1000 * 0.0004
45
 
 
 
 
46
 
47
  def ask_with_memory(vector_store, query, chat_history=[]):
 
48
  from langchain.chains import ConversationalRetrievalChain
49
- from langchain.chat_models import ChatOpenAI
50
-
51
- llm = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=1, openai_api_key=openai_api_key)
 
 
52
 
53
- # The retriever is created with metadata filter directly in search_kwargs
54
- # retriever = vector_store.as_retriever(search_type='similarity', search_kwargs={'k': 3, 'filter': {'source': {'$eq': 'https://mimtsstac.org/sites/default/files/session-documents/Intensifying%20Literacy%20Instruction%20-%20Essential%20Practices%20%28NATIONAL%29.pdf'}}})
55
- retriever = vector_store.as_retriever(search_type='similarity', search_kwargs={'k': 3, 'filter': {'source':'https://mimtsstac.org/sites/default/files/session-documents/Intensifying%20Literacy%20Instruction%20-%20Essential%20Practices%20%28NATIONAL%29.pdf'}})
56
 
57
- chain= ConversationalRetrievalChain.from_llm(llm, retriever)
58
- result = chain({'question': query, 'chat_history': st.session_state['history']})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  # Append to chat history as a dictionary
60
  st.session_state['history'].append((query, result['answer']))
61
 
@@ -142,12 +320,6 @@ if 'placeholder' not in st.session_state:
142
 
143
  q = st.text_input(label='Ask a question or make a request ', value='', placeholder=st.session_state.placeholder)
144
  # q = st.text_input(label='Ask a question or make a request ', value='')
145
-
146
- k = 3 # Set k to 3
147
-
148
- # # Initialize chat history if not present
149
- # if 'history' not in st.session_state:
150
- # st.session_state.history = []
151
 
152
  if q:
153
  with st.spinner('Thinking...'):
 
1
+ # import streamlit as st
2
+ # import pinecone
3
+ # from langchain.embeddings.openai import OpenAIEmbeddings
4
+ # from langchain.vectorstores import Pinecone, Chroma
5
+ # from langchain.chains import RetrievalQA
6
+ # from langchain.chat_models import ChatOpenAI
7
+ # import tiktoken
8
+ # import random
9
+
10
+ # # Fetch the OpenAI API key from Streamlit secrets
11
+ # openai_api_key = st.secrets["openai_api_key"]
12
+
13
+ # # Fetch Pinecone API key and environment from Streamlit secrets
14
+ # pinecone_api_key = st.secrets["pinecone_api_key"]
15
+ # pinecone_environment = st.secrets["pinecone_environment"]
16
+
17
+ # # Initialize Pinecone
18
+ # pinecone.init(api_key=pinecone_api_key, environment=pinecone_environment)
19
+
20
+ # # Define the name of the Pinecone index
21
+ # index_name = 'mi-resource-qa'
22
+
23
+ # # Initialize the OpenAI embeddings object with the hardcoded API key
24
+ # embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)
25
+
26
+ # # Define functions
27
+ # def insert_or_fetch_embeddings(index_name):
28
+ # if index_name in pinecone.list_indexes():
29
+ # vector_store = Pinecone.from_existing_index(index_name, embeddings)
30
+ # return vector_store
31
+ # else:
32
+ # raise ValueError(f"Index {index_name} does not exist. Please create it before fetching.")
33
+
34
+ # # Initialize or fetch Pinecone vector store
35
+ # vector_store = insert_or_fetch_embeddings(index_name)
36
+
37
+ # # calculate embedding cost using tiktoken
38
+ # def calculate_embedding_cost(text):
39
+ # import tiktoken
40
+ # enc = tiktoken.encoding_for_model('text-embedding-ada-002')
41
+ # total_tokens = len(enc.encode(text))
42
+ # # print(f'Total Tokens: {total_tokens}')
43
+ # # print(f'Embedding Cost in USD: {total_tokens / 1000 * 0.0004:.6f}')
44
+ # return total_tokens, total_tokens / 1000 * 0.0004
45
+
46
+
47
+ # def ask_with_memory(vector_store, query, chat_history=[]):
48
+ # from langchain.chains import ConversationalRetrievalChain
49
+ # from langchain.chat_models import ChatOpenAI
50
+
51
+ # llm = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=1, openai_api_key=openai_api_key)
52
+
53
+ # # The retriever is created with metadata filter directly in search_kwargs
54
+ # # retriever = vector_store.as_retriever(search_type='similarity', search_kwargs={'k': 3, 'filter': {'source': {'$eq': 'https://mimtsstac.org/sites/default/files/session-documents/Intensifying%20Literacy%20Instruction%20-%20Essential%20Practices%20%28NATIONAL%29.pdf'}}})
55
+ # retriever = vector_store.as_retriever(search_type='similarity', search_kwargs={'k': 3, 'filter': {'source':'https://mimtsstac.org/sites/default/files/session-documents/Intensifying%20Literacy%20Instruction%20-%20Essential%20Practices%20%28NATIONAL%29.pdf'}})
56
+
57
+ # chain= ConversationalRetrievalChain.from_llm(llm, retriever)
58
+ # result = chain({'question': query, 'chat_history': st.session_state['history']})
59
+ # # Append to chat history as a dictionary
60
+ # st.session_state['history'].append((query, result['answer']))
61
+
62
+ # return (result['answer'])
63
+
64
+ # # Initialize chat history
65
+ # if 'history' not in st.session_state:
66
+ # st.session_state['history'] = []
67
+
68
+ # # # STREAMLIT APPLICATION SETUP WITH PASSWORD
69
+
70
+ # # Define the correct password
71
+ # # correct_password = "MiBLSi"
72
+
73
+ # #Add the image with a specified width
74
+ # image_width = 300 # Set the desired width in pixels
75
+ # st.image('MTSS.ai_Logo.png', width=image_width)
76
+ # st.subheader('Ink QA™ | Dynamic PDFs')
77
+
78
+ # # Using Markdown for formatted text
79
+ # st.markdown("""
80
+ # Resource: **Intensifying Literacy Instruction: Essential Practices**
81
+ # """, unsafe_allow_html=True)
82
+
83
+ # with st.sidebar:
84
+ # # Password input field
85
+ # # password = st.text_input("Enter Password:", type="password")
86
+
87
+ # st.image('mimtss.png', width=200)
88
+ # st.image('Literacy_Cover.png', width=200)
89
+ # st.link_button("View | Download", "https://mimtsstac.org/sites/default/files/session-documents/Intensifying%20Literacy%20Instruction%20-%20Essential%20Practices%20%28NATIONAL%29.pdf")
90
+
91
+ # Audio_Header_text = """
92
+ # **Tune into Dr. St. Martin's introduction**"""
93
+ # st.markdown(Audio_Header_text)
94
+
95
+ # # Path or URL to the audio file
96
+ # audio_file_path = 'Audio_Introduction_Literacy.m4a'
97
+ # # Display the audio player widget
98
+ # st.audio(audio_file_path, format='audio/mp4', start_time=0)
99
+
100
+ # # Citation text with Markdown formatting
101
+ # citation_Content_text = """
102
+ # **Citation**
103
+ # St. Martin, K., Vaughn, S., Troia, G., Fien, & H., Coyne, M. (2023). *Intensifying literacy instruction: Essential practices, Version 2.0*. Lansing, MI: MiMTSS Technical Assistance Center, Michigan Department of Education.
104
+
105
+ # **Table of Contents**
106
+ # * **Introduction**: pg. 1
107
+ # * **Intensifying Literacy Instruction: Essential Practices**: pg. 4
108
+ # * **Purpose**: pg. 4
109
+ # * **Practice 1**: Knowledge and Use of a Learning Progression for Developing Skilled Readers and Writers: pg. 6
110
+ # * **Practice 2**: Design and Use of an Intervention Platform as the Foundation for Effective Intervention: pg. 13
111
+ # * **Practice 3**: On-going Data-Based Decision Making for Providing and Intensifying Interventions: pg. 16
112
+ # * **Practice 4**: Adaptations to Increase the Instructional Intensity of the Intervention: pg. 20
113
+ # * **Practice 5**: Infrastructures to Support Students with Significant and Persistent Literacy Needs: pg. 24
114
+ # * **Motivation and Engagement**: pg. 28
115
+ # * **Considerations for Understanding How Students' Learning and Behavior are Enhanced**: pg. 28
116
+ # * **Summary**: pg. 29
117
+ # * **Endnotes**: pg. 30
118
+ # * **Acknowledgment**: pg. 39
119
+ # """
120
+ # st.markdown(citation_Content_text)
121
+
122
+ # # if password == correct_password:
123
+ # # Define a list of possible placeholder texts
124
+ # placeholders = [
125
+ # 'Example: Summarize the article in 200 words or less',
126
+ # 'Example: What are the essential practices?',
127
+ # 'Example: I am a teacher, why is this resource important?',
128
+ # 'Example: How can this resource support my instruction in reading and writing?',
129
+ # 'Example: Does this resource align with the learning progression for developing skilled readers and writers?',
130
+ # 'Example: How does this resource address the needs of students scoring below the 20th percentile?',
131
+ # 'Example: Are there assessment tools included in this resource to monitor student progress?',
132
+ # 'Example: Does this resource provide guidance on data collection and analysis for monitoring student outcomes?',
133
+ # "Example: How can this resource be used to support students' social-emotional development?",
134
+ # "Example: How does this resource align with the district's literacy goals and objectives?",
135
+ # 'Example: What research and evidence support the effectiveness of this resource?',
136
+ # 'Example: Does this resource provide guidance on implementation fidelity'
137
+ # ]
138
+
139
+ # # Select a random placeholder from the list
140
+ # if 'placeholder' not in st.session_state:
141
+ # st.session_state.placeholder = random.choice(placeholders)
142
+
143
+ # q = st.text_input(label='Ask a question or make a request ', value='', placeholder=st.session_state.placeholder)
144
+ # # q = st.text_input(label='Ask a question or make a request ', value='')
145
+
146
+ # k = 3 # Set k to 3
147
+
148
+ # # # Initialize chat history if not present
149
+ # # if 'history' not in st.session_state:
150
+ # # st.session_state.history = []
151
+
152
+ # if q:
153
+ # with st.spinner('Thinking...'):
154
+ # answer = ask_with_memory(vector_store, q, st.session_state.history)
155
+
156
+ # # Display the response in a text area
157
+ # st.text_area('Response: ', value=answer, height=400, key="response_text_area")
158
+
159
+ # st.success('Powered by MTSS GPT. AI can make mistakes. Consider checking important information.')
160
+
161
+ # # # Prepare chat history text for display
162
+ # # history_text = "\n\n".join(f"Q: {entry[0]}\nA: {entry[1]}" for entry in st.session_state.history)
163
+ # # Prepare chat history text for display in reverse order
164
+ # history_text = "\n\n".join(f"Q: {entry[0]}\nA: {entry[1]}" for entry in reversed(st.session_state.history))
165
+
166
+ # # Display chat history
167
+ # st.text_area('Chat History', value=history_text, height=800)
168
+
169
+
170
+
171
+
172
+
173
  import streamlit as st
174
+ import openai
 
 
 
 
 
175
  import random
176
 
177
  # Fetch the OpenAI API key from Streamlit secrets
178
  openai_api_key = st.secrets["openai_api_key"]
179
 
180
+ # Initialize the OpenAI service with API key
181
+ openai.api_key = openai_api_key
182
+
183
  # Fetch Pinecone API key and environment from Streamlit secrets
184
  pinecone_api_key = st.secrets["pinecone_api_key"]
185
  pinecone_environment = st.secrets["pinecone_environment"]
186
 
187
+ # AUTHENTICATE/INITIALIZE PINCONE SERVICE
188
+ from pinecone import Pinecone
189
+ pc = Pinecone()
190
 
191
  # Define the name of the Pinecone index
192
+ index_name = 'mimtssinkqa'
 
 
 
193
 
194
+ # Initialize the OpenAI embeddings object
195
+ from langchain_openai import OpenAIEmbeddings
196
+ embeddings = OpenAIEmbeddings()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
+ # LOAD VECTOR STORE FROM EXISTING INDEX
199
+ from langchain_community.vectorstores import Pinecone
200
+ vector_store = Pinecone.from_existing_index(index_name='mimtssinkqa', embedding=embeddings)
201
 
202
  def ask_with_memory(vector_store, query, chat_history=[]):
203
+ from langchain_openai import ChatOpenAI
204
  from langchain.chains import ConversationalRetrievalChain
205
+ from langchain.memory import ConversationBufferMemory
206
+
207
+ from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
208
+
209
+ llm = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=0.5)
210
 
211
+ retriever = vector_store.as_retriever(search_type='similarity', search_kwargs={'k': 3})
 
 
212
 
213
+ memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)
214
+
215
+ system_template = r'''
216
+ Use the following pieces of context to answer the user's question. The title of the article is Intensifying literacy Instruction: Essential Practices. Do not mention the Header unless asked.
217
+ ----------------
218
+ Context: ```{context}```
219
+ '''
220
+
221
+ user_template = '''
222
+ Question: ```{question}```
223
+ Chat History: ```{chat_history}```
224
+ '''
225
+
226
+ messages= [
227
+ SystemMessagePromptTemplate.from_template(system_template),
228
+ HumanMessagePromptTemplate.from_template(user_template)
229
+ ]
230
+
231
+ qa_prompt = ChatPromptTemplate.from_messages (messages)
232
+
233
+ chain = ConversationalRetrievalChain.from_llm(llm=llm, retriever=retriever, memory=memory,chain_type='stuff', combine_docs_chain_kwargs={'prompt': qa_prompt}, verbose=False
234
+ )
235
+
236
+ result = chain.invoke({'question': query, 'chat_history': st.session_state['history']})
237
  # Append to chat history as a dictionary
238
  st.session_state['history'].append((query, result['answer']))
239
 
 
320
 
321
  q = st.text_input(label='Ask a question or make a request ', value='', placeholder=st.session_state.placeholder)
322
  # q = st.text_input(label='Ask a question or make a request ', value='')
 
 
 
 
 
 
323
 
324
  if q:
325
  with st.spinner('Thinking...'):