File size: 7,233 Bytes
2ac93d3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
import os
import tiktoken
import requests, json
def num_token(string: str) -> int:
"""Returns the number of tokens in a text string."""
encoding = tiktoken.get_encoding('cl100k_base')
num_tokens = len(encoding.encode(string))
return num_tokens
def qa_prompt(context_str, query_str):
temp = (
"Context information is below. \n"
"---------------------\n"
"{context_str}"
"\n---------------------\n"
"Given the context information and not prior knowledge, "
"answer the question: {query_str}\n"
)
temp = temp.format(context_str=context_str, query_str=query_str)
print('qa_prompt token: ', num_token(temp))
return temp
def refine_prompt(context_str, query_str, existing_answer):
temp = (
"The original question is as follows: {query_str}\n"
"We have provided an existing answer: {existing_answer}\n"
"Given the new context, refine the original answer to better "
"answer the question. However, "
"------------\n"
"{context_str}\n"
"------------\n"
"If the context isn't useful, return the original answer as new answer."
"New answer:"
)
temp = temp.format(
context_str=context_str,
query_str=query_str,
existing_answer=existing_answer
)
print('qa_prompt token: ', num_token(temp))
return temp
def qa_prompt_t(query_str):
temp = (
"Context information is below. \n"
"---------------------\n"
"{text}"
"\n---------------------\n"
"Given the context information and not prior knowledge, "
"answer the question: {query_str}\n"
)
return temp.replace('{query_str}', query_str)
def refine_prompt_t(query_str):
temp = (
"The original question is as follows: {query_str}\n"
"We have provided an existing answer: {existing_answer}\n"
"Given the new context, refine the original answer to better "
"answer the question. However, "
"------------\n"
"{text}\n"
"------------\n"
"If the context isn't useful, return the original answer as new answer."
"New answer:"
)
return temp.replace('{query_str}', query_str)
def language_detection(query_str):
detect_template = (
"Determine if the QUERY want to be answered in English/繁體中文/简体中文 (ONLY choose one).\n"
f"QUERY: {query_str}"
"LANGUAGE of the answer should be (default English if you don't know):"
)
return detect_template
# rephrased text is the current text.
def rephrase_query(query_str, history, company, language):
rephrase_template = (
f"Given the following conversation and a new input from user, rephrase it (in {language}) to a standalone input.\n\n"
"Chat History:\n"
f"{history}\n"
f"User (New Input): {query_str}\n"
"Standalone Input (rephrase according to User's perspective):"
)
return rephrase_template
def rephrase_query_hkas(query_str, history, language):
rephrase_template = (
f"Rewrite the new QUERY in {language} given the context of the previous QA history, "
"such that the objective and subject should be clear in the REWRITED QUERY.\n\n "
"QA history:\n"
"===\n"
f"{history}\n"
"===\n\n"
f"QUERY: {query_str} \n"
f"REWRITED QUERY ONLY (no description):"
)
return rephrase_template
def rephrase_query_chat(query, history, language):
rephrase_template = (
f"Given the following conversation and a new input from user, rephrase it (in {language}) to a new standalone input.\n\n"
"Chat History:\n"
f"{history}\n"
f"New Input: {query}\n"
"Standalone Input (New Input perspective):"
)
return rephrase_template
def search_query_gradio(chat_history):
history = []
for i in chat_history:
if i[1]:
history.append(f'User: {i[0]}')
history.append(f'Assistant: {i[1]}')
else:
question = i[0]
num = [num_token(record) for record in history]
cum_sum = [abs(sum(num[-i-1::]) - 700) for i in range(len(num))]
cum_sum = cum_sum[::-1]
if cum_sum:
idx = cum_sum.index(min(cum_sum))
format_history = '\n'.join(i for i in history[idx:])
else:
format_history = ''
print(format_history)
template = """
Below is a history of the conversation so far, and a new question asked by the user that needs to be answered by searching in a knowledge base. Generate a search query based on the conversation and the new question. Do not include cited source filenames and document names e.g info.txt or doc.pdf or https://web.com in the search query terms. Do not include any text inside [] or <<>> in the search query terms.
Chat History:
{format_history}
Question:
{question}
Search query in the language used in Question:
"""
return template.format(format_history=format_history, question=question)
def question_answer_gradio(chat_history, search_query):
docs_string = requests.get(f'http://{os.environ["QUESTION_ANSWER"]}/retrieve_docs/comsec/{search_query}')
docs_dict = json.loads(docs_string.json())
source_lst = []
for i, k in docs_dict.items():
source_lst.append(f"{i}: {k}")
print('can do source lst: ', source_lst)
format_source = '\n\n'.join(source_lst)
# TODO number of docs
history = []
for i in chat_history:
if i[1]:
history.append(f'User: {i[0]}')
history.append(f'Assistant: {i[1]}')
else:
history.append(f'User: {i[0]}')
num = [num_token(record) for record in history]
cum_sum = [abs(sum(num[-i-1::]) - 700) for i in range(len(num))]
cum_sum = cum_sum[::-1]
if cum_sum:
idx = cum_sum.index(min(cum_sum))
format_history = '\n'.join(i for i in history[idx:])
else:
format_history = ''
print('history ok: ', format_history)
# Each source has a name followed by colon and the actual information, ALWAYS include the source name for each fact you use in the response. Use square brakets to reference the source, e.g. [info1.txt]. Don't combine sources, list each source separately, e.g. [info1.txt][info2.pdf].
template = """<|im_start|>
Assistant helps the user with their questions about City of Lake Elsinore Proposal. Be brief in your answers with appropriate tone and emotion. Answer ONLY with the facts listed in the list of sources below, where each source has a name followed by colon and the actual information. If there isn't enough information below, say you don't know. Do not generate answers that don't use the sources below. If asking a clarifying question to the user would help, ask the question. For tabular information return it as an html table. Do not return markdown format.
Sources:
{sources}
<|im_end|>
{chat_history}
Assistant:
"""
token_for_doc = 3700 - num_token(format_history) - num_token(template)
print('token for doc: ', token_for_doc)
return template.format(sources=format_source, chat_history=format_history)
|