Spaces:
Runtime error
Runtime error
File size: 13,257 Bytes
26f62c4 90a4f47 26f62c4 e4c798e 26f62c4 e4c798e 90a4f47 26f62c4 90a4f47 e4c798e 26f62c4 e4c798e 26f62c4 e4c798e 26f62c4 e4c798e 26f62c4 90a4f47 |
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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 |
import re
import os
import logging
from typing import List
from opencc import OpenCC
import openai
import tiktoken
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
class GPTAgent:
def __init__(self, model):
openai.api_key = OPENAI_API_KEY
self.model = model
self.temperature = 0.8
self.frequency_penalty = 0
self.presence_penalty = 0.6
self.max_tokens = 2048
self.split_max_tokens = 13000
def request(self, messages):
response = self.agent.complete(messages=messages)
return response.choices[0].message["content"]
def split_into_many(self, text):
tokenizer = tiktoken.get_encoding("cl100k_base")
sentences = text.split("。")
n_tokens = [len(tokenizer.encode(" " + sentence)) for sentence in sentences]
chunks = []
tokens_so_far = 0
chunk = []
for sentence, token in zip(sentences, n_tokens):
if tokens_so_far + token > 3000:
chunks.append("。".join(chunk) + "。")
chunk = []
tokens_so_far = 0
if token > 3000:
continue
chunk.append(sentence)
tokens_so_far += token + 1
chunks.append("。".join(chunk) + "。")
return [text] if len(chunks) == 0 else chunks
def preprocess(self, text):
text = text.replace("\n", " ").replace("\r", "")
return text
def parse_result(self, result):
parsed_result = []
chinese_converter = OpenCC("s2tw")
for i in range(len(result)):
result[i] = result[i].split(",")
if len(result[i]) == 1:
result[i] = result[i][0].split("、")
if len(result[i]) == 1:
result[i] = result[i][0].split(",")
for word in result[i]:
try:
parsed_result.append(
chinese_converter.convert(word).strip().replace("。", "")
)
except Exception as e:
logging.error(e)
logging.error("Failed to parse result")
return parsed_result
class Translator(GPTAgent):
def __init__(self):
super().__init__("gpt-3.5-turbo")
def translate_to_chinese(self, text):
system_prompt = """
I want you to act as an Chinese translator, spelling corrector and improver.
I will speak to you in English, translate it and answer in the corrected and improved version of my text, in Traditional Chinese.
Keep the meaning same, but make them more literary. I want you to only reply the correction, the improvements and nothing else, do not write explanations and DO NOT use any Simplified Chinese.
"""
system_prompt_zh_tw = """
我希望你擔任中文翻譯、拼寫糾正及改進的角色。
我將用英文與你交流,請將其翻譯並用繁體中文回答,同時對我的文本進行糾正和改進。
保持原意不變,但使其更具文學性。我希望你僅回覆更正、改進的部分,不要寫解釋,也不要使用任何简体中文。
"""
messages = [
{"role": "system", "content": f"{system_prompt_zh_tw}"},
{"role": "user", "content": text},
]
try:
response = openai.ChatCompletion.create(
model=self.model,
messages=messages,
temperature=self.temperature,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
)
except Exception as e:
logging.error(e)
logging.error("Failed to translate to Chinese")
# translate from simplified chinese to traditional chinese
chinese_converter = OpenCC("s2tw")
return chinese_converter.convert(
response["choices"][0]["message"]["content"].strip()
)
class EmbeddingGenerator(GPTAgent):
def __init__(self):
super().__init__("text-davinci-002")
def get_embedding(self, text):
return openai.Embedding.create(input=text, engine="text-embedding-ada-002")[
"data"
][0]["embedding"]
class KeywordsGenerator(GPTAgent):
def __init__(self):
super().__init__("gpt-3.5-turbo")
def extract_keywords(self, text):
system_prompt = """
請你為以下內容抓出 5 個關鍵字用以搜尋這篇文章,並用「,」來分隔
"""
text_chunks = self.split_into_many(text)
keywords = []
for i in range(len(text_chunks)):
text = text_chunks[i]
messages = [
{"role": "system", "content": f"{system_prompt}"},
{"role": "user", "content": f"{self.preprocess(text)}"},
]
try:
response = openai.ChatCompletion.create(
model=self.model,
messages=messages,
temperature=0,
max_tokens=self.max_tokens,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
)
keywords.append(response["choices"][0]["message"]["content"].strip())
except Exception as e:
logging.error(e)
logging.error("Failed to extract keywords")
return self.parse_result(keywords)
class TopicsGenerator(GPTAgent):
def __init__(self):
super().__init__("gpt-3.5-turbo")
def extract_topics(self, text):
system_prompt = """
請你為以下內容給予 3 個高度抽象的主題分類這篇文章,並用「,」來分隔
"""
text_chunks = self.split_into_many(text)
topics = []
for i in range(len(text_chunks)):
text = text_chunks[i]
messages = [
{"role": "system", "content": f"{system_prompt}"},
{"role": "user", "content": f"{self.preprocess(text)}"},
]
try:
response = openai.ChatCompletion.create(
model=self.model,
messages=messages,
temperature=0,
max_tokens=self.max_tokens,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
)
topics.append(response["choices"][0]["message"]["content"].strip())
except Exception as e:
logging.error(e)
logging.error("Failed to extract topics")
return self.parse_result(topics)
class Summarizer(GPTAgent):
def __init__(self):
super().__init__("gpt-3.5-turbo-16k")
def summarize(self, text):
system_prompt = """
請幫我總結以下的文章。
"""
text_chunks = self.split_into_many(text)
if len(text_chunks) > 1:
concated_summary = ""
for i in range(len(text_chunks)):
text_chunk = text[i].replace("\n", " ").replace("\r", "")
messages = [
{"role": "system", "content": f"{system_prompt}"},
{"role": "user", "content": text_chunk},
]
try:
response = openai.ChatCompletion.create(
model=self.model,
messages=messages,
temperature=self.temperature,
max_tokens=self.max_tokens,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
)
except Exception as e:
logging.error(e)
logging.error("Failed to summarize text_chunk")
chinese_converter = OpenCC("s2tw")
concated_summary += chinese_converter.convert(
response["choices"][0]["message"]["content"].strip()
)
# summarize concated_summary
messages = [
{"role": "system", "content": f"{system_prompt}"},
{"role": "user", "content": concated_summary},
]
try:
response = openai.ChatCompletion.create(
model=self.model,
messages=messages,
temperature=self.temperature,
max_tokens=self.max_tokens,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
)
except Exception as e:
logging.error(e)
logging.error("Failed to summarize concated_summary")
chinese_converter = OpenCC("s2tw")
return chinese_converter.convert(
response["choices"][0]["message"]["content"].strip()
)
else:
messages = [
{"role": "system", "content": f"{system_prompt}"},
{"role": "user", "content": text},
]
try:
response = openai.ChatCompletion.create(
model=self.model,
messages=messages,
temperature=self.temperature,
max_tokens=self.max_tokens,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
)
except Exception as e:
logging.error(e)
logging.error("Failed to summarize")
chinese_converter = OpenCC("s2tw")
print(f'the summary is {response["choices"][0]["message"]["content"].strip()}')
response = chinese_converter.convert(
response["choices"][0]["message"]["content"]
)
return response
class QuestionAnswerer(GPTAgent):
def __init__(self):
super().__init__("gpt-3.5-turbo-16k")
def answer_chunk_question(self, text, question):
system_prompt = """
你是一個知識檢索系統,我會給你一份文件,請幫我依照文件內容回答問題,並用繁體中文回答。以下是文件內容
"""
text_chunks = self.split_into_many(text)
answer_chunks = []
for i in range(len(text_chunks)):
text = text_chunks[i]
messages = [
{"role": "system", "content": f"{system_prompt} + '\n' '{text}'"},
{"role": "user", "content": f"{question}"},
]
try:
response = openai.ChatCompletion.create(
model=self.model,
messages=messages,
temperature=self.temperature,
max_tokens=1024,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
)
except Exception as e:
logging.error(e)
logging.error("Failed to answer question")
chinese_converter = OpenCC("s2tw")
answer_chunks.append(
chinese_converter.convert(
response["choices"][0]["message"]["content"].strip()
)
)
return "。".join(answer_chunks)
def answer_question(self, context, context_page_num, context_file_name, history):
system_prompt = """
你是一個知識檢索系統,我會給你一份文件,請幫我依照文件內容回答問題,並用繁體中文回答。以下是文件內容
"""
history = self.__construct_message_history(history)
messages = [
{"role": "system", "content": f"{system_prompt} + '\n' '''{context}'''"},
] + history
try:
response = openai.ChatCompletion.create(
model=self.model,
messages=messages,
temperature=self.temperature,
max_tokens=2048,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
)
chinese_converter = OpenCC("s2tw")
page_num_message = f"以下內容來自 {context_file_name},第 {context_page_num} 頁\n\n"
bot_answer = response["choices"][0]["message"]["content"]
whole_answer = page_num_message + bot_answer
return chinese_converter.convert(whole_answer)
except Exception as e:
logging.error(e)
logging.error("Failed to answer question")
def __construct_message_history(self, history):
print(f"history is {history}")
max_history_length = 10
if len(history) > max_history_length:
history = history[-max_history_length:]
messages = []
for i in range(len(history)):
messages.append({"role": "user", "content": history[i][0]})
if history[i][1] is not None:
messages.append({"role": "assistant", "content": history[i][1]})
return messages |