diff --git a/app.py b/app.py index 1a5cc7fd377c1c2eadb456833a43f42a759469a8..57ea4e286efdd56330a59cef2ac71e1229ce6de8 100644 --- a/app.py +++ b/app.py @@ -36,17 +36,18 @@ OPENAI_API_KEY = manage_sensitive("openai_api_key") os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY # db connection -conn_str = ( - "DRIVER={ODBC Driver 17 for SQL Server};SERVER=" - + DB_SERVER - + ";DATABASE=" - + DB_NAME - + ";UID=" - + DB_USER - + ";PWD=" - + DB_PASSWORD -) -conn = pyodbc.connect(conn_str) +def get_db_connection(): + conn_str = ( + "DRIVER={ODBC Driver 17 for SQL Server};SERVER=" + + DB_SERVER + + ";DATABASE=" + + DB_NAME + + ";UID=" + + DB_USER + + ";PWD=" + + DB_PASSWORD + ) + return pyodbc.connect(conn_str) # page metadata st.set_page_config( @@ -93,11 +94,11 @@ vectordb = FAISS.load_local("faiss_index", embedding) docsearch = vectordb.as_retriever() with st.form(key="query_form"): - query = st.text_input("Enter your research question:") + user_question = st.text_input("Enter your research question:") submit_button = st.form_submit_button("Submit") if submit_button: - docs = docsearch.get_relevant_documents(query) + docs = docsearch.get_relevant_documents(user_question) template="""You are a helpful assistant that tells a researcher whether their idea is appropriate given the data in the MPOG database. The MPOG database contains the following data elements that may be relevant to the researcher's ideas. @@ -162,21 +163,21 @@ with st.form(key="query_form"): [system_message_prompt, human_message_prompt]) with st.spinner("Thinking..."): submit_time = datetime.datetime.now() - result = chat(chat_prompt.format_prompt(context=docs, question=query).to_messages()) + result = chat(chat_prompt.format_prompt(context=docs, question=user_question).to_messages()) response_time = datetime.datetime.now() st.markdown(result.content) try: - with conn: + with get_db_connection() as conn: cursor = conn.cursor() query = """ - INSERT INTO [DS_apps].[dbo].[mpog_helper] (user_input, llm_response, request_sent, response_received) + INSERT INTO [dbo].[mpog_helper] (user_input, llm_response, request_sent, response_received) VALUES (?, ?, ?, ?) """ - - cursor.execute(query, (query, result.content, submit_time, response_time)) - st.success("Your idea has been recorded and may be reviewed by the MPOG Steering Committee.") + cursor.execute(query, (user_question, result.content, submit_time, response_time)) + + st.success("Your idea has also been recorded and may be reviewed by the MPOG steering committee.") except Exception as e: st.error("Something went wrong, and your idea was not recorded for review by the MPOG Steering Committee. Give the following message when asking for help from IT or Data Science:") st.error(e)