chukbert commited on
Commit
79c0556
·
verified ·
1 Parent(s): 4bcd7d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -45
app.py CHANGED
@@ -1,64 +1,105 @@
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  messages = [{"role": "system", "content": system_message}]
 
 
 
 
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
27
 
28
- response = ""
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
41
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
  demo = gr.ChatInterface(
47
- respond,
48
  additional_inputs=[
49
  gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
  ],
 
 
60
  )
61
 
62
-
63
  if __name__ == "__main__":
64
  demo.launch()
 
1
+ import pandas as pd
2
+ import openai
3
+ import faiss
4
+ import numpy as np
5
+ import time
6
+ import os
7
+ import pickle
8
  import gradio as gr
9
+ from langchain.embeddings.openai import OpenAIEmbeddings
10
+ from io import StringIO
11
+
12
+ def create_and_save_faiss_index(questions, embedding_model, index_file, embedding_file):
13
+ question_embeddings = embedding_model.embed_documents(questions)
14
+ faiss_index = faiss.IndexFlatL2(len(question_embeddings[0]))
15
+ faiss_index.add(np.array(question_embeddings))
16
+
17
+ faiss.write_index(faiss_index, index_file)
18
+ with open(embedding_file, 'wb') as f:
19
+ pickle.dump(question_embeddings, f)
20
+
21
+ return faiss_index, question_embeddings
22
+
23
+ def load_faiss_index(index_file, embedding_file):
24
+ faiss_index = faiss.read_index(index_file)
25
+ with open(embedding_file, 'rb') as f:
26
+ question_embeddings = pickle.load(f)
27
+ return faiss_index, question_embeddings
28
+
29
+ def retrieve_answer(question, faiss_index, embedding_model, answers, threshold=0.8):
30
+ question_embedding = embedding_model.embed_query(question)
31
+ distances, indices = faiss_index.search(np.array([question_embedding]), k=1)
32
+
33
+ closest_distance = distances[0][0]
34
+ closest_index = indices[0][0]
35
+ print(f"closest_distance: {closest_distance}")
36
+
37
+ if closest_distance > threshold:
38
+ return "No good match found in dataset. Using GPT-4o-mini to generate an answer."
39
+ else:
40
+ return answers[closest_index]
41
+
42
+ def ask_openai_gpt4(question):
43
+ response = openai.chat.completions.create(
44
+ messages=[
45
+ {"role": "user", "content": f"Answer the following medical question: {question}"}
46
+ ],
47
+ model="gpt-4o-mini",
48
+ max_tokens=150
49
+ )
50
+ return response.choices[0].message.content
51
+
52
+ def respond(message, history, system_message, max_tokens, temperature, top_p):
53
+ log_output = StringIO()
54
+
55
+ start_time = time.time()
56
+
57
+ if os.path.exists('faiss.index') and os.path.exists('embeddings.pkl'):
58
+ log_output.write("Loading FAISS index from disk...\n")
59
+ faiss_index, question_embeddings = load_faiss_index('faiss.index', 'embeddings.pkl')
60
+ else:
61
+ log_output.write("Creating and saving FAISS index...\n")
62
+ df = pd.read_csv("medquad.csv")
63
+ questions = df['question'].tolist()
64
+ answers = df['answer'].tolist()
65
+ embedding_model = OpenAIEmbeddings(openai_api_key=openai.api_key)
66
+ faiss_index, question_embeddings = create_and_save_faiss_index(questions, embedding_model, 'faiss.index', 'embeddings.pkl')
67
+
68
  messages = [{"role": "system", "content": system_message}]
69
+ for user_message, bot_response in history:
70
+ messages.append({"role": "user", "content": user_message})
71
+ if bot_response:
72
+ messages.append({"role": "assistant", "content": bot_response})
73
 
74
+ user_message = message
75
+ messages.append({"role": "user", "content": user_message})
 
 
 
76
 
77
+ response_text = retrieve_answer(user_message, faiss_index, OpenAIEmbeddings(openai_api_key=openai.api_key), answers=["..."], threshold=0.8)
78
 
79
+ if response_text == "No good match found in dataset. Using GPT-4o-mini to generate an answer.":
80
+ log_output.write("No good match found in dataset. Using GPT-4o-mini to generate an answer.\n")
81
+ response_text = ask_openai_gpt4(user_message)
82
 
83
+ # Stop the timer and calculate response time
84
+ end_time = time.time()
85
+ response_time = end_time - start_time # Time in seconds
 
 
 
 
 
86
 
87
+ # Yield the response with the logs and response time
88
+ yield response_text, f"Response time: {response_time:.4f} seconds", log_output.getvalue()
89
 
90
 
91
+ # Gradio ChatInterface with additional inputs for model settings and response time
 
 
92
  demo = gr.ChatInterface(
93
+ fn=respond,
94
  additional_inputs=[
95
  gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
96
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
97
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
98
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
 
 
 
 
 
 
99
  ],
100
+ title="Medical Chatbot with Customizable Parameters and Response Time",
101
+ description="A chatbot with customizable parameters using FAISS for quick responses or fallback to GPT-4 when no relevant answer is found. Response time is also tracked."
102
  )
103
 
 
104
  if __name__ == "__main__":
105
  demo.launch()