File size: 9,707 Bytes
5135ab4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9633aea7-5c45-44f9-a78b-b5bc39984754",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_google_genai import ChatGoogleGenerativeAI\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain.chains import LLMChain\n",
    "\n",
    "import os\n",
    "\n",
    "import google.generativeai as genai\n",
    "from langchain.document_loaders import PyPDFLoader\n",
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings\n",
    "from langchain.vectorstores import FAISS\n",
    "import gradio as gr\n",
    "\n",
    "\n",
    "os.environ[\"MY_SECRET_KEY\"] = \"AIzaSyDRj3wAgqOCjc_D45W_u-G3y9dk5YDgxEo\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "41abde7b-366d-427e-8938-35ce7a4ed778",
   "metadata": {},
   "outputs": [],
   "source": [
    "#pip install pypdf\n",
    "#!pip install faiss-cpu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b7e3810f-c5fb-44d7-b4b7-a30ac507d78b",
   "metadata": {},
   "outputs": [],
   "source": [
    "google_api_key = os.environ[\"MY_SECRET_KEY\"]\n",
    "\n",
    "# Check if the API key was found\n",
    "if google_api_key:\n",
    "    # Set the environment variable if the API key was found\n",
    "    os.environ[\"GOOGLE_API_KEY\"] = google_api_key\n",
    "\n",
    "    llm = ChatGoogleGenerativeAI(\n",
    "        model=\"gemini-pro\",  # Specify the model name\n",
    "        google_api_key=os.environ[\"GOOGLE_API_KEY\"]\n",
    "    )\n",
    "else:\n",
    "    print(\"Error: GOOGLE_API_KEY not found in Colab secrets. Please store your API key.\")\n",
    "\n",
    "\n",
    "\n",
    "genai.configure(api_key=google_api_key)\n",
    "model = genai.GenerativeModel(\"gemini-pro\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ef330936-8c45-4aff-b2cf-fe9dfaaf2764",
   "metadata": {},
   "outputs": [],
   "source": [
    "work_dir=os.getcwd()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a55af811-7758-4090-a5f8-748b6192971b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Current Working Directory: /Users/saurabhverma/GENAI\n"
     ]
    }
   ],
   "source": [
    "# Verify file existence\n",
    "assert \"Team1.pdf\" in os.listdir(work_dir), \"Team1.pdf not found in the specified directory!\"\n",
    "print(f\"Current Working Directory: {os.getcwd()}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "7a0a4457-2f9c-40db-9dd4-d57e3edf1fd0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load PDF and split text\n",
    "pdf_path = \"Team1.pdf\"  # Ensure this file is uploaded to Colab\n",
    "loader = PyPDFLoader(pdf_path)\n",
    "documents = loader.load()\n",
    "\n",
    "# Split text into chunks\n",
    "text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=10)\n",
    "text_chunks = text_splitter.split_documents(documents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b5387499-a756-49de-86b0-96a5ce712ba7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate embeddings\n",
    "embeddings = GoogleGenerativeAIEmbeddings(model=\"models/embedding-001\")\n",
    "\n",
    "# Store embeddings in FAISS index\n",
    "vectorstore = FAISS.from_documents(text_chunks, embeddings)\n",
    "retriever = vectorstore.as_retriever(search_kwargs={\"k\": 4})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "35554163-75cd-4f0b-a538-565a48700245",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set up Gemini model\n",
    "llm = ChatGoogleGenerativeAI(model=\"gemini-2.0-flash-001\", temperature=0)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "e95b424b-11c1-46f3-9b4e-9e2d42d1f05d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gradio as gr\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain.chains import LLMChain\n",
    "\n",
    "def rag_query(query):\n",
    "    # Retrieve relevant documents\n",
    "    docs = retriever.get_relevant_documents(query)\n",
    "    \n",
    "    # Otherwise, use RAG\n",
    "    context = \"\\n\".join([doc.page_content for doc in docs])\n",
    "    prompt = f\"Context:\\n{context}\\n\\nQuestion: {query}\\nAnswer directly and concisely:\"\n",
    "\n",
    "    try:\n",
    "        response = llm.invoke(prompt)\n",
    "    except Exception as e:\n",
    "        response = f\"Error in RAG processing: {str(e)}\"\n",
    "\n",
    "    return response.content\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "552ff2fa-3c70-4054-803e-633efc7601f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gradio as gr\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain.chains import LLMChain\n",
    "from langchain_google_genai import ChatGoogleGenerativeAI\n",
    "\n",
    "# Initialize LLM once (avoid repeated initialization)\n",
    "llm = ChatGoogleGenerativeAI(model=\"gemini-2.0-flash\", temperature=0)\n",
    "\n",
    "# Define the general query function\n",
    "def general_query(query):\n",
    "    try:\n",
    "        # Define the prompt correctly\n",
    "        prompt = PromptTemplate.from_template(\"Answer the following query: {query}\")\n",
    "        \n",
    "        # Create an LLM Chain\n",
    "        chain = LLMChain(llm=llm, prompt=prompt)\n",
    "        \n",
    "        # Run chatbot and return response\n",
    "        response = chain.run(query=query)\n",
    "        \n",
    "        return response  # Return response directly (not response.content)\n",
    "    \n",
    "    except Exception as e:\n",
    "        return f\"Error: {str(e)}\"\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ab63a509-e927-405a-985b-d07039e05e9f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7860\n",
      "* Running on public URL: https://efeff91c52754b11ed.gradio.live\n",
      "\n",
      "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"https://efeff91c52754b11ed.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gradio as gr\n",
    "\n",
    "\n",
    "# Function to call the selected query method\n",
    "def query_router(query, method):\n",
    "    if method == \"Team Query\":  # Ensure exact match with dropdown options\n",
    "        return rag_query(query)\n",
    "    elif method == \"General Query\":\n",
    "        return general_query(query)\n",
    "    return \"Invalid selection!\"\n",
    "\n",
    "# Define local image paths\n",
    "logo_path = \"equinix-sign.jpg\"  # Ensure this file exists\n",
    "\n",
    "# Custom CSS for background styling\n",
    "custom_css = \"\"\"\n",
    ".gradio-container {\n",
    "    background-color: #f0f0f0;\n",
    "    text-align: center;\n",
    "}\n",
    "#logo img {\n",
    "    display: block;\n",
    "    margin: 0 auto;\n",
    "    max-width: 200px; /* Adjust size */\n",
    "}\n",
    "\"\"\"\n",
    "\n",
    "# Create Gradio UI\n",
    "with gr.Blocks(css=custom_css) as ui:\n",
    "    gr.Image(logo_path, elem_id=\"logo\", show_label=False, height=100, width=200)  # Display Logo\n",
    "    \n",
    "    # Title & Description\n",
    "    gr.Markdown(\"<h1 style='text-align: center; color: black;'>Equinix Chatbot for Automation Team</h1>\")\n",
    "    gr.Markdown(\"<p style='text-align: center; color: black;'>Ask me anything!</p>\")\n",
    "\n",
    "    # Input & Dropdown Section\n",
    "    with gr.Row():\n",
    "        query_input = gr.Textbox(label=\"Enter your query\")\n",
    "        query_method = gr.Dropdown([\"Team Query\", \"General Query\"], label=\"Select Query Type\")\n",
    "    \n",
    "    # Button for submitting query\n",
    "    submit_button = gr.Button(\"Submit\")\n",
    "\n",
    "    # Output Textbox\n",
    "    output_box = gr.Textbox(label=\"Response\", interactive=False)\n",
    "\n",
    "    # Button Click Event\n",
    "    submit_button.click(query_router, inputs=[query_input, query_method], outputs=output_box)\n",
    "\n",
    "# Launch UI\n",
    "ui.launch(share=True)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}