schellrw commited on
Commit
ae51f0c
β€’
1 Parent(s): d381608

os env var from hf

Browse files
Files changed (1) hide show
  1. app.py +145 -147
app.py CHANGED
@@ -1,147 +1,145 @@
1
- from dataclasses import dataclass
2
- from typing import Literal
3
- import streamlit as st
4
- from langchain_pinecone.vectorstores import PineconeVectorStore
5
- from langchain_huggingface import HuggingFaceEmbeddings, HuggingFaceEndpoint
6
- from langchain.prompts import PromptTemplate
7
- from pinecone import Pinecone #, ServerlessSpec
8
- from langchain_community.chat_message_histories import ChatMessageHistory
9
- from langchain.memory import ConversationBufferMemory
10
- from langchain.chains import ConversationalRetrievalChain
11
- # from dotenv import load_dotenv
12
- # import os
13
-
14
- # Load environment variables from the .env file
15
- # load_dotenv()
16
-
17
- @dataclass
18
- class Message:
19
- """Class for keeping track of a chat message."""
20
- origin: Literal["πŸ‘€ Human", "πŸ‘¨πŸ»β€βš–οΈ Ai"]
21
- message: str
22
-
23
-
24
- def download_hugging_face_embeddings():
25
- embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2')
26
- return embeddings
27
-
28
-
29
- def initialize_session_state():
30
- if "history" not in st.session_state:
31
- st.session_state.history = []
32
- if "conversation" not in st.session_state:
33
- embeddings = download_hugging_face_embeddings()
34
- pc = Pinecone(api_key=st.secrets["PINECONE_API_KEY"])
35
- # pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
36
- index = pc.Index("il-legal")
37
- docsearch = PineconeVectorStore.from_existing_index(index_name="il-legal", embedding=embeddings)
38
-
39
- repo_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"
40
- llm = HuggingFaceEndpoint(
41
- repo_id=repo_id,
42
- model_kwargs={"huggingface_api_token":st.secrets["HUGGINGFACEHUB_API_TOKEN"]},
43
- # model_kwargs={"huggingface_api_token":os.environ["HUGGINGFACEHUB_API_TOKEN"]},
44
- temperature=0.5,
45
- top_k=10,
46
- )
47
-
48
- prompt_template = """
49
- You are a trained bot to guide people about Illinois Crimnal Law Statutes and the Safe-T Act. You will answer user's query with your knowledge and the context provided.
50
- If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.
51
- Do not say thank you and tell you are an AI Assistant and be open about everything.
52
- Use the following pieces of context to answer the users question.
53
- Context: {context}
54
- Question: {question}
55
- Only return the helpful answer below and nothing else.
56
- Helpful answer:
57
- """
58
-
59
- PROMPT = PromptTemplate(
60
- template=prompt_template,
61
- input_variables=["context", "question"])
62
-
63
- #chain_type_kwargs = {"prompt": PROMPT}
64
- message_history = ChatMessageHistory()
65
- memory = ConversationBufferMemory(
66
- memory_key="chat_history",
67
- output_key="answer",
68
- chat_memory=message_history,
69
- return_messages=True,
70
- )
71
- retrieval_chain = ConversationalRetrievalChain.from_llm(
72
- llm=llm,
73
- chain_type="stuff",
74
- retriever=docsearch.as_retriever(
75
- search_kwargs={
76
- 'filter': {'source': 'user_id'},
77
- }),
78
- return_source_documents=True,
79
- combine_docs_chain_kwargs={"prompt": PROMPT},
80
- memory= memory
81
- )
82
-
83
- st.session_state.conversation = retrieval_chain
84
-
85
-
86
- def on_click_callback():
87
- human_prompt = st.session_state.human_prompt
88
- st.session_state.human_prompt=""
89
- response = st.session_state.conversation(
90
- human_prompt
91
- )
92
- llm_response = response['answer']
93
- st.session_state.history.append(
94
- Message("πŸ‘€ Human", human_prompt)
95
- )
96
- st.session_state.history.append(
97
- Message("πŸ‘¨πŸ»β€βš–οΈ Ai", llm_response)
98
- )
99
-
100
-
101
- initialize_session_state()
102
-
103
- st.title("IL-Legal Advisor Chatbot")
104
-
105
- st.markdown(
106
- """
107
- πŸ‘‹ **Welcome to IL-Legal Advisor!**
108
- I'm here to assist you with your legal queries within the framework of Illinois criminal law. Whether you're navigating through specific legal issues or seeking general advice, I'm here to help.
109
-
110
- πŸ“š **How I Can Assist:**
111
-
112
- - Answer questions on various aspects of Illinois criminal law.
113
- - Guide you through legal processes relevant to Illinois.
114
- - Provide information on your rights and responsibilities as per Illinois legal standards.
115
-
116
- βš–οΈ **Disclaimer:**
117
-
118
- While I can provide general information, it may be necessary to consult with a qualified Illinois attorney for advice tailored to your specific situation.
119
-
120
- πŸ€– **Getting Started:**
121
-
122
- Feel free to ask any legal question related to Illinois law, using keywords like "pre-trial release," "motions," or "procedure." I'm here to assist you!
123
- Let's get started! How may I help you today?
124
- """
125
- )
126
-
127
- chat_placeholder = st.container()
128
- prompt_placeholder = st.form("chat-form")
129
-
130
- with chat_placeholder:
131
- for chat in st.session_state.history:
132
- st.markdown(f"{chat.origin} : {chat.message}")
133
-
134
- with prompt_placeholder:
135
- st.markdown("**Chat**")
136
- cols = st.columns((6, 1))
137
- cols[0].text_input(
138
- "Chat",
139
- label_visibility="collapsed",
140
- key="human_prompt",
141
- )
142
- cols[1].form_submit_button(
143
- "Submit",
144
- type="primary",
145
- on_click=on_click_callback,
146
- )
147
-
 
1
+ from dataclasses import dataclass
2
+ from typing import Literal
3
+ import streamlit as st
4
+ from langchain_pinecone.vectorstores import PineconeVectorStore
5
+ from langchain_huggingface import HuggingFaceEmbeddings, HuggingFaceEndpoint
6
+ from langchain.prompts import PromptTemplate
7
+ from pinecone import Pinecone #, ServerlessSpec
8
+ from langchain_community.chat_message_histories import ChatMessageHistory
9
+ from langchain.memory import ConversationBufferMemory
10
+ from langchain.chains import ConversationalRetrievalChain
11
+ # from dotenv import load_dotenv
12
+ import os
13
+
14
+ # Load environment variables from the .env file
15
+ # load_dotenv()
16
+
17
+ @dataclass
18
+ class Message:
19
+ """Class for keeping track of a chat message."""
20
+ origin: Literal["πŸ‘€ Human", "πŸ‘¨πŸ»β€βš–οΈ Ai"]
21
+ message: str
22
+
23
+
24
+ def download_hugging_face_embeddings():
25
+ embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2')
26
+ return embeddings
27
+
28
+
29
+ def initialize_session_state():
30
+ if "history" not in st.session_state:
31
+ st.session_state.history = []
32
+ if "conversation" not in st.session_state:
33
+ embeddings = download_hugging_face_embeddings()
34
+ pc = Pinecone(api_key=os.getenv["PINECONE_API_KEY"])
35
+ index = pc.Index("il-legal")
36
+ docsearch = PineconeVectorStore.from_existing_index(index_name="il-legal", embedding=embeddings)
37
+
38
+ repo_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"
39
+ llm = HuggingFaceEndpoint(
40
+ repo_id=repo_id,
41
+ model_kwargs={"huggingface_api_token":os.getenv["HUGGINGFACEHUB_API_TOKEN"]},
42
+ temperature=0.5,
43
+ top_k=10,
44
+ )
45
+
46
+ prompt_template = """
47
+ You are a trained bot to guide people about Illinois Crimnal Law Statutes and the Safe-T Act. You will answer user's query with your knowledge and the context provided.
48
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.
49
+ Do not say thank you and tell you are an AI Assistant and be open about everything.
50
+ Use the following pieces of context to answer the users question.
51
+ Context: {context}
52
+ Question: {question}
53
+ Only return the helpful answer below and nothing else.
54
+ Helpful answer:
55
+ """
56
+
57
+ PROMPT = PromptTemplate(
58
+ template=prompt_template,
59
+ input_variables=["context", "question"])
60
+
61
+ #chain_type_kwargs = {"prompt": PROMPT}
62
+ message_history = ChatMessageHistory()
63
+ memory = ConversationBufferMemory(
64
+ memory_key="chat_history",
65
+ output_key="answer",
66
+ chat_memory=message_history,
67
+ return_messages=True,
68
+ )
69
+ retrieval_chain = ConversationalRetrievalChain.from_llm(
70
+ llm=llm,
71
+ chain_type="stuff",
72
+ retriever=docsearch.as_retriever(
73
+ search_kwargs={
74
+ 'filter': {'source': 'user_id'},
75
+ }),
76
+ return_source_documents=True,
77
+ combine_docs_chain_kwargs={"prompt": PROMPT},
78
+ memory= memory
79
+ )
80
+
81
+ st.session_state.conversation = retrieval_chain
82
+
83
+
84
+ def on_click_callback():
85
+ human_prompt = st.session_state.human_prompt
86
+ st.session_state.human_prompt=""
87
+ response = st.session_state.conversation(
88
+ human_prompt
89
+ )
90
+ llm_response = response['answer']
91
+ st.session_state.history.append(
92
+ Message("πŸ‘€ Human", human_prompt)
93
+ )
94
+ st.session_state.history.append(
95
+ Message("πŸ‘¨πŸ»β€βš–οΈ Ai", llm_response)
96
+ )
97
+
98
+
99
+ initialize_session_state()
100
+
101
+ st.title("IL-Legal Advisor Chatbot")
102
+
103
+ st.markdown(
104
+ """
105
+ πŸ‘‹ **Welcome to IL-Legal Advisor!**
106
+ I'm here to assist you with your legal queries within the framework of Illinois criminal law. Whether you're navigating through specific legal issues or seeking general advice, I'm here to help.
107
+
108
+ πŸ“š **How I Can Assist:**
109
+
110
+ - Answer questions on various aspects of Illinois criminal law.
111
+ - Guide you through legal processes relevant to Illinois.
112
+ - Provide information on your rights and responsibilities as per Illinois legal standards.
113
+
114
+ βš–οΈ **Disclaimer:**
115
+
116
+ While I can provide general information, it may be necessary to consult with a qualified Illinois attorney for advice tailored to your specific situation.
117
+
118
+ πŸ€– **Getting Started:**
119
+
120
+ Feel free to ask any legal question related to Illinois law, using keywords like "pre-trial release," "motions," or "procedure." I'm here to assist you!
121
+ Let's get started! How may I help you today?
122
+ """
123
+ )
124
+
125
+ chat_placeholder = st.container()
126
+ prompt_placeholder = st.form("chat-form")
127
+
128
+ with chat_placeholder:
129
+ for chat in st.session_state.history:
130
+ st.markdown(f"{chat.origin} : {chat.message}")
131
+
132
+ with prompt_placeholder:
133
+ st.markdown("**Chat**")
134
+ cols = st.columns((6, 1))
135
+ cols[0].text_input(
136
+ "Chat",
137
+ label_visibility="collapsed",
138
+ key="human_prompt",
139
+ )
140
+ cols[1].form_submit_button(
141
+ "Submit",
142
+ type="primary",
143
+ on_click=on_click_callback,
144
+ )
145
+