Spaces:
Runtime error
Runtime error
Refactoring (#48)
Browse filesRefactor the `Chatbot` class to make overall handling easier.
* Fix error logging
* Limit to words instead of chars
* Add support for text before the documents (useful for prompt engineering)
* return GPT responses separately
* put a check for relevance in a separate function
* use relevance to check if documents were found or not
- buster/chatbot.py +103 -64
buster/chatbot.py
CHANGED
@@ -8,7 +8,7 @@ import pandas as pd
|
|
8 |
import promptlayer
|
9 |
from openai.embeddings_utils import cosine_similarity, get_embedding
|
10 |
|
11 |
-
from buster.docparser import
|
12 |
|
13 |
logger = logging.getLogger(__name__)
|
14 |
logging.basicConfig(level=logging.INFO)
|
@@ -32,7 +32,7 @@ class ChatbotConfig:
|
|
32 |
embedding_model: OpenAI model to use to get embeddings.
|
33 |
top_k: Max number of documents to retrieve, ordered by cosine similarity
|
34 |
thresh: threshold for cosine similarity to be considered
|
35 |
-
|
36 |
completion_kwargs: kwargs for the OpenAI.Completion() method
|
37 |
separator: the separator to use, can be either "\n" or <p> depending on rendering.
|
38 |
link_format: the type of format to render links with, e.g. slack or markdown
|
@@ -45,7 +45,8 @@ class ChatbotConfig:
|
|
45 |
embedding_model: str = "text-embedding-ada-002"
|
46 |
top_k: int = 3
|
47 |
thresh: float = 0.7
|
48 |
-
|
|
|
49 |
|
50 |
completion_kwargs: dict = field(
|
51 |
default_factory=lambda: {
|
@@ -60,6 +61,7 @@ class ChatbotConfig:
|
|
60 |
separator: str = "\n"
|
61 |
link_format: str = "slack"
|
62 |
unknown_prompt: str = "I Don't know how to answer your question."
|
|
|
63 |
text_before_prompt: str = "I'm a chatbot, bleep bloop."
|
64 |
text_after_response: str = "Answer the following question:\n"
|
65 |
|
@@ -78,25 +80,23 @@ class Chatbot:
|
|
78 |
logger.info(f"embeddings loaded.")
|
79 |
|
80 |
def _init_unk_embedding(self):
|
81 |
-
logger.info("Generating UNK
|
82 |
-
unknown_prompt = self.cfg.unknown_prompt
|
83 |
-
engine = self.cfg.embedding_model
|
84 |
self.unk_embedding = get_embedding(
|
85 |
-
unknown_prompt,
|
86 |
-
engine=
|
87 |
)
|
88 |
|
89 |
def rank_documents(
|
90 |
self,
|
91 |
documents: pd.DataFrame,
|
92 |
query: str,
|
|
|
|
|
|
|
93 |
) -> pd.DataFrame:
|
94 |
"""
|
95 |
Compare the question to the series of documents and return the best matching documents.
|
96 |
"""
|
97 |
-
top_k = self.cfg.top_k
|
98 |
-
thresh = self.cfg.thresh
|
99 |
-
engine = self.cfg.embedding_model # EMBEDDING_MODEL
|
100 |
|
101 |
query_embedding = get_embedding(
|
102 |
query,
|
@@ -121,59 +121,64 @@ class Chatbot:
|
|
121 |
|
122 |
return matched_documents
|
123 |
|
124 |
-
def
|
125 |
-
|
126 |
-
|
127 |
-
"""
|
128 |
-
|
129 |
-
max_chars = self.cfg.max_chars
|
130 |
-
text_before_prompt = self.cfg.text_before_prompt
|
131 |
-
|
132 |
-
documents_list = candidates.text.to_list()
|
133 |
documents_str = " ".join(documents_list)
|
134 |
-
|
|
|
|
|
|
|
|
|
135 |
logger.info("truncating documents to fit...")
|
136 |
-
documents_str = documents_str[0:
|
|
|
137 |
|
138 |
-
return documents_str
|
139 |
|
140 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
141 |
"""
|
142 |
-
|
143 |
"""
|
144 |
-
|
145 |
-
|
146 |
-
response_text = "I did not find any relevant documentation related to your question."
|
147 |
-
return response_text
|
148 |
|
149 |
-
|
150 |
-
logger.info(f"Prompt: {prompt}")
|
151 |
# Call the API to generate a response
|
|
|
152 |
try:
|
153 |
-
|
154 |
-
completion_kwargs["prompt"] = prompt
|
155 |
-
response = openai.Completion.create(**completion_kwargs)
|
156 |
-
|
157 |
-
# Get the response text
|
158 |
-
response_text = response["choices"][0]["text"]
|
159 |
-
logger.info(f"GPT Response:\n{response_text}")
|
160 |
-
return response_text
|
161 |
|
162 |
except Exception as e:
|
163 |
# log the error and return a generic response instead.
|
164 |
-
|
|
|
|
|
165 |
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
|
171 |
-
def add_sources(self, response: str, matched_documents: pd.DataFrame):
|
172 |
"""
|
173 |
Add sources fromt the matched documents to the response.
|
174 |
"""
|
175 |
-
sep = self.cfg.separator # \n
|
176 |
-
format = self.cfg.link_format
|
177 |
|
178 |
urls = matched_documents.url.to_list()
|
179 |
names = matched_documents.name.to_list()
|
@@ -192,25 +197,46 @@ class Chatbot:
|
|
192 |
|
193 |
return response
|
194 |
|
195 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
196 |
"""
|
197 |
Format the response by adding the sources if necessary, and a disclaimer prompt.
|
198 |
"""
|
199 |
-
|
200 |
sep = self.cfg.separator
|
201 |
-
text_after_response = self.cfg.text_after_response
|
202 |
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
208 |
)
|
209 |
-
score = cosine_similarity(response_embedding, self.unk_embedding)
|
210 |
-
logger.info(f"UNK score: {score}")
|
211 |
-
if score < 0.9:
|
212 |
-
# Liekly that the answer is meaningful, add the top sources
|
213 |
-
response = self.add_sources(response, matched_documents=matched_documents)
|
214 |
|
215 |
response += f"{sep}{sep}{sep}{text_after_response}{sep}"
|
216 |
|
@@ -223,9 +249,22 @@ class Chatbot:
|
|
223 |
|
224 |
logger.info(f"User Question:\n{question}")
|
225 |
|
226 |
-
matched_documents = self.rank_documents(
|
227 |
-
|
228 |
-
|
229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
230 |
|
231 |
return formatted_output
|
|
|
8 |
import promptlayer
|
9 |
from openai.embeddings_utils import cosine_similarity, get_embedding
|
10 |
|
11 |
+
from buster.docparser import read_documents
|
12 |
|
13 |
logger = logging.getLogger(__name__)
|
14 |
logging.basicConfig(level=logging.INFO)
|
|
|
32 |
embedding_model: OpenAI model to use to get embeddings.
|
33 |
top_k: Max number of documents to retrieve, ordered by cosine similarity
|
34 |
thresh: threshold for cosine similarity to be considered
|
35 |
+
max_words: maximum number of words the retrieved documents can be. Will truncate otherwise.
|
36 |
completion_kwargs: kwargs for the OpenAI.Completion() method
|
37 |
separator: the separator to use, can be either "\n" or <p> depending on rendering.
|
38 |
link_format: the type of format to render links with, e.g. slack or markdown
|
|
|
45 |
embedding_model: str = "text-embedding-ada-002"
|
46 |
top_k: int = 3
|
47 |
thresh: float = 0.7
|
48 |
+
max_words: int = 3000
|
49 |
+
unknown_threshold: float = 0.9 # set to 0 to deactivate
|
50 |
|
51 |
completion_kwargs: dict = field(
|
52 |
default_factory=lambda: {
|
|
|
61 |
separator: str = "\n"
|
62 |
link_format: str = "slack"
|
63 |
unknown_prompt: str = "I Don't know how to answer your question."
|
64 |
+
text_before_documents: str = ("You are a chatbot.",)
|
65 |
text_before_prompt: str = "I'm a chatbot, bleep bloop."
|
66 |
text_after_response: str = "Answer the following question:\n"
|
67 |
|
|
|
80 |
logger.info(f"embeddings loaded.")
|
81 |
|
82 |
def _init_unk_embedding(self):
|
83 |
+
logger.info("Generating UNK embedding...")
|
|
|
|
|
84 |
self.unk_embedding = get_embedding(
|
85 |
+
self.cfg.unknown_prompt,
|
86 |
+
engine=self.cfg.embedding_model,
|
87 |
)
|
88 |
|
89 |
def rank_documents(
|
90 |
self,
|
91 |
documents: pd.DataFrame,
|
92 |
query: str,
|
93 |
+
top_k: float,
|
94 |
+
thresh: float,
|
95 |
+
engine: str,
|
96 |
) -> pd.DataFrame:
|
97 |
"""
|
98 |
Compare the question to the series of documents and return the best matching documents.
|
99 |
"""
|
|
|
|
|
|
|
100 |
|
101 |
query_embedding = get_embedding(
|
102 |
query,
|
|
|
121 |
|
122 |
return matched_documents
|
123 |
|
124 |
+
def prepare_documents(self, matched_documents: pd.DataFrame, max_words: int) -> str:
|
125 |
+
# gather the documents in one large plaintext variable
|
126 |
+
documents_list = matched_documents.text.to_list()
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
documents_str = " ".join(documents_list)
|
128 |
+
|
129 |
+
# truncate the documents to fit
|
130 |
+
# TODO: increase to actual token count
|
131 |
+
word_count = len(documents_str.split(" "))
|
132 |
+
if word_count > max_words:
|
133 |
logger.info("truncating documents to fit...")
|
134 |
+
documents_str = " ".join(documents_str.split(" ")[0:max_words])
|
135 |
+
logger.info(f"Documents after truncation: {documents_str}")
|
136 |
|
137 |
+
return documents_str
|
138 |
|
139 |
+
def prepare_prompt(
|
140 |
+
self,
|
141 |
+
question: str,
|
142 |
+
matched_documents: pd.DataFrame,
|
143 |
+
text_before_prompt: str,
|
144 |
+
text_before_documents: str,
|
145 |
+
) -> str:
|
146 |
"""
|
147 |
+
Prepare the prompt with prompt engineering.
|
148 |
"""
|
149 |
+
documents_str: str = self.prepare_documents(matched_documents, max_words=self.cfg.max_words)
|
150 |
+
return text_before_documents + documents_str + text_before_prompt + question
|
|
|
|
|
151 |
|
152 |
+
def get_gpt_response(self, **completion_kwargs):
|
|
|
153 |
# Call the API to generate a response
|
154 |
+
logger.info(f"querying GPT...")
|
155 |
try:
|
156 |
+
return openai.Completion.create(**completion_kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
157 |
|
158 |
except Exception as e:
|
159 |
# log the error and return a generic response instead.
|
160 |
+
logger.exception("Error connecting to OpenAI API. See traceback:")
|
161 |
+
response = {"choices": [{"text": "We're having trouble connecting to OpenAI right now... Try again soon!"}]}
|
162 |
+
return response
|
163 |
|
164 |
+
def generate_response(self, prompt: str, matched_documents: pd.DataFrame, unknown_prompt: str) -> str:
|
165 |
+
"""
|
166 |
+
Generate a response based on the retrieved documents.
|
167 |
+
"""
|
168 |
+
if len(matched_documents) == 0:
|
169 |
+
# No matching documents were retrieved, return
|
170 |
+
return unknown_prompt
|
171 |
+
|
172 |
+
logger.info(f"Prompt: {prompt}")
|
173 |
+
response = self.get_gpt_response(prompt=prompt, **self.cfg.completion_kwargs)
|
174 |
+
response_str = response["choices"][0]["text"]
|
175 |
+
logger.info(f"GPT Response:\n{response_str}")
|
176 |
+
return response_str
|
177 |
|
178 |
+
def add_sources(self, response: str, matched_documents: pd.DataFrame, sep: str, format: str):
|
179 |
"""
|
180 |
Add sources fromt the matched documents to the response.
|
181 |
"""
|
|
|
|
|
182 |
|
183 |
urls = matched_documents.url.to_list()
|
184 |
names = matched_documents.name.to_list()
|
|
|
197 |
|
198 |
return response
|
199 |
|
200 |
+
def check_response_relevance(
|
201 |
+
self, response: str, engine: str, unk_embedding: np.array, unk_threshold: float
|
202 |
+
) -> bool:
|
203 |
+
"""Check to see if a response is relevant to the chatbot's knowledge or not.
|
204 |
+
|
205 |
+
We assume we've prompt-engineered our bot to say a response is unrelated to the context if it isn't relevant.
|
206 |
+
Here, we compare the embedding of the response to the embedding of the prompt-engineered "I don't know" embedding.
|
207 |
+
|
208 |
+
set the unk_threshold to 0 to essentially turn off this feature.
|
209 |
+
"""
|
210 |
+
response_embedding = get_embedding(
|
211 |
+
response,
|
212 |
+
engine=engine,
|
213 |
+
)
|
214 |
+
score = cosine_similarity(response_embedding, unk_embedding)
|
215 |
+
logger.info(f"UNK score: {score}")
|
216 |
+
|
217 |
+
# Likely that the answer is meaningful, add the top sources
|
218 |
+
return score < unk_threshold
|
219 |
+
|
220 |
+
def format_response(self, response: str, matched_documents: pd.DataFrame, text_after_response: str) -> str:
|
221 |
"""
|
222 |
Format the response by adding the sources if necessary, and a disclaimer prompt.
|
223 |
"""
|
|
|
224 |
sep = self.cfg.separator
|
|
|
225 |
|
226 |
+
is_relevant = self.check_response_relevance(
|
227 |
+
response=response,
|
228 |
+
engine=self.cfg.embedding_model,
|
229 |
+
unk_embedding=self.unk_embedding,
|
230 |
+
unk_threshold=self.cfg.unknown_threshold,
|
231 |
+
)
|
232 |
+
if is_relevant:
|
233 |
+
# Passes our relevance detection mechanism that the answer is meaningful, add the top sources
|
234 |
+
response = self.add_sources(
|
235 |
+
response=response,
|
236 |
+
matched_documents=matched_documents,
|
237 |
+
sep=self.cfg.separator,
|
238 |
+
format=self.cfg.link_format,
|
239 |
)
|
|
|
|
|
|
|
|
|
|
|
240 |
|
241 |
response += f"{sep}{sep}{sep}{text_after_response}{sep}"
|
242 |
|
|
|
249 |
|
250 |
logger.info(f"User Question:\n{question}")
|
251 |
|
252 |
+
matched_documents = self.rank_documents(
|
253 |
+
documents=self.documents,
|
254 |
+
query=question,
|
255 |
+
top_k=self.cfg.top_k,
|
256 |
+
thresh=self.cfg.thresh,
|
257 |
+
engine=self.cfg.embedding_model,
|
258 |
+
)
|
259 |
+
prompt = self.prepare_prompt(
|
260 |
+
question=question,
|
261 |
+
matched_documents=matched_documents,
|
262 |
+
text_before_prompt=self.cfg.text_before_prompt,
|
263 |
+
text_before_documents=self.cfg.text_before_documents,
|
264 |
+
)
|
265 |
+
response = self.generate_response(prompt, matched_documents, self.cfg.unknown_prompt)
|
266 |
+
formatted_output = self.format_response(
|
267 |
+
response, matched_documents, text_after_response=self.cfg.text_after_response
|
268 |
+
)
|
269 |
|
270 |
return formatted_output
|