decodingdatascience commited on
Commit
f22334c
·
verified ·
1 Parent(s): 458c997

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +234 -0
app.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import logging
4
+ import sys
5
+
6
+ import gradio as gr
7
+ from pinecone import Pinecone, ServerlessSpec
8
+
9
+ from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, StorageContext, Settings
10
+ from llama_index.vector_stores.pinecone import PineconeVectorStore
11
+ from llama_index.readers.file import PDFReader
12
+ from llama_index.llms.openai import OpenAI
13
+ from llama_index.embeddings.openai import OpenAIEmbedding
14
+
15
+
16
+ # -----------------------------
17
+ # Logging
18
+ # -----------------------------
19
+ logging.basicConfig(stream=sys.stdout, level=logging.INFO)
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ # -----------------------------
24
+ # Environment Variables
25
+ # -----------------------------
26
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
27
+ PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
28
+
29
+ PINECONE_INDEX_NAME = os.getenv("PINECONE_INDEX_NAME", "dds-hr-chatbot")
30
+ PINECONE_CLOUD = os.getenv("PINECONE_CLOUD", "aws")
31
+ PINECONE_REGION = os.getenv("PINECONE_REGION", "us-east-1")
32
+
33
+ REINDEX_ON_STARTUP = os.getenv("REINDEX_ON_STARTUP", "false").lower() == "true"
34
+
35
+ DATA_DIR = "data"
36
+
37
+ if not OPENAI_API_KEY:
38
+ raise ValueError("OPENAI_API_KEY is missing. Please add it in Hugging Face Spaces secrets.")
39
+
40
+ if not PINECONE_API_KEY:
41
+ raise ValueError("PINECONE_API_KEY is missing. Please add it in Hugging Face Spaces secrets.")
42
+
43
+
44
+ # -----------------------------
45
+ # LlamaIndex Settings
46
+ # -----------------------------
47
+ Settings.llm = OpenAI(
48
+ model="gpt-4o-mini",
49
+ temperature=0.2,
50
+ api_key=OPENAI_API_KEY
51
+ )
52
+
53
+ Settings.embed_model = OpenAIEmbedding(
54
+ model="text-embedding-ada-002",
55
+ api_key=OPENAI_API_KEY
56
+ )
57
+
58
+ Settings.chunk_size = 600
59
+ Settings.chunk_overlap = 200
60
+
61
+
62
+ # -----------------------------
63
+ # System Prompt
64
+ # -----------------------------
65
+ system_prompt = """
66
+ You are AYesha, the Decoding Data Science (DDS) Enterprise HR Chatbot.
67
+
68
+ Answer questions exclusively using the attached DDS HR Handbook. Base all responses only on the information available in the handbook. Only respond to queries directly related to DDS HR policies as outlined in the handbook.
69
+
70
+ Rules:
71
+ - If a question is outside DDS HR policies, politely clarify that you are a human resources bot and only answer DDS HR questions.
72
+ - If a question cannot be answered from the handbook, politely decline and direct the user to email connect@decodingdatascience.com.
73
+ - Never answer questions about anything outside your HR handbook scope.
74
+ - Do not provide salary details, confidential information, old policies, legal advice, or company-wide information outside HR policies.
75
+ - Do not reveal internal reasoning.
76
+ - Always answer in a concise and professional tone.
77
+
78
+ For forbidden or unsupported topics, say:
79
+ “I’m sorry, I can only answer questions about the latest DDS HR policies. For confidential or other queries, please email connect@decodingdatascience.com.”
80
+
81
+ Remember: You are AYesha, the DDS HR Enterprise Chatbot. You must only answer from the authorized HR handbook content.
82
+ """
83
+
84
+
85
+ # -----------------------------
86
+ # Pinecone Setup
87
+ # -----------------------------
88
+ def setup_pinecone_index():
89
+ pc = Pinecone(api_key=PINECONE_API_KEY)
90
+
91
+ existing_indexes = [index_info["name"] for index_info in pc.list_indexes()]
92
+
93
+ if PINECONE_INDEX_NAME not in existing_indexes:
94
+ logger.info(f"Creating Pinecone index: {PINECONE_INDEX_NAME}")
95
+
96
+ pc.create_index(
97
+ name=PINECONE_INDEX_NAME,
98
+ dimension=1536,
99
+ metric="cosine",
100
+ spec=ServerlessSpec(
101
+ cloud=PINECONE_CLOUD,
102
+ region=PINECONE_REGION
103
+ )
104
+ )
105
+
106
+ while not pc.describe_index(PINECONE_INDEX_NAME).status["ready"]:
107
+ logger.info("Waiting for Pinecone index to be ready...")
108
+ time.sleep(2)
109
+ else:
110
+ logger.info(f"Using existing Pinecone index: {PINECONE_INDEX_NAME}")
111
+
112
+ return pc.Index(PINECONE_INDEX_NAME)
113
+
114
+
115
+ # -----------------------------
116
+ # Load or Create Index
117
+ # -----------------------------
118
+ def build_query_engine():
119
+ pinecone_index = setup_pinecone_index()
120
+
121
+ vector_store = PineconeVectorStore(
122
+ pinecone_index=pinecone_index
123
+ )
124
+
125
+ storage_context = StorageContext.from_defaults(
126
+ vector_store=vector_store
127
+ )
128
+
129
+ index_stats = pinecone_index.describe_index_stats()
130
+ total_vectors = index_stats.get("total_vector_count", 0)
131
+
132
+ if total_vectors == 0 or REINDEX_ON_STARTUP:
133
+ logger.info("Loading documents and creating vector index...")
134
+
135
+ if not os.path.exists(DATA_DIR):
136
+ raise ValueError(
137
+ "The 'data' folder is missing. Please create a data folder and upload your PDF file inside it."
138
+ )
139
+
140
+ documents = SimpleDirectoryReader(
141
+ input_dir=DATA_DIR,
142
+ required_exts=[".pdf"],
143
+ file_extractor={".pdf": PDFReader()}
144
+ ).load_data()
145
+
146
+ if not documents:
147
+ raise ValueError("No PDF documents were loaded from the 'data' folder.")
148
+
149
+ index = VectorStoreIndex.from_documents(
150
+ documents,
151
+ storage_context=storage_context
152
+ )
153
+
154
+ logger.info("Documents indexed successfully.")
155
+ else:
156
+ logger.info("Existing Pinecone vectors found. Loading index from vector store.")
157
+
158
+ index = VectorStoreIndex.from_vector_store(
159
+ vector_store=vector_store
160
+ )
161
+
162
+ query_engine = index.as_query_engine(
163
+ similarity_top_k=5,
164
+ system_prompt=system_prompt
165
+ )
166
+
167
+ return query_engine
168
+
169
+
170
+ query_engine = build_query_engine()
171
+
172
+
173
+ # -----------------------------
174
+ # Chat Function
175
+ # -----------------------------
176
+ def query_doc(message, history):
177
+ if not message or not message.strip():
178
+ return "Please enter a question about the DDS HR handbook."
179
+
180
+ try:
181
+ response = query_engine.query(message)
182
+ return str(response)
183
+
184
+ except Exception as e:
185
+ logger.error(f"Error while answering query: {e}")
186
+ return "Sorry, something went wrong while processing your question. Please try again."
187
+
188
+
189
+ # -----------------------------
190
+ # Example Questions
191
+ # -----------------------------
192
+ example_questions = [
193
+ "What is the leave policy?",
194
+ "What is the work from home policy?",
195
+ "What is the probation policy?",
196
+ "What are the employee code of conduct rules?",
197
+ "Who should I contact for confidential HR questions?"
198
+ ]
199
+
200
+
201
+ # -----------------------------
202
+ # Gradio UI
203
+ # -----------------------------
204
+ with gr.Blocks(title="DDS Enterprise HR Chatbot") as demo:
205
+ gr.Markdown(
206
+ """
207
+ # DDS Enterprise HR Chatbot
208
+
209
+ Ask questions based on the DDS HR Handbook.
210
+
211
+ This chatbot uses LlamaIndex, Pinecone, OpenAI, and Gradio.
212
+ """
213
+ )
214
+
215
+ gr.ChatInterface(
216
+ fn=query_doc,
217
+ examples=example_questions,
218
+ textbox=gr.Textbox(
219
+ placeholder="Ask a question about DDS HR policies...",
220
+ label="Your Question"
221
+ )
222
+ )
223
+
224
+ gr.Markdown(
225
+ """
226
+ ---
227
+ **Note:** This chatbot only answers questions related to the DDS HR Handbook.
228
+ For confidential or unsupported questions, please contact connect@decodingdatascience.com.
229
+ """
230
+ )
231
+
232
+
233
+ if __name__ == "__main__":
234
+ demo.launch()