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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#------------------------------------------------------------------------
|
| 2 |
+
# Import Modules
|
| 3 |
+
#------------------------------------------------------------------------
|
| 4 |
+
|
| 5 |
+
import streamlit as st
|
| 6 |
+
import openai
|
| 7 |
+
import random
|
| 8 |
+
import os
|
| 9 |
+
from pinecone import Pinecone
|
| 10 |
+
from langchain.chat_models import ChatOpenAI
|
| 11 |
+
from langsmith import Client
|
| 12 |
+
|
| 13 |
+
#------------------------------------------------------------------------
|
| 14 |
+
# Load API Keys From the .env File & Load the OpenAI, Pinecone, and LangSmith Client
|
| 15 |
+
#------------------------------------------------------------------------
|
| 16 |
+
|
| 17 |
+
# Fetch the OpenAI API key from Streamlit secrets
|
| 18 |
+
OPENAI_API_KEY = st.secrets["OPENAI_API_KEY"]
|
| 19 |
+
# Retrieve the OpenAI API Key from secrets
|
| 20 |
+
openai.api_key = st.secrets["OPENAI_API_KEY"]
|
| 21 |
+
|
| 22 |
+
# # Fetch Pinecone API key and environment from Streamlit secrets
|
| 23 |
+
PINECONE_API_KEY = st.secrets["PINECONE_API_KEY"]
|
| 24 |
+
# # AUTHENTICATE/INITIALIZE PINCONE SERVICE
|
| 25 |
+
from pinecone import Pinecone
|
| 26 |
+
# PINECONE_API_KEY = "555c0e70-331d-4b43-aac7-5b3aac5078d6"
|
| 27 |
+
pc = Pinecone(api_key=PINECONE_API_KEY)
|
| 28 |
+
|
| 29 |
+
os.environ ["LANGCHAIN_API_KEY"] = str(os.getenv("LANGCHAIN_API_KEY"))
|
| 30 |
+
os.environ ["LANGCHAIN_TRACING_V2"] = "true"
|
| 31 |
+
os.environ ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
|
| 32 |
+
os.environ ["LANGCHAIN_PROJECT"] = "Inkqa"
|
| 33 |
+
|
| 34 |
+
client = Client() #langsmith client
|
| 35 |
+
|
| 36 |
+
#------------------------------------------------------------------------
|
| 37 |
+
# Initialize
|
| 38 |
+
#------------------------------------------------------------------------
|
| 39 |
+
|
| 40 |
+
# # Define the name of the Pinecone index
|
| 41 |
+
index_name = 'mimtssinkqa'
|
| 42 |
+
|
| 43 |
+
# Initialize the OpenAI embeddings object
|
| 44 |
+
from langchain_openai import OpenAIEmbeddings
|
| 45 |
+
embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY)
|
| 46 |
+
|
| 47 |
+
# LOAD VECTOR STORE FROM EXISTING INDEX
|
| 48 |
+
from langchain_community.vectorstores import Pinecone
|
| 49 |
+
vector_store = Pinecone.from_existing_index(index_name='mimtssinkqa', embedding=embeddings)
|
| 50 |
+
|
| 51 |
+
def ask_with_memory(vector_store, query, chat_history=[]):
|
| 52 |
+
from langchain_openai import ChatOpenAI
|
| 53 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 54 |
+
from langchain.memory import ConversationBufferMemory
|
| 55 |
+
|
| 56 |
+
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
|
| 57 |
+
|
| 58 |
+
llm = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=0.5, openai_api_key=OPENAI_API_KEY)
|
| 59 |
+
|
| 60 |
+
retriever = vector_store.as_retriever(search_type='similarity', search_kwargs={'k': 3})
|
| 61 |
+
|
| 62 |
+
memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)
|
| 63 |
+
|
| 64 |
+
system_template = r'''
|
| 65 |
+
Article Title: 'Intensifying Literacy Instruction: Essential Practices.'
|
| 66 |
+
Article Focus: The main focus of the article is reading and the secondary focus is writing.
|
| 67 |
+
Expertise: Assume the role of an expert literacy coach with in-depth knowledge of the Simple View of Reading, School-Wide Positive Behavioral Interventions and Supports (SWPBIS), and Social Emotional Learning (SEL).
|
| 68 |
+
Audience: Tailor your response for teachers and administrators seeking to enhance literacy instruction within their educational settings.
|
| 69 |
+
Response Requirements: Provide an answer utilizing the context provided. Unless specifically requested by the user, avoid mentioning the article's header.
|
| 70 |
+
Cover all necessary details relevant to the question posed, drawing on your expertise in literacy instruction and the Simple View of Reading.
|
| 71 |
+
Utilize paragraphs for detailed and descriptive explanations, and bullet points for highlighting key points or steps, ensuring the information is easily understood.
|
| 72 |
+
Conclude with a recapitulation of main points, summarizing the essential takeaways from your response.
|
| 73 |
+
----------------
|
| 74 |
+
Context: ```{context}```
|
| 75 |
+
'''
|
| 76 |
+
|
| 77 |
+
user_template = '''
|
| 78 |
+
Question: ```{question}```
|
| 79 |
+
Chat History: ```{chat_history}```
|
| 80 |
+
'''
|
| 81 |
+
|
| 82 |
+
messages= [
|
| 83 |
+
SystemMessagePromptTemplate.from_template(system_template),
|
| 84 |
+
HumanMessagePromptTemplate.from_template(user_template)
|
| 85 |
+
]
|
| 86 |
+
|
| 87 |
+
qa_prompt = ChatPromptTemplate.from_messages (messages)
|
| 88 |
+
|
| 89 |
+
chain = ConversationalRetrievalChain.from_llm(llm=llm, retriever=retriever, memory=memory,chain_type='stuff', combine_docs_chain_kwargs={'prompt': qa_prompt}, verbose=False
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
result = chain.invoke({'question': query, 'chat_history': st.session_state['history']})
|
| 93 |
+
# Append to chat history as a dictionary
|
| 94 |
+
st.session_state['history'].append((query, result['answer']))
|
| 95 |
+
|
| 96 |
+
return (result['answer'])
|
| 97 |
+
|
| 98 |
+
# Initialize chat history
|
| 99 |
+
if 'history' not in st.session_state:
|
| 100 |
+
st.session_state['history'] = []
|
| 101 |
+
|
| 102 |
+
# # STREAMLIT APPLICATION SETUP WITH PASSWORD
|
| 103 |
+
|
| 104 |
+
# Define the correct password
|
| 105 |
+
# correct_password = "MiBLSi"
|
| 106 |
+
|
| 107 |
+
#Add the image with a specified width
|
| 108 |
+
image_width = 300 # Set the desired width in pixels
|
| 109 |
+
st.image('MTSS.ai_Logo.png', width=image_width)
|
| 110 |
+
st.subheader('Ink QA™ | Dynamic PDFs')
|
| 111 |
+
|
| 112 |
+
# Using Markdown for formatted text
|
| 113 |
+
st.markdown("""
|
| 114 |
+
Resource: **Intensifying Literacy Instruction: Essential Practices**
|
| 115 |
+
""", unsafe_allow_html=True)
|
| 116 |
+
|
| 117 |
+
with st.sidebar:
|
| 118 |
+
# Password input field
|
| 119 |
+
# password = st.text_input("Enter Password:", type="password")
|
| 120 |
+
|
| 121 |
+
st.image('mimtss.png', width=200)
|
| 122 |
+
st.image('Literacy_Cover.png', width=200)
|
| 123 |
+
st.link_button("View | Download", "https://mimtsstac.org/sites/default/files/session-documents/Intensifying%20Literacy%20Instruction%20-%20Essential%20Practices%20%28NATIONAL%29.pdf")
|
| 124 |
+
|
| 125 |
+
Audio_Header_text = """
|
| 126 |
+
**Tune into Dr. St. Martin's introduction**"""
|
| 127 |
+
st.markdown(Audio_Header_text)
|
| 128 |
+
|
| 129 |
+
# Path or URL to the audio file
|
| 130 |
+
audio_file_path = 'Audio_Introduction_Literacy.m4a'
|
| 131 |
+
# Display the audio player widget
|
| 132 |
+
st.audio(audio_file_path, format='audio/mp4', start_time=0)
|
| 133 |
+
|
| 134 |
+
# Citation text with Markdown formatting
|
| 135 |
+
citation_Content_text = """
|
| 136 |
+
**Citation**
|
| 137 |
+
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.
|
| 138 |
+
|
| 139 |
+
**Table of Contents**
|
| 140 |
+
* **Introduction**: pg. 1
|
| 141 |
+
* **Intensifying Literacy Instruction: Essential Practices**: pg. 4
|
| 142 |
+
* **Purpose**: pg. 4
|
| 143 |
+
* **Practice 1**: Knowledge and Use of a Learning Progression for Developing Skilled Readers and Writers: pg. 6
|
| 144 |
+
* **Practice 2**: Design and Use of an Intervention Platform as the Foundation for Effective Intervention: pg. 13
|
| 145 |
+
* **Practice 3**: On-going Data-Based Decision Making for Providing and Intensifying Interventions: pg. 16
|
| 146 |
+
* **Practice 4**: Adaptations to Increase the Instructional Intensity of the Intervention: pg. 20
|
| 147 |
+
* **Practice 5**: Infrastructures to Support Students with Significant and Persistent Literacy Needs: pg. 24
|
| 148 |
+
* **Motivation and Engagement**: pg. 28
|
| 149 |
+
* **Considerations for Understanding How Students' Learning and Behavior are Enhanced**: pg. 28
|
| 150 |
+
* **Summary**: pg. 29
|
| 151 |
+
* **Endnotes**: pg. 30
|
| 152 |
+
* **Acknowledgment**: pg. 39
|
| 153 |
+
"""
|
| 154 |
+
st.markdown(citation_Content_text)
|
| 155 |
+
|
| 156 |
+
# if password == correct_password:
|
| 157 |
+
# Define a list of possible placeholder texts
|
| 158 |
+
placeholders = [
|
| 159 |
+
'Example: Summarize the article in 200 words or less',
|
| 160 |
+
'Example: What are the essential practices?',
|
| 161 |
+
'Example: I am a teacher, why is this resource important?',
|
| 162 |
+
'Example: How can this resource support my instruction in reading and writing?',
|
| 163 |
+
'Example: Does this resource align with the learning progression for developing skilled readers and writers?',
|
| 164 |
+
'Example: How does this resource address the needs of students scoring below the 20th percentile?',
|
| 165 |
+
'Example: Are there assessment tools included in this resource to monitor student progress?',
|
| 166 |
+
'Example: Does this resource provide guidance on data collection and analysis for monitoring student outcomes?',
|
| 167 |
+
"Example: How can this resource be used to support students' social-emotional development?",
|
| 168 |
+
"Example: How does this resource align with the district's literacy goals and objectives?",
|
| 169 |
+
'Example: What research and evidence support the effectiveness of this resource?',
|
| 170 |
+
'Example: Does this resource provide guidance on implementation fidelity'
|
| 171 |
+
]
|
| 172 |
+
|
| 173 |
+
# Select a random placeholder from the list
|
| 174 |
+
if 'placeholder' not in st.session_state:
|
| 175 |
+
st.session_state.placeholder = random.choice(placeholders)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# CLEAR THE TEXT BOX
|
| 179 |
+
with st.form("Question",clear_on_submit=True):
|
| 180 |
+
q = st.text_input(label='Ask a Question | Send a Prompt', placeholder=st.session_state.placeholder, value='', )
|
| 181 |
+
submitted = st.form_submit_button("Submit")
|
| 182 |
+
|
| 183 |
+
st.divider()
|
| 184 |
+
|
| 185 |
+
if submitted:
|
| 186 |
+
with st.spinner('Thinking...'):
|
| 187 |
+
answer = ask_with_memory(vector_store, q, st.session_state.history)
|
| 188 |
+
|
| 189 |
+
# st.write(q)
|
| 190 |
+
st.write(f"**{q}**")
|
| 191 |
+
|
| 192 |
+
import time
|
| 193 |
+
import random
|
| 194 |
+
|
| 195 |
+
def stream_answer():
|
| 196 |
+
for word in answer.split(" "):
|
| 197 |
+
yield word + " "
|
| 198 |
+
# time.sleep(0.02)
|
| 199 |
+
time.sleep(random.uniform(0.03, 0.08))
|
| 200 |
+
|
| 201 |
+
st.write(stream_answer)
|
| 202 |
+
|
| 203 |
+
# Display the response in a text area
|
| 204 |
+
# st.text_area('Response: ', value=answer, height=400, key="response_text_area")
|
| 205 |
+
# OR to display as Markdown (interprets Markdown formatting)
|
| 206 |
+
# st.markdown(answer)
|
| 207 |
+
|
| 208 |
+
st.success('Powered by MTSS GPT. AI can make mistakes. Consider checking important information.')
|
| 209 |
+
|
| 210 |
+
st.divider()
|
| 211 |
+
|
| 212 |
+
# # Prepare chat history text for display
|
| 213 |
+
history_text = "\n\n".join(f"Q: {entry[0]}\nA: {entry[1]}" for entry in reversed(st.session_state.history))
|
| 214 |
+
|
| 215 |
+
# Display chat history
|
| 216 |
+
st.text_area('Chat History', value=history_text, height=800)
|