ajalisatgi commited on
Commit
1d91ffa
·
verified ·
1 Parent(s): bc10f71

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -0
app.py CHANGED
@@ -1,3 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # Initialize models and configurations
2
  model_name = 'intfloat/e5-small'
3
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@@ -9,3 +30,91 @@ vectordb = Chroma(
9
  persist_directory='./docs/chroma/',
10
  embedding_function=embedding_model
11
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ from langchain.embeddings import HuggingFaceEmbeddings
4
+ from langchain_community.vectorstores import Chroma
5
+ import openai
6
+ import time
7
+ import logging
8
+ from datasets import load_dataset
9
+ from nltk.tokenize import sent_tokenize
10
+ import nltk
11
+
12
+ # Set up logging
13
+ logging.basicConfig(level=logging.INFO)
14
+ logger = logging.getLogger(__name__)
15
+
16
+ # Initialize OpenAI API key
17
+ openai.api_key = 'YOUR_API_KEY' # Replace with your API key
18
+
19
+ # Download NLTK data
20
+ nltk.download('punkt')
21
+
22
  # Initialize models and configurations
23
  model_name = 'intfloat/e5-small'
24
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
30
  persist_directory='./docs/chroma/',
31
  embedding_function=embedding_model
32
  )
33
+
34
+ def process_query(query):
35
+ try:
36
+ logger.info(f"Processing query: {query}")
37
+
38
+ # Get relevant documents
39
+ relevant_docs = vectordb.similarity_search(query, k=30)
40
+ context = " ".join([doc.page_content for doc in relevant_docs])
41
+
42
+ # Add delay to respect API rate limits
43
+ time.sleep(1)
44
+
45
+ # Generate response using OpenAI
46
+ response = openai.chat.completions.create(
47
+ model="gpt-4",
48
+ messages=[
49
+ {"role": "system", "content": "You are a helpful assistant."},
50
+ {"role": "user", "content": f"Given the document: {context}\n\nGenerate a response to the query: {query}"}
51
+ ],
52
+ max_tokens=300,
53
+ temperature=0.7,
54
+ )
55
+
56
+ answer = response.choices[0].message.content.strip()
57
+ logger.info("Successfully generated response")
58
+
59
+ # Extract and display metrics
60
+ metrics = extract_metrics(query, answer, relevant_docs)
61
+
62
+ return answer, metrics
63
+
64
+ except Exception as e:
65
+ logger.error(f"Error processing query: {str(e)}")
66
+ return f"Error: {str(e)}", "Metrics unavailable"
67
+
68
+ def extract_metrics(query, response, relevant_docs):
69
+ try:
70
+ context = " ".join([doc.page_content for doc in relevant_docs])
71
+ metrics_prompt = f"""
72
+ Question: {query}
73
+ Context: {context}
74
+ Response: {response}
75
+
76
+ Extract metrics for:
77
+ - Context Relevance
78
+ - Context Utilization
79
+ - Completeness
80
+ - Response Quality
81
+ """
82
+
83
+ metrics_response = openai.chat.completions.create(
84
+ model="gpt-4",
85
+ messages=[{"role": "user", "content": metrics_prompt}],
86
+ max_tokens=150,
87
+ temperature=0.7,
88
+ )
89
+
90
+ return metrics_response.choices[0].message.content.strip()
91
+ except Exception as e:
92
+ return "Metrics calculation failed"
93
+
94
+ # Create Gradio interface
95
+ demo = gr.Interface(
96
+ fn=process_query,
97
+ inputs=[
98
+ gr.Textbox(
99
+ label="Enter your question",
100
+ placeholder="Type your question here...",
101
+ lines=2
102
+ )
103
+ ],
104
+ outputs=[
105
+ gr.Textbox(label="Answer", lines=5),
106
+ gr.Textbox(label="Metrics", lines=4)
107
+ ],
108
+ title="RAG-Powered Question Answering System",
109
+ description="Ask questions and get answers based on the embedded document knowledge.",
110
+ examples=[
111
+ ["What role does T-cell count play in severe human adenovirus type 55 (HAdV-55) infection?"],
112
+ ["In what school district is Governor John R. Rogers High School located?"],
113
+ ["Is there a functional neural correlate of individual differences in cardiovascular reactivity?"],
114
+ ["How do I select Natural mode?"]
115
+ ]
116
+ )
117
+
118
+ # Launch with debugging enabled
119
+ if __name__ == "__main__":
120
+ demo.launch(debug=True)