srinuksv commited on
Commit
2b44908
1 Parent(s): d796bd3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -36
app.py CHANGED
@@ -1,16 +1,18 @@
1
  import os
2
  from dotenv import load_dotenv
3
  import gradio as gr
4
- from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
5
  from llama_index.llms.huggingface import HuggingFaceInferenceAPI
6
  from llama_index.embeddings.huggingface import HuggingFaceEmbedding
7
  from sentence_transformers import SentenceTransformer
8
- from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate, Settings
 
9
  load_dotenv()
 
10
  # Configure the Llama index settings
11
  Settings.llm = HuggingFaceInferenceAPI(
12
- model_name="google/gemma-1.1-7b-it",
13
- tokenizer_name="google/gemma-1.1-7b-it",
14
  context_window=3000,
15
  token=os.getenv("HF_TOKEN"),
16
  max_new_tokens=512,
@@ -24,10 +26,13 @@ Settings.embed_model = HuggingFaceEmbedding(
24
  PERSIST_DIR = "db"
25
  PDF_DIRECTORY = 'data' # Changed to the directory containing PDFs
26
 
27
- # Ensure PDF directory exists
28
  os.makedirs(PDF_DIRECTORY, exist_ok=True)
29
  os.makedirs(PERSIST_DIR, exist_ok=True)
30
 
 
 
 
31
  def data_ingestion_from_directory():
32
  # Use SimpleDirectoryReader on the directory containing the PDF files
33
  documents = SimpleDirectoryReader(PDF_DIRECTORY).load_data()
@@ -40,21 +45,7 @@ def handle_query(query):
40
  (
41
  "user",
42
  """
43
- Provide the best user experience by delivering accurate and professional responses to user inquiries. Ensure all interactions reflect the professionalism and expertise of RedfernsTech.
44
- Guidelines:
45
- Professional Tone:
46
- Always maintain a polite, professional, and helpful tone.
47
- Use clear and concise language.
48
- Single Best Answer:
49
- Provide only one comprehensive and accurate answer to each question.
50
- Ensure the response is detailed enough to address the user’s inquiry fully.
51
- Redirect Personal Questions:
52
- If users ask personal questions about the chatbot, redirect them to ask about the company.
53
- Example: "For more information about RedfernsTech, please ask me specific questions about our products or services."
54
- Company-Centric Responses:
55
- Focus on delivering information relevant to RedfernsTech’s products, services, and values.
56
- Highlight the benefits and features of RedfernsTech offerings whenever possible.
57
- Context:
58
  {context_str}
59
  Question:
60
  {query_str}
@@ -67,31 +58,31 @@ def handle_query(query):
67
  storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
68
  index = load_index_from_storage(storage_context)
69
 
70
- query_engine = index.as_query_engine(text_qa_template=text_qa_template)
 
 
 
 
 
 
71
  answer = query_engine.query(query)
72
 
73
  if hasattr(answer, 'response'):
74
- return answer.response
75
  elif isinstance(answer, dict) and 'response' in answer:
76
- return answer['response']
77
  else:
78
- return "Sorry, I couldn't find an answer."
79
 
80
- # Example usage
 
81
 
82
- # Process PDF ingestion from directory
 
 
83
  print("Processing PDF ingestion from directory:", PDF_DIRECTORY)
84
  data_ingestion_from_directory()
85
 
86
- # Example query
87
- query = "How do I use the RedfernsTech Q&A assistant?"
88
- print("Query:", query)
89
- response = handle_query(query)
90
- print("Answer:", response)
91
- # prompt: create a gradio chatbot for this
92
-
93
-
94
-
95
  # Define the input and output components for the Gradio interface
96
  input_component = gr.Textbox(
97
  show_label=False,
@@ -100,9 +91,14 @@ input_component = gr.Textbox(
100
 
101
  output_component = gr.Textbox()
102
 
 
 
 
 
 
103
  # Create the Gradio interface
104
  interface = gr.Interface(
105
- fn=handle_query,
106
  inputs=input_component,
107
  outputs=output_component,
108
  title="RedfernsTech Q&A Chatbot",
 
1
  import os
2
  from dotenv import load_dotenv
3
  import gradio as gr
4
+ from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate, Settings
5
  from llama_index.llms.huggingface import HuggingFaceInferenceAPI
6
  from llama_index.embeddings.huggingface import HuggingFaceEmbedding
7
  from sentence_transformers import SentenceTransformer
8
+
9
+ # Load environment variables
10
  load_dotenv()
11
+
12
  # Configure the Llama index settings
13
  Settings.llm = HuggingFaceInferenceAPI(
14
+ model_name="meta-llama/Meta-Llama-3-8B-Instruct",
15
+ tokenizer_name="meta-llama/Meta-Llama-3-8B-Instruct",
16
  context_window=3000,
17
  token=os.getenv("HF_TOKEN"),
18
  max_new_tokens=512,
 
26
  PERSIST_DIR = "db"
27
  PDF_DIRECTORY = 'data' # Changed to the directory containing PDFs
28
 
29
+ # Ensure directories exist
30
  os.makedirs(PDF_DIRECTORY, exist_ok=True)
31
  os.makedirs(PERSIST_DIR, exist_ok=True)
32
 
33
+ # Variable to store current chat conversation
34
+ current_chat_history = []
35
+
36
  def data_ingestion_from_directory():
37
  # Use SimpleDirectoryReader on the directory containing the PDF files
38
  documents = SimpleDirectoryReader(PDF_DIRECTORY).load_data()
 
45
  (
46
  "user",
47
  """
48
+ You are now the RedFerns Tech chatbot. Your aim is to provide answers to the user based on the conversation flow only.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  {context_str}
50
  Question:
51
  {query_str}
 
58
  storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
59
  index = load_index_from_storage(storage_context)
60
 
61
+ # Use chat history to enhance response
62
+ context_str = ""
63
+ for past_query, response in reversed(current_chat_history):
64
+ if past_query.strip():
65
+ context_str += f"User asked: '{past_query}'\nBot answered: '{response}'\n"
66
+
67
+ query_engine = index.as_query_engine(text_qa_template=text_qa_template, context_str=context_str)
68
  answer = query_engine.query(query)
69
 
70
  if hasattr(answer, 'response'):
71
+ response = answer.response
72
  elif isinstance(answer, dict) and 'response' in answer:
73
+ response = answer['response']
74
  else:
75
+ response = "Sorry, I couldn't find an answer."
76
 
77
+ # Update current chat history
78
+ current_chat_history.append((query, response))
79
 
80
+ return response
81
+
82
+ # Example usage: Process PDF ingestion from directory
83
  print("Processing PDF ingestion from directory:", PDF_DIRECTORY)
84
  data_ingestion_from_directory()
85
 
 
 
 
 
 
 
 
 
 
86
  # Define the input and output components for the Gradio interface
87
  input_component = gr.Textbox(
88
  show_label=False,
 
91
 
92
  output_component = gr.Textbox()
93
 
94
+ # Function to handle queries
95
+ def chatbot_handler(query):
96
+ response = handle_query(query)
97
+ return response
98
+
99
  # Create the Gradio interface
100
  interface = gr.Interface(
101
+ fn=chatbot_handler,
102
  inputs=input_component,
103
  outputs=output_component,
104
  title="RedfernsTech Q&A Chatbot",