Akash9281 commited on
Commit
3825759
·
verified ·
1 Parent(s): c4ea1ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -47
app.py CHANGED
@@ -1,10 +1,7 @@
1
- import os
2
  import gradio as gr
3
- from azure.storage.blob import BlobServiceClient
4
  from azure.search.documents import SearchClient
5
  from azure.search.documents.models import QueryType
6
- from azure.core.credentials import AzureKeyCredential
7
- import requests # Added for OpenAI API call
8
 
9
  # Azure Configuration
10
  SEARCH_ENDPOINT = "https://rag-search-service-ak.search.windows.net"
@@ -12,15 +9,14 @@ SEARCH_KEY = "Kq2Ww1XBwGCvV4JXTMvWT6qo1O9HprGo74elTSNYHiAzSeDETx4y"
12
  INDEX_NAME = "rag-index-ak"
13
  OPENAI_ENDPOINT = "https://rag-openai-service-ak.openai.azure.com/"
14
  OPENAI_KEY = "B1XyCaz87o456EVD949oODcGC8KTAEQsNLI7Yq5cnYKk41SMY9PtJQQJ99AKACHYHv6XJ3w3AAABACOGAaCZ"
15
- BLOB_CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=blobstorageak;AccountKey=r5AuAs93I3lLQpLq/Vhp43RkimOxIf3YQ4urlISTxTk07VUcZLzyH+7srlM0NAXjC0mnoHcjyMjS+AStuOv1Gw==;EndpointSuffix=core.windows.net"
16
- BLOB_CONTAINER_NAME = "dataragak"
17
 
18
- # Azure Clients
19
- search_client = SearchClient(endpoint=SEARCH_ENDPOINT, index_name=INDEX_NAME, credential=AzureKeyCredential(SEARCH_KEY))
20
 
21
- # Function: Call OpenAI API using Requests
22
  def call_openai_api(prompt):
23
- url = f"{OPENAI_ENDPOINT}openai/deployments/gpt-4/completions?api-version=2023-05-15"
24
  headers = {
25
  "Content-Type": "application/json",
26
  "Authorization": f"Bearer {OPENAI_KEY}"
@@ -31,56 +27,60 @@ def call_openai_api(prompt):
31
  "temperature": 0.7
32
  }
33
  response = requests.post(url, headers=headers, json=data)
34
- response_json = response.json()
35
- return response_json.get("choices", [{}])[0].get("text", "No response from OpenAI API.")
 
36
 
37
- # Function: Process User Query
38
- def process_query(question, history):
 
39
  search_results = search_client.search(
40
  search_text=question,
41
  query_type=QueryType.SIMPLE,
42
  top=3
43
  )
 
 
44
  content = "\n".join([result['content'] for result in search_results])
45
-
46
- # Call OpenAI API
 
 
47
  prompt = f"Use the following content to answer the question:\n{content}\nQuestion: {question}"
48
  return call_openai_api(prompt)
49
 
50
- # Function: Upload PDFs and Reindex
51
- def upload_pdfs(file_list):
52
- blob_service_client = BlobServiceClient.from_connection_string(BLOB_CONNECTION_STRING)
53
- container_client = blob_service_client.get_container_client(BLOB_CONTAINER_NAME)
54
-
55
- for file in file_list:
56
- blob_name = os.path.basename(file.name)
57
- blob_client = container_client.get_blob_client(blob_name)
58
- blob_client.upload_blob(file, overwrite=True)
59
-
60
- return "PDFs uploaded successfully! Reindexing may take some time."
61
 
62
  # Gradio UI
63
- def chatbot_ui(question, files):
64
- if files:
65
- upload_response = upload_pdfs(files)
66
- return upload_response, ""
 
67
 
68
- response = process_query(question, [])
69
- return "", response
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- # Gradio App
72
- demo = gr.Interface(
73
- chatbot_ui,
74
- inputs=[
75
- gr.Textbox(label="Ask a Question", placeholder="Type your question here..."),
76
- gr.File(label="Upload PDFs (optional)", file_types=[".pdf"], file_count="multiple")
77
- ],
78
- outputs=[
79
- gr.Textbox(label="Progress"),
80
- gr.Textbox(label="Chatbot Response")
81
- ],
82
- title="Azure-Powered RAG Chatbot"
83
- )
84
 
 
85
  if __name__ == "__main__":
86
- demo.launch()
 
 
1
  import gradio as gr
 
2
  from azure.search.documents import SearchClient
3
  from azure.search.documents.models import QueryType
4
+ import requests
 
5
 
6
  # Azure Configuration
7
  SEARCH_ENDPOINT = "https://rag-search-service-ak.search.windows.net"
 
9
  INDEX_NAME = "rag-index-ak"
10
  OPENAI_ENDPOINT = "https://rag-openai-service-ak.openai.azure.com/"
11
  OPENAI_KEY = "B1XyCaz87o456EVD949oODcGC8KTAEQsNLI7Yq5cnYKk41SMY9PtJQQJ99AKACHYHv6XJ3w3AAABACOGAaCZ"
12
+ DEPLOYMENT_ID = "gpt-4"
 
13
 
14
+ # Azure Cognitive Search Client
15
+ search_client = SearchClient(endpoint=SEARCH_ENDPOINT, index_name=INDEX_NAME, credential=SEARCH_KEY)
16
 
17
+ # Function to call Azure OpenAI API
18
  def call_openai_api(prompt):
19
+ url = f"{OPENAI_ENDPOINT}openai/deployments/{DEPLOYMENT_ID}/completions?api-version=2023-05-15"
20
  headers = {
21
  "Content-Type": "application/json",
22
  "Authorization": f"Bearer {OPENAI_KEY}"
 
27
  "temperature": 0.7
28
  }
29
  response = requests.post(url, headers=headers, json=data)
30
+ if response.status_code == 200:
31
+ return response.json()["choices"][0]["text"].strip()
32
+ return "Failed to generate a response."
33
 
34
+ # Function to process user queries
35
+ def process_query(question):
36
+ # Search in Azure Cognitive Search
37
  search_results = search_client.search(
38
  search_text=question,
39
  query_type=QueryType.SIMPLE,
40
  top=3
41
  )
42
+
43
+ # Extract search results content
44
  content = "\n".join([result['content'] for result in search_results])
45
+ if not content:
46
+ return "No relevant information found in the indexed documents."
47
+
48
+ # Use OpenAI to generate an enhanced response
49
  prompt = f"Use the following content to answer the question:\n{content}\nQuestion: {question}"
50
  return call_openai_api(prompt)
51
 
52
+ # Predefined questions
53
+ predefined_questions = [
54
+ "What is the purpose of the Master of Engineering Handbook?",
55
+ "What are the career opportunities in AI?",
56
+ "What are the program requirements for the Master of Engineering?",
57
+ "How can I build a career in AI?",
58
+ "What does the Master of Engineering handbook say about internships?"
59
+ ]
 
 
 
60
 
61
  # Gradio UI
62
+ def chatbot_ui(question):
63
+ if question in predefined_questions:
64
+ response = process_query(question)
65
+ return response
66
+ return "Please select a predefined question or enter a valid query."
67
 
68
+ # Gradio Interface
69
+ with gr.Blocks() as demo:
70
+ gr.Markdown("### Azure-Powered RAG Chatbot")
71
+ with gr.Row():
72
+ with gr.Column():
73
+ question_dropdown = gr.Dropdown(
74
+ choices=predefined_questions,
75
+ label="Select a predefined question",
76
+ value=predefined_questions[0]
77
+ )
78
+ submit_button = gr.Button("Submit")
79
+ with gr.Column():
80
+ response_output = gr.Textbox(label="Chatbot Response", lines=10)
81
 
82
+ submit_button.click(fn=chatbot_ui, inputs=question_dropdown, outputs=response_output)
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
+ # Run the Gradio app
85
  if __name__ == "__main__":
86
+ demo.launch(server_name="0.0.0.0", server_port=7860)