decodingdatascience commited on
Commit
899eccb
·
verified ·
1 Parent(s): 9bf3c2c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +142 -0
app.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # for hugingface to create app.py
2
+ # !pip install -U gradio pinecone llama-index llama-index-vector-stores-pinecone llama-index-readers-file pypdf
3
+ from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, StorageContext, Settings
4
+ # --- Imports ---
5
+ import logging
6
+ import sys
7
+ import gradio as gr
8
+
9
+ from google.colab import userdata
10
+ from pinecone import Pinecone, ServerlessSpec
11
+ from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, StorageContext , Settings
12
+ from llama_index.vector_stores.pinecone import PineconeVectorStore
13
+ from llama_index.readers.file import PDFReader
14
+ from llama_index.llms.openai import OpenAI
15
+ from llama_index.embeddings.openai import OpenAIEmbedding
16
+ # --- Logging ---
17
+ logging.basicConfig(stream=sys.stdout, level=logging.INFO)
18
+
19
+ #load keys for huggingface
20
+ import os
21
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
22
+ PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
23
+
24
+
25
+ Settings.llm = OpenAI(model="gpt-4o-mini", temperature=0.2)
26
+ Settings.embed_model = OpenAIEmbedding(model="text-embedding-ada-002")
27
+ Settings.chunk_size = 600
28
+ Settings.chunk_overlap = 200
29
+
30
+ # Define a system prompt
31
+ system_prompt = '''
32
+ You are AYesha, the Decoding Data Science (DDS) Enterprise HR Chatbot. Answer questions exclusively using the attached DDS HR Handbook. Base all responses on the most up-to-date information available in the handbook. Only respond to queries directly related to DDS HR policies as outlined in the handbook.
33
+
34
+ - If a question pertains to topics outside DDS HR policies, respond politely, clarifying that you are a human resources bot and only answer DDS HR questions.
35
+ - For questions you cannot answer (e.g., requests for old policies, salary details, or confidential information), politely decline and direct the user to email connect@decodingdatascience.com.
36
+ - Never answer questions about anything outside of your scope.
37
+ - Persist in following these constraints for any follow-up questions.
38
+ - Before answering, carefully check that the information and query are within the allowed scope. Follow chain-of-thought reasoning:
39
+ 1. First, reason step-by-step whether the question is covered in the current handbook and is within HR.
40
+ 2. Only after confirming, produce a final answer.
41
+
42
+ Format answers as concise, professional responses. Do not wrap answers in code blocks or any special formatting.
43
+
44
+ Output requirements:
45
+ - For allowed HR questions, answer concisely based only on the latest DDS HR handbook information.
46
+ - For forbidden topics, output: “I’m sorry, I can only answer questions about the latest DDS HR policies. For confidential or other queries, please email connect@decodingdatascience.com.”
47
+
48
+
49
+ **Example 1**
50
+ User: What is the leave encashment policy at DDS?
51
+ Reasoning: This is an HR policy question found in the latest handbook.
52
+ Final Answer: [Provide answer summarized from the latest handbook’s section on leave encashment]
53
+
54
+ **Example 2**
55
+ User: Can you tell me the salary range for Data Scientists?
56
+ Reasoning: Salary details are confidential and not shared by this bot.
57
+ Final Answer: I’m sorry, I can only answer questions about the latest DDS HR policies. For confidential or other queries, please email connect@decodingdatascience.com.
58
+
59
+ **Example 3**
60
+ User: Can you explain what DDS does as a company overall?
61
+ Reasoning: This is not an HR question, so it cannot be answered.
62
+ Final Answer: I’m sorry, I only answer DDS HR policy questions as outlined in the handbook.
63
+
64
+ (Real-world examples should be longer and use precise wording from the handbook where appropriate.)
65
+
66
+ **Important instructions:**
67
+ - Only answer questions directly supported by the latest DDS HR handbook.
68
+ - Decline politely and redirect to the provided email address for any questions outside scope or for confidential information.
69
+ - Always reason before concluding. Only present the answer after checking scope and source.
70
+
71
+ Remember: As AYesha, the DDS HR Enterprise Chatbot, you must never provide information outside authorized HR handbook content and always respond respectfully according to these constraints.
72
+
73
+ '''
74
+
75
+
76
+
77
+
78
+ # --- Initialize Pinecone ---
79
+ pc = Pinecone(api_key=PINECONE_API_KEY)
80
+ index_name = "quickstart"
81
+ dimension = 1536
82
+
83
+ # --- Delete index if it already exists (optional) ---
84
+ existing_indexes = [idx["name"] for idx in pc.list_indexes()]
85
+
86
+ if index_name in existing_indexes:
87
+ pc.delete_index(index_name)
88
+
89
+ # --- Create Pinecone index ---
90
+ pc.create_index(
91
+ name=index_name,
92
+ dimension=dimension,
93
+ metric="euclidean",
94
+ spec=ServerlessSpec(cloud="aws", region="us-east-1"),
95
+ )
96
+
97
+ pinecone_index = pc.Index(index_name)
98
+
99
+ # --- Load PDF documents from folder ---
100
+ documents = SimpleDirectoryReader(
101
+ input_dir="Data",
102
+ required_exts=[".pdf"],
103
+ file_extractor={".pdf": PDFReader()}
104
+ ).load_data()
105
+
106
+ if not documents:
107
+ raise ValueError("No PDF documents were loaded from the 'data' folder.")
108
+
109
+ # --- Create Vector Index ---
110
+ vector_store = PineconeVectorStore(pinecone_index=pinecone_index)
111
+ storage_context = StorageContext.from_defaults(vector_store=vector_store)
112
+
113
+ index = VectorStoreIndex.from_documents(
114
+ documents,
115
+ storage_context=storage_context
116
+ )
117
+
118
+ # --- Query Engine ---
119
+ query_engine = index.as_query_engine(system_prompt=system_prompt)
120
+
121
+ # --- Gradio App ---
122
+ def query_doc(prompt):
123
+ try:
124
+ response = query_engine.query(prompt)
125
+ return str(response)
126
+ except Exception as e:
127
+ return f"Error: {str(e)}"
128
+
129
+ gr.Interface(
130
+ fn=query_doc,
131
+ inputs=gr.Textbox(label="Ask a question about the document"),
132
+ outputs=gr.Textbox(label="Answer"),
133
+ title="DDS Enterprise HR Chatbot",
134
+ description="Ask questions related to HR for latest Information."
135
+ ).launch(share=True)
136
+
137
+
138
+
139
+
140
+
141
+
142
+