maxiaolong03
commited on
Commit
·
4d5ee59
1
Parent(s):
b5e5daf
add files
Browse files- app.py +152 -38
- bot_requests.py +88 -77
app.py
CHANGED
|
@@ -109,14 +109,25 @@ def get_args() -> argparse.Namespace:
|
|
| 109 |
"""
|
| 110 |
parser = ArgumentParser(description="ERNIE models web chat demo.")
|
| 111 |
|
| 112 |
-
parser.add_argument(
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
parser.add_argument(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
parser.add_argument(
|
| 117 |
"--model_map",
|
| 118 |
type=str,
|
| 119 |
-
default=
|
| 120 |
help="""JSON string defining model name to endpoint mappings.
|
| 121 |
Required Format:
|
| 122 |
{"ERNIE-4.5": "http://localhost:port/v1"}
|
|
@@ -129,15 +140,56 @@ def get_args() -> argparse.Namespace:
|
|
| 129 |
""",
|
| 130 |
)
|
| 131 |
parser.add_argument(
|
| 132 |
-
"--embedding_service_url",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
)
|
| 134 |
-
parser.add_argument("--qianfan_api_key", type=str, default=os.environ.get("API_KEY"), help="Qianfan API key.")
|
| 135 |
-
parser.add_argument("--embedding_model", type=str, default="embedding-v1", help="Embedding model name.")
|
| 136 |
-
parser.add_argument("--embedding_dim", type=int, default=384, help="Dimension of the embedding vector.")
|
| 137 |
-
parser.add_argument("--chunk_size", type=int, default=512, help="Chunk size for splitting long documents.")
|
| 138 |
-
parser.add_argument("--top_k", type=int, default=3, help="Top k results to retrieve.")
|
| 139 |
-
parser.add_argument("--faiss_index_path", type=str, default="data/faiss_index", help="Faiss index path.")
|
| 140 |
-
parser.add_argument("--text_db_path", type=str, default="data/text_db.jsonl", help="Text database path.")
|
| 141 |
|
| 142 |
args = parser.parse_args()
|
| 143 |
try:
|
|
@@ -179,11 +231,14 @@ class FaissTextDatabase:
|
|
| 179 |
# If faiss_index_path exists, load it and text_db_path
|
| 180 |
if os.path.exists(self.faiss_index_path) and os.path.exists(self.text_db_path):
|
| 181 |
self.index = faiss.read_index(self.faiss_index_path)
|
| 182 |
-
with open(self.text_db_path,
|
| 183 |
self.text_db = json.load(f)
|
| 184 |
else:
|
| 185 |
self.index = faiss.IndexFlatIP(self.embedding_dim)
|
| 186 |
-
self.text_db = {
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
def calculate_md5(self, file_path: str) -> str:
|
| 189 |
"""
|
|
@@ -212,7 +267,11 @@ class FaissTextDatabase:
|
|
| 212 |
return file_md5 in self.text_db["file_md5s"]
|
| 213 |
|
| 214 |
def add_embeddings(
|
| 215 |
-
self,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
) -> bool:
|
| 217 |
"""
|
| 218 |
Stores document embeddings in FAISS database after checking for duplicates.
|
|
@@ -241,7 +300,7 @@ class FaissTextDatabase:
|
|
| 241 |
if progress_bar is not None:
|
| 242 |
progress_bar((i + 1) / len(segments), desc=file_name + " Processing...")
|
| 243 |
vectors = np.array(vectors)
|
| 244 |
-
self.index.add(vectors.astype(
|
| 245 |
|
| 246 |
start_id = len(self.text_db["chunks"])
|
| 247 |
for i, text in enumerate(segments):
|
|
@@ -275,7 +334,7 @@ class FaissTextDatabase:
|
|
| 275 |
# Step 1: Retrieve top_k results for each query and collect all indices
|
| 276 |
all_indices = []
|
| 277 |
for query in query_list:
|
| 278 |
-
query_vector = np.array([self.bot_client.embed_fn(query)]).astype(
|
| 279 |
_, indices = self.index.search(query_vector, self.top_k)
|
| 280 |
all_indices.extend(indices[0].tolist())
|
| 281 |
|
|
@@ -293,12 +352,17 @@ class FaissTextDatabase:
|
|
| 293 |
|
| 294 |
if target_file_md5 not in file_boundaries:
|
| 295 |
file_start = target_idx
|
| 296 |
-
while
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
file_start -= 1
|
| 298 |
file_end = target_idx
|
| 299 |
while (
|
| 300 |
file_end < len(self.text_db["chunks"]) - 1
|
| 301 |
-
and self.text_db["chunks"][file_end + 1]["file_md5"]
|
|
|
|
| 302 |
):
|
| 303 |
file_end += 1
|
| 304 |
else:
|
|
@@ -330,7 +394,9 @@ class FaissTextDatabase:
|
|
| 330 |
# Step 5: Create merged text for each group
|
| 331 |
result = ""
|
| 332 |
for idx, group in enumerate(groups):
|
| 333 |
-
result += "\n段落{idx}:\n{title}\n".format(
|
|
|
|
|
|
|
| 334 |
for idx in group:
|
| 335 |
result += self.text_db["chunks"][idx]["text"] + "\n"
|
| 336 |
self.logger.info(f"Merged chunk range: {group[0]}-{group[-1]}")
|
|
@@ -341,7 +407,7 @@ class FaissTextDatabase:
|
|
| 341 |
"""Save the database to disk."""
|
| 342 |
faiss.write_index(self.index, self.faiss_index_path)
|
| 343 |
|
| 344 |
-
with open(self.text_db_path,
|
| 345 |
json.dump(self.text_db, f, ensure_ascii=False, indent=2)
|
| 346 |
|
| 347 |
|
|
@@ -396,19 +462,26 @@ class GradioEvents:
|
|
| 396 |
Yields:
|
| 397 |
dict: A dictionary containing the event type and its corresponding content.
|
| 398 |
"""
|
| 399 |
-
conversation, conversation_str = GradioEvents.get_history_conversation(
|
|
|
|
|
|
|
| 400 |
conversation_str += f"user:\n{query}\n"
|
| 401 |
|
| 402 |
search_info_message = QUERY_REWRITE_PROMPT.format(
|
| 403 |
-
TIMESTAMP=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
|
|
|
| 404 |
)
|
| 405 |
search_conversation = [{"role": "user", "content": search_info_message}]
|
| 406 |
-
search_info_result = GradioEvents.get_sub_query(
|
|
|
|
|
|
|
| 407 |
if search_info_result is None:
|
| 408 |
search_info_result = {"query": [query]}
|
| 409 |
|
| 410 |
if search_info_result.get("query", []):
|
| 411 |
-
relevant_passages = faiss_db.search_with_context(
|
|
|
|
|
|
|
| 412 |
yield {"type": "relevant_passage", "content": relevant_passages}
|
| 413 |
|
| 414 |
query = ANSWER_PROMPT.format(
|
|
@@ -562,7 +635,9 @@ class GradioEvents:
|
|
| 562 |
"""
|
| 563 |
GradioEvents.gc()
|
| 564 |
|
| 565 |
-
reset_result = namedtuple(
|
|
|
|
|
|
|
| 566 |
return reset_result(
|
| 567 |
[], # clear chatbot
|
| 568 |
[], # clear task_history
|
|
@@ -600,7 +675,9 @@ class GradioEvents:
|
|
| 600 |
return url
|
| 601 |
|
| 602 |
@staticmethod
|
| 603 |
-
def get_sub_query(
|
|
|
|
|
|
|
| 604 |
"""
|
| 605 |
Enhances user queries by generating alternative phrasings using language models.
|
| 606 |
Creates semantically similar variations of the original query to improve retrieval accuracy.
|
|
@@ -644,7 +721,20 @@ class GradioEvents:
|
|
| 644 |
Returns:
|
| 645 |
tuple: Two strings, the first part of the original line and the rest of the line.
|
| 646 |
"""
|
| 647 |
-
PUNCTUATIONS = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 648 |
|
| 649 |
if len(line) <= chunk_size:
|
| 650 |
return line, ""
|
|
@@ -711,7 +801,10 @@ class GradioEvents:
|
|
| 711 |
|
| 712 |
@staticmethod
|
| 713 |
def file_upload(
|
| 714 |
-
files_url: list,
|
|
|
|
|
|
|
|
|
|
| 715 |
) -> str:
|
| 716 |
"""
|
| 717 |
Uploads and processes multiple files by splitting them into semantically meaningful chunks,
|
|
@@ -730,7 +823,9 @@ class GradioEvents:
|
|
| 730 |
return
|
| 731 |
yield gr.update(visible=True)
|
| 732 |
for file_url in files_url:
|
| 733 |
-
if not GradioEvents.save_file_to_db(
|
|
|
|
|
|
|
| 734 |
file_name = os.path.basename(file_url)
|
| 735 |
gr.Info(f"{file_name} already processed.")
|
| 736 |
|
|
@@ -779,7 +874,11 @@ class GradioEvents:
|
|
| 779 |
return False
|
| 780 |
|
| 781 |
|
| 782 |
-
def launch_demo(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 783 |
"""
|
| 784 |
Launch demo program
|
| 785 |
|
|
@@ -843,7 +942,11 @@ def launch_demo(args: argparse.Namespace, bot_client: BotClient, faiss_db_templa
|
|
| 843 |
file_count="multiple",
|
| 844 |
)
|
| 845 |
relevant_passage = gr.Textbox(
|
| 846 |
-
label="Relevant Passage",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 847 |
)
|
| 848 |
with gr.Row():
|
| 849 |
progress_bar = gr.Textbox(label="Progress", visible=False)
|
|
@@ -857,8 +960,12 @@ def launch_demo(args: argparse.Namespace, bot_client: BotClient, faiss_db_templa
|
|
| 857 |
|
| 858 |
task_history = gr.State([])
|
| 859 |
|
| 860 |
-
predict_with_clients = partial(
|
| 861 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 862 |
file_upload_with_clients = partial(
|
| 863 |
GradioEvents.file_upload,
|
| 864 |
)
|
|
@@ -884,7 +991,9 @@ def launch_demo(args: argparse.Namespace, bot_client: BotClient, faiss_db_templa
|
|
| 884 |
)
|
| 885 |
submit_btn.click(GradioEvents.reset_user_input, [], [query])
|
| 886 |
empty_btn.click(
|
| 887 |
-
GradioEvents.reset_state,
|
|
|
|
|
|
|
| 888 |
)
|
| 889 |
regen_btn.click(
|
| 890 |
regenerate_with_clients,
|
|
@@ -893,7 +1002,10 @@ def launch_demo(args: argparse.Namespace, bot_client: BotClient, faiss_db_templa
|
|
| 893 |
show_progress=True,
|
| 894 |
)
|
| 895 |
|
| 896 |
-
demo.queue(
|
|
|
|
|
|
|
|
|
|
| 897 |
|
| 898 |
|
| 899 |
def main():
|
|
@@ -903,7 +1015,9 @@ def main():
|
|
| 903 |
faiss_db = FaissTextDatabase(args, bot_client)
|
| 904 |
|
| 905 |
# Run file upload function to save default knowledge base.
|
| 906 |
-
GradioEvents.save_file_to_db(
|
|
|
|
|
|
|
| 907 |
|
| 908 |
launch_demo(args, bot_client, faiss_db)
|
| 909 |
|
|
|
|
| 109 |
"""
|
| 110 |
parser = ArgumentParser(description="ERNIE models web chat demo.")
|
| 111 |
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--server-port", type=int, default=7860, help="Demo server port."
|
| 114 |
+
)
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
"--server-name", type=str, default="0.0.0.0", help="Demo server name."
|
| 117 |
+
)
|
| 118 |
+
parser.add_argument(
|
| 119 |
+
"--max_char",
|
| 120 |
+
type=int,
|
| 121 |
+
default=20000,
|
| 122 |
+
help="Maximum character limit for messages.",
|
| 123 |
+
)
|
| 124 |
+
parser.add_argument(
|
| 125 |
+
"--max_retry_num", type=int, default=3, help="Maximum retry number for request."
|
| 126 |
+
)
|
| 127 |
parser.add_argument(
|
| 128 |
"--model_map",
|
| 129 |
type=str,
|
| 130 |
+
default='{"ernie-4.5-turbo-128k-preview": "https://qianfan.baidubce.com/v2"}',
|
| 131 |
help="""JSON string defining model name to endpoint mappings.
|
| 132 |
Required Format:
|
| 133 |
{"ERNIE-4.5": "http://localhost:port/v1"}
|
|
|
|
| 140 |
""",
|
| 141 |
)
|
| 142 |
parser.add_argument(
|
| 143 |
+
"--embedding_service_url",
|
| 144 |
+
type=str,
|
| 145 |
+
default="https://qianfan.baidubce.com/v2",
|
| 146 |
+
help="Embedding service url.",
|
| 147 |
+
)
|
| 148 |
+
parser.add_argument(
|
| 149 |
+
"--qianfan_api_key",
|
| 150 |
+
type=str,
|
| 151 |
+
default=os.environ.get("API_KEY"),
|
| 152 |
+
help="Qianfan API key.",
|
| 153 |
+
)
|
| 154 |
+
parser.add_argument(
|
| 155 |
+
"--embedding_model",
|
| 156 |
+
type=str,
|
| 157 |
+
default="embedding-v1",
|
| 158 |
+
help="Embedding model name.",
|
| 159 |
+
)
|
| 160 |
+
parser.add_argument(
|
| 161 |
+
"--embedding_dim",
|
| 162 |
+
type=int,
|
| 163 |
+
default=384,
|
| 164 |
+
help="Dimension of the embedding vector.",
|
| 165 |
+
)
|
| 166 |
+
parser.add_argument(
|
| 167 |
+
"--chunk_size",
|
| 168 |
+
type=int,
|
| 169 |
+
default=512,
|
| 170 |
+
help="Chunk size for splitting long documents.",
|
| 171 |
+
)
|
| 172 |
+
parser.add_argument(
|
| 173 |
+
"--top_k", type=int, default=3, help="Top k results to retrieve."
|
| 174 |
+
)
|
| 175 |
+
parser.add_argument(
|
| 176 |
+
"--faiss_index_path",
|
| 177 |
+
type=str,
|
| 178 |
+
default="data/faiss_index",
|
| 179 |
+
help="Faiss index path.",
|
| 180 |
+
)
|
| 181 |
+
parser.add_argument(
|
| 182 |
+
"--text_db_path",
|
| 183 |
+
type=str,
|
| 184 |
+
default="data/text_db.jsonl",
|
| 185 |
+
help="Text database path.",
|
| 186 |
+
)
|
| 187 |
+
parser.add_argument(
|
| 188 |
+
"--concurrency_limit", type=int, default=10, help="Default concurrency limit."
|
| 189 |
+
)
|
| 190 |
+
parser.add_argument(
|
| 191 |
+
"--max_queue_size", type=int, default=50, help="Maximum queue size for request."
|
| 192 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
args = parser.parse_args()
|
| 195 |
try:
|
|
|
|
| 231 |
# If faiss_index_path exists, load it and text_db_path
|
| 232 |
if os.path.exists(self.faiss_index_path) and os.path.exists(self.text_db_path):
|
| 233 |
self.index = faiss.read_index(self.faiss_index_path)
|
| 234 |
+
with open(self.text_db_path, "r", encoding="utf-8") as f:
|
| 235 |
self.text_db = json.load(f)
|
| 236 |
else:
|
| 237 |
self.index = faiss.IndexFlatIP(self.embedding_dim)
|
| 238 |
+
self.text_db = {
|
| 239 |
+
"file_md5s": [],
|
| 240 |
+
"chunks": [],
|
| 241 |
+
} # Save file_md5s to avoid duplicates # Save chunks
|
| 242 |
|
| 243 |
def calculate_md5(self, file_path: str) -> str:
|
| 244 |
"""
|
|
|
|
| 267 |
return file_md5 in self.text_db["file_md5s"]
|
| 268 |
|
| 269 |
def add_embeddings(
|
| 270 |
+
self,
|
| 271 |
+
file_path: str,
|
| 272 |
+
segments: list[str],
|
| 273 |
+
progress_bar: gr.Progress = None,
|
| 274 |
+
save_file: bool = False,
|
| 275 |
) -> bool:
|
| 276 |
"""
|
| 277 |
Stores document embeddings in FAISS database after checking for duplicates.
|
|
|
|
| 300 |
if progress_bar is not None:
|
| 301 |
progress_bar((i + 1) / len(segments), desc=file_name + " Processing...")
|
| 302 |
vectors = np.array(vectors)
|
| 303 |
+
self.index.add(vectors.astype("float32"))
|
| 304 |
|
| 305 |
start_id = len(self.text_db["chunks"])
|
| 306 |
for i, text in enumerate(segments):
|
|
|
|
| 334 |
# Step 1: Retrieve top_k results for each query and collect all indices
|
| 335 |
all_indices = []
|
| 336 |
for query in query_list:
|
| 337 |
+
query_vector = np.array([self.bot_client.embed_fn(query)]).astype("float32")
|
| 338 |
_, indices = self.index.search(query_vector, self.top_k)
|
| 339 |
all_indices.extend(indices[0].tolist())
|
| 340 |
|
|
|
|
| 352 |
|
| 353 |
if target_file_md5 not in file_boundaries:
|
| 354 |
file_start = target_idx
|
| 355 |
+
while (
|
| 356 |
+
file_start > 0
|
| 357 |
+
and self.text_db["chunks"][file_start - 1]["file_md5"]
|
| 358 |
+
== target_file_md5
|
| 359 |
+
):
|
| 360 |
file_start -= 1
|
| 361 |
file_end = target_idx
|
| 362 |
while (
|
| 363 |
file_end < len(self.text_db["chunks"]) - 1
|
| 364 |
+
and self.text_db["chunks"][file_end + 1]["file_md5"]
|
| 365 |
+
== target_file_md5
|
| 366 |
):
|
| 367 |
file_end += 1
|
| 368 |
else:
|
|
|
|
| 394 |
# Step 5: Create merged text for each group
|
| 395 |
result = ""
|
| 396 |
for idx, group in enumerate(groups):
|
| 397 |
+
result += "\n段落{idx}:\n{title}\n".format(
|
| 398 |
+
idx=idx + 1, title=self.text_db["chunks"][group[0]]["file_txt"]
|
| 399 |
+
)
|
| 400 |
for idx in group:
|
| 401 |
result += self.text_db["chunks"][idx]["text"] + "\n"
|
| 402 |
self.logger.info(f"Merged chunk range: {group[0]}-{group[-1]}")
|
|
|
|
| 407 |
"""Save the database to disk."""
|
| 408 |
faiss.write_index(self.index, self.faiss_index_path)
|
| 409 |
|
| 410 |
+
with open(self.text_db_path, "w", encoding="utf-8") as f:
|
| 411 |
json.dump(self.text_db, f, ensure_ascii=False, indent=2)
|
| 412 |
|
| 413 |
|
|
|
|
| 462 |
Yields:
|
| 463 |
dict: A dictionary containing the event type and its corresponding content.
|
| 464 |
"""
|
| 465 |
+
conversation, conversation_str = GradioEvents.get_history_conversation(
|
| 466 |
+
task_history
|
| 467 |
+
)
|
| 468 |
conversation_str += f"user:\n{query}\n"
|
| 469 |
|
| 470 |
search_info_message = QUERY_REWRITE_PROMPT.format(
|
| 471 |
+
TIMESTAMP=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 472 |
+
CONVERSATION=conversation_str,
|
| 473 |
)
|
| 474 |
search_conversation = [{"role": "user", "content": search_info_message}]
|
| 475 |
+
search_info_result = GradioEvents.get_sub_query(
|
| 476 |
+
search_conversation, model, bot_client
|
| 477 |
+
)
|
| 478 |
if search_info_result is None:
|
| 479 |
search_info_result = {"query": [query]}
|
| 480 |
|
| 481 |
if search_info_result.get("query", []):
|
| 482 |
+
relevant_passages = faiss_db.search_with_context(
|
| 483 |
+
search_info_result["query"]
|
| 484 |
+
)
|
| 485 |
yield {"type": "relevant_passage", "content": relevant_passages}
|
| 486 |
|
| 487 |
query = ANSWER_PROMPT.format(
|
|
|
|
| 635 |
"""
|
| 636 |
GradioEvents.gc()
|
| 637 |
|
| 638 |
+
reset_result = namedtuple(
|
| 639 |
+
"reset_result", ["chatbot", "task_history", "file_btn", "relevant_passage"]
|
| 640 |
+
)
|
| 641 |
return reset_result(
|
| 642 |
[], # clear chatbot
|
| 643 |
[], # clear task_history
|
|
|
|
| 675 |
return url
|
| 676 |
|
| 677 |
@staticmethod
|
| 678 |
+
def get_sub_query(
|
| 679 |
+
conversation: list, model_name: str, bot_client: BotClient
|
| 680 |
+
) -> dict:
|
| 681 |
"""
|
| 682 |
Enhances user queries by generating alternative phrasings using language models.
|
| 683 |
Creates semantically similar variations of the original query to improve retrieval accuracy.
|
|
|
|
| 721 |
Returns:
|
| 722 |
tuple: Two strings, the first part of the original line and the rest of the line.
|
| 723 |
"""
|
| 724 |
+
PUNCTUATIONS = {
|
| 725 |
+
".",
|
| 726 |
+
"。",
|
| 727 |
+
"!",
|
| 728 |
+
"!",
|
| 729 |
+
"?",
|
| 730 |
+
"?",
|
| 731 |
+
",",
|
| 732 |
+
",",
|
| 733 |
+
";",
|
| 734 |
+
";",
|
| 735 |
+
":",
|
| 736 |
+
":",
|
| 737 |
+
}
|
| 738 |
|
| 739 |
if len(line) <= chunk_size:
|
| 740 |
return line, ""
|
|
|
|
| 801 |
|
| 802 |
@staticmethod
|
| 803 |
def file_upload(
|
| 804 |
+
files_url: list,
|
| 805 |
+
chunk_size: int,
|
| 806 |
+
faiss_db: FaissTextDatabase,
|
| 807 |
+
progress_bar: gr.Progress = gr.Progress(),
|
| 808 |
) -> str:
|
| 809 |
"""
|
| 810 |
Uploads and processes multiple files by splitting them into semantically meaningful chunks,
|
|
|
|
| 823 |
return
|
| 824 |
yield gr.update(visible=True)
|
| 825 |
for file_url in files_url:
|
| 826 |
+
if not GradioEvents.save_file_to_db(
|
| 827 |
+
file_url, chunk_size, faiss_db, progress_bar
|
| 828 |
+
):
|
| 829 |
file_name = os.path.basename(file_url)
|
| 830 |
gr.Info(f"{file_name} already processed.")
|
| 831 |
|
|
|
|
| 874 |
return False
|
| 875 |
|
| 876 |
|
| 877 |
+
def launch_demo(
|
| 878 |
+
args: argparse.Namespace,
|
| 879 |
+
bot_client: BotClient,
|
| 880 |
+
faiss_db_template: FaissTextDatabase,
|
| 881 |
+
):
|
| 882 |
"""
|
| 883 |
Launch demo program
|
| 884 |
|
|
|
|
| 942 |
file_count="multiple",
|
| 943 |
)
|
| 944 |
relevant_passage = gr.Textbox(
|
| 945 |
+
label="Relevant Passage",
|
| 946 |
+
lines=5,
|
| 947 |
+
max_lines=5,
|
| 948 |
+
placeholder=RELEVANT_PASSAGE_DEFAULT,
|
| 949 |
+
interactive=False,
|
| 950 |
)
|
| 951 |
with gr.Row():
|
| 952 |
progress_bar = gr.Textbox(label="Progress", visible=False)
|
|
|
|
| 960 |
|
| 961 |
task_history = gr.State([])
|
| 962 |
|
| 963 |
+
predict_with_clients = partial(
|
| 964 |
+
GradioEvents.predict_stream, bot_client=bot_client
|
| 965 |
+
)
|
| 966 |
+
regenerate_with_clients = partial(
|
| 967 |
+
GradioEvents.regenerate, bot_client=bot_client
|
| 968 |
+
)
|
| 969 |
file_upload_with_clients = partial(
|
| 970 |
GradioEvents.file_upload,
|
| 971 |
)
|
|
|
|
| 991 |
)
|
| 992 |
submit_btn.click(GradioEvents.reset_user_input, [], [query])
|
| 993 |
empty_btn.click(
|
| 994 |
+
GradioEvents.reset_state,
|
| 995 |
+
outputs=[chatbot, task_history, file_btn, relevant_passage],
|
| 996 |
+
show_progress=True,
|
| 997 |
)
|
| 998 |
regen_btn.click(
|
| 999 |
regenerate_with_clients,
|
|
|
|
| 1002 |
show_progress=True,
|
| 1003 |
)
|
| 1004 |
|
| 1005 |
+
demo.queue(
|
| 1006 |
+
default_concurrency_limit=args.concurrency_limit, max_size=args.max_queue_size
|
| 1007 |
+
)
|
| 1008 |
+
demo.launch(server_port=args.server_port, server_name=args.server_name)
|
| 1009 |
|
| 1010 |
|
| 1011 |
def main():
|
|
|
|
| 1015 |
faiss_db = FaissTextDatabase(args, bot_client)
|
| 1016 |
|
| 1017 |
# Run file upload function to save default knowledge base.
|
| 1018 |
+
GradioEvents.save_file_to_db(
|
| 1019 |
+
FILE_URL_DEFAULT, args.chunk_size, faiss_db, save_file=True
|
| 1020 |
+
)
|
| 1021 |
|
| 1022 |
launch_demo(args, bot_client, faiss_db)
|
| 1023 |
|
bot_requests.py
CHANGED
|
@@ -16,20 +16,22 @@
|
|
| 16 |
|
| 17 |
import os
|
| 18 |
import argparse
|
|
|
|
| 19 |
import logging
|
| 20 |
import traceback
|
| 21 |
-
|
| 22 |
import jieba
|
|
|
|
| 23 |
from openai import OpenAI
|
| 24 |
|
| 25 |
-
import requests
|
| 26 |
|
| 27 |
-
class BotClient
|
| 28 |
"""Client for interacting with various AI models."""
|
|
|
|
| 29 |
def __init__(self, args: argparse.Namespace):
|
| 30 |
"""
|
| 31 |
-
Initializes the BotClient instance by configuring essential parameters from command line arguments
|
| 32 |
-
including retry limits, character constraints, model endpoints and API credentials while setting up
|
| 33 |
default values for missing arguments to ensure robust operation.
|
| 34 |
|
| 35 |
Args:
|
|
@@ -37,25 +39,29 @@ class BotClient(object):
|
|
| 37 |
Uses getattr() to safely retrieve values with fallback defaults.
|
| 38 |
"""
|
| 39 |
self.logger = logging.getLogger(__name__)
|
| 40 |
-
|
| 41 |
-
self.max_retry_num = getattr(args, 'max_retry_num', 3)
|
| 42 |
-
self.max_char = getattr(args, 'max_char', 8000)
|
| 43 |
|
| 44 |
-
self.
|
|
|
|
|
|
|
|
|
|
| 45 |
self.api_key = os.environ.get("API_KEY")
|
| 46 |
|
| 47 |
-
self.embedding_service_url = getattr(
|
| 48 |
-
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
self.web_search_service_url = getattr(
|
| 51 |
-
|
|
|
|
|
|
|
| 52 |
|
| 53 |
self.qianfan_api_key = os.environ.get("API_KEY")
|
| 54 |
|
| 55 |
def call_back(self, host_url: str, req_data: dict) -> dict:
|
| 56 |
"""
|
| 57 |
-
Executes an HTTP request to the specified endpoint using the OpenAI client, handles the response
|
| 58 |
-
conversion to a compatible dictionary format, and manages any exceptions that may occur during
|
| 59 |
the request process while logging errors appropriately.
|
| 60 |
|
| 61 |
Args:
|
|
@@ -68,20 +74,18 @@ class BotClient(object):
|
|
| 68 |
"""
|
| 69 |
try:
|
| 70 |
client = OpenAI(base_url=host_url, api_key=self.api_key)
|
| 71 |
-
response = client.chat.completions.create(
|
| 72 |
-
|
| 73 |
-
)
|
| 74 |
-
|
| 75 |
# Convert OpenAI response to compatible format
|
| 76 |
return response.model_dump()
|
| 77 |
|
| 78 |
except Exception as e:
|
| 79 |
-
self.logger.error("Stream request failed: {}"
|
| 80 |
raise
|
| 81 |
|
| 82 |
def call_back_stream(self, host_url: str, req_data: dict) -> dict:
|
| 83 |
"""
|
| 84 |
-
Makes a streaming HTTP request to the specified host URL using the OpenAI client and yields response chunks
|
| 85 |
in real-time while handling any exceptions that may occur during the streaming process.
|
| 86 |
|
| 87 |
Args:
|
|
@@ -100,25 +104,25 @@ class BotClient(object):
|
|
| 100 |
for chunk in response:
|
| 101 |
if not chunk.choices:
|
| 102 |
continue
|
| 103 |
-
|
| 104 |
# Convert OpenAI response to compatible format
|
| 105 |
yield chunk.model_dump()
|
| 106 |
|
| 107 |
except Exception as e:
|
| 108 |
-
self.logger.error("Stream request failed: {}"
|
| 109 |
raise
|
| 110 |
|
| 111 |
def process(
|
| 112 |
-
self,
|
| 113 |
-
model_name: str,
|
| 114 |
-
req_data: dict,
|
| 115 |
-
max_tokens: int=2048,
|
| 116 |
-
temperature: float=1.0,
|
| 117 |
-
top_p: float=0.7
|
| 118 |
) -> dict:
|
| 119 |
"""
|
| 120 |
-
Handles chat completion requests by mapping the model name to its endpoint, preparing request parameters
|
| 121 |
-
including token limits and sampling settings, truncating messages to fit character limits, making API calls
|
| 122 |
with built-in retry mechanism, and logging the full request/response cycle for debugging purposes.
|
| 123 |
|
| 124 |
Args:
|
|
@@ -140,7 +144,7 @@ class BotClient(object):
|
|
| 140 |
req_data["messages"] = self.truncate_messages(req_data["messages"])
|
| 141 |
for _ in range(self.max_retry_num):
|
| 142 |
try:
|
| 143 |
-
self.logger.info("[MODEL] {}"
|
| 144 |
self.logger.info("[req_data]====>")
|
| 145 |
self.logger.info(json.dumps(req_data, ensure_ascii=False))
|
| 146 |
res = self.call_back(model_url, req_data)
|
|
@@ -153,15 +157,16 @@ class BotClient(object):
|
|
| 153 |
res = {}
|
| 154 |
if len(res) != 0 and "error" not in res:
|
| 155 |
break
|
| 156 |
-
|
| 157 |
return res
|
| 158 |
|
| 159 |
def process_stream(
|
| 160 |
-
self,
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
|
|
|
| 165 |
) -> dict:
|
| 166 |
"""
|
| 167 |
Processes streaming requests by mapping the model name to its endpoint, configuring request parameters,
|
|
@@ -184,29 +189,30 @@ class BotClient(object):
|
|
| 184 |
req_data["temperature"] = temperature
|
| 185 |
req_data["top_p"] = top_p
|
| 186 |
req_data["messages"] = self.truncate_messages(req_data["messages"])
|
| 187 |
-
|
| 188 |
last_error = None
|
| 189 |
for _ in range(self.max_retry_num):
|
| 190 |
try:
|
| 191 |
-
self.logger.info("[MODEL] {}"
|
| 192 |
self.logger.info("[req_data]====>")
|
| 193 |
self.logger.info(json.dumps(req_data, ensure_ascii=False))
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
yield chunk
|
| 197 |
return
|
| 198 |
-
|
| 199 |
except Exception as e:
|
| 200 |
last_error = e
|
| 201 |
-
self.logger.error(
|
| 202 |
-
|
|
|
|
|
|
|
| 203 |
self.logger.error("All retry attempts failed for stream request")
|
| 204 |
yield {"error": str(last_error)}
|
| 205 |
|
| 206 |
def cut_chinese_english(self, text: str) -> list:
|
| 207 |
"""
|
| 208 |
-
Segments mixed Chinese and English text into individual components using Jieba for Chinese words
|
| 209 |
-
while preserving English words as whole units, with special handling for Unicode character ranges
|
| 210 |
to distinguish between the two languages.
|
| 211 |
|
| 212 |
Args:
|
|
@@ -219,7 +225,9 @@ class BotClient(object):
|
|
| 219 |
en_ch_words = []
|
| 220 |
|
| 221 |
for word in words:
|
| 222 |
-
if word.isalpha() and not any(
|
|
|
|
|
|
|
| 223 |
en_ch_words.append(word)
|
| 224 |
else:
|
| 225 |
en_ch_words.extend(list(word))
|
|
@@ -239,10 +247,10 @@ class BotClient(object):
|
|
| 239 |
"""
|
| 240 |
if not messages:
|
| 241 |
return messages
|
| 242 |
-
|
| 243 |
processed = []
|
| 244 |
total_units = 0
|
| 245 |
-
|
| 246 |
for msg in messages:
|
| 247 |
# Handle two different content formats
|
| 248 |
if isinstance(msg["content"], str):
|
|
@@ -251,31 +259,33 @@ class BotClient(object):
|
|
| 251 |
text_content = msg["content"][1]["text"]
|
| 252 |
else:
|
| 253 |
text_content = ""
|
| 254 |
-
|
| 255 |
# Calculate unit count after tokenization
|
| 256 |
units = self.cut_chinese_english(text_content)
|
| 257 |
unit_count = len(units)
|
| 258 |
-
|
| 259 |
-
processed.append(
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
|
|
|
|
|
|
| 266 |
total_units += unit_count
|
| 267 |
-
|
| 268 |
if total_units <= self.max_char:
|
| 269 |
return messages
|
| 270 |
-
|
| 271 |
# Number of units to remove
|
| 272 |
to_remove = total_units - self.max_char
|
| 273 |
-
|
| 274 |
# 1. Truncate historical messages
|
| 275 |
for i in range(len(processed) - 1, 1):
|
| 276 |
if to_remove <= 0:
|
| 277 |
break
|
| 278 |
-
|
| 279 |
# current = processed[i]
|
| 280 |
if processed[i]["unit_count"] <= to_remove:
|
| 281 |
processed[i]["text_content"] = ""
|
|
@@ -293,7 +303,7 @@ class BotClient(object):
|
|
| 293 |
elif isinstance(processed[i]["original_content"], list):
|
| 294 |
processed[i]["original_content"][1]["text"] = new_text
|
| 295 |
to_remove = 0
|
| 296 |
-
|
| 297 |
# 2. Truncate system message
|
| 298 |
if to_remove > 0:
|
| 299 |
system_msg = processed[0]
|
|
@@ -313,7 +323,7 @@ class BotClient(object):
|
|
| 313 |
elif isinstance(processed[0]["original_content"], list):
|
| 314 |
processed[0]["original_content"][1]["text"] = new_text
|
| 315 |
to_remove = 0
|
| 316 |
-
|
| 317 |
# 3. Truncate last message
|
| 318 |
if to_remove > 0 and len(processed) > 1:
|
| 319 |
last_msg = processed[-1]
|
|
@@ -331,15 +341,12 @@ class BotClient(object):
|
|
| 331 |
last_msg["original_content"] = ""
|
| 332 |
elif isinstance(last_msg["original_content"], list):
|
| 333 |
last_msg["original_content"][1]["text"] = ""
|
| 334 |
-
|
| 335 |
result = []
|
| 336 |
for msg in processed:
|
| 337 |
if msg["text_content"]:
|
| 338 |
-
result.append({
|
| 339 |
-
|
| 340 |
-
"content": msg["original_content"]
|
| 341 |
-
})
|
| 342 |
-
|
| 343 |
return result
|
| 344 |
|
| 345 |
def embed_fn(self, text: str) -> list:
|
|
@@ -352,7 +359,9 @@ class BotClient(object):
|
|
| 352 |
Returns:
|
| 353 |
list: A list of floats representing the embedding.
|
| 354 |
"""
|
| 355 |
-
client = OpenAI(
|
|
|
|
|
|
|
| 356 |
response = client.embeddings.create(input=[text], model=self.embedding_model)
|
| 357 |
return response.data[0].embedding
|
| 358 |
|
|
@@ -368,7 +377,7 @@ class BotClient(object):
|
|
| 368 |
"""
|
| 369 |
headers = {
|
| 370 |
"Authorization": "Bearer " + self.qianfan_api_key,
|
| 371 |
-
"Content-Type": "application/json"
|
| 372 |
}
|
| 373 |
|
| 374 |
results = []
|
|
@@ -376,9 +385,11 @@ class BotClient(object):
|
|
| 376 |
for query in query_list:
|
| 377 |
payload = {
|
| 378 |
"messages": [{"role": "user", "content": query}],
|
| 379 |
-
"resource_type_filter": [{"type": "web", "top_k": top_k}]
|
| 380 |
}
|
| 381 |
-
response = requests.post(
|
|
|
|
|
|
|
| 382 |
|
| 383 |
if response.status_code == 200:
|
| 384 |
response = response.json()
|
|
@@ -387,4 +398,4 @@ class BotClient(object):
|
|
| 387 |
else:
|
| 388 |
self.logger.info(f"请求失败,状态码: {response.status_code}")
|
| 389 |
self.logger.info(response.text)
|
| 390 |
-
return results
|
|
|
|
| 16 |
|
| 17 |
import os
|
| 18 |
import argparse
|
| 19 |
+
import json
|
| 20 |
import logging
|
| 21 |
import traceback
|
| 22 |
+
|
| 23 |
import jieba
|
| 24 |
+
import requests
|
| 25 |
from openai import OpenAI
|
| 26 |
|
|
|
|
| 27 |
|
| 28 |
+
class BotClient:
|
| 29 |
"""Client for interacting with various AI models."""
|
| 30 |
+
|
| 31 |
def __init__(self, args: argparse.Namespace):
|
| 32 |
"""
|
| 33 |
+
Initializes the BotClient instance by configuring essential parameters from command line arguments
|
| 34 |
+
including retry limits, character constraints, model endpoints and API credentials while setting up
|
| 35 |
default values for missing arguments to ensure robust operation.
|
| 36 |
|
| 37 |
Args:
|
|
|
|
| 39 |
Uses getattr() to safely retrieve values with fallback defaults.
|
| 40 |
"""
|
| 41 |
self.logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
self.max_retry_num = getattr(args, "max_retry_num", 3)
|
| 44 |
+
self.max_char = getattr(args, "max_char", 8000)
|
| 45 |
+
|
| 46 |
+
self.model_map = getattr(args, "model_map", {})
|
| 47 |
self.api_key = os.environ.get("API_KEY")
|
| 48 |
|
| 49 |
+
self.embedding_service_url = getattr(
|
| 50 |
+
args, "embedding_service_url", "embedding_service_url"
|
| 51 |
+
)
|
| 52 |
+
self.embedding_model = getattr(args, "embedding_model", "embedding_model")
|
| 53 |
|
| 54 |
+
self.web_search_service_url = getattr(
|
| 55 |
+
args, "web_search_service_url", "web_search_service_url"
|
| 56 |
+
)
|
| 57 |
+
self.max_search_results_num = getattr(args, "max_search_results_num", 15)
|
| 58 |
|
| 59 |
self.qianfan_api_key = os.environ.get("API_KEY")
|
| 60 |
|
| 61 |
def call_back(self, host_url: str, req_data: dict) -> dict:
|
| 62 |
"""
|
| 63 |
+
Executes an HTTP request to the specified endpoint using the OpenAI client, handles the response
|
| 64 |
+
conversion to a compatible dictionary format, and manages any exceptions that may occur during
|
| 65 |
the request process while logging errors appropriately.
|
| 66 |
|
| 67 |
Args:
|
|
|
|
| 74 |
"""
|
| 75 |
try:
|
| 76 |
client = OpenAI(base_url=host_url, api_key=self.api_key)
|
| 77 |
+
response = client.chat.completions.create(**req_data)
|
| 78 |
+
|
|
|
|
|
|
|
| 79 |
# Convert OpenAI response to compatible format
|
| 80 |
return response.model_dump()
|
| 81 |
|
| 82 |
except Exception as e:
|
| 83 |
+
self.logger.error(f"Stream request failed: {e}")
|
| 84 |
raise
|
| 85 |
|
| 86 |
def call_back_stream(self, host_url: str, req_data: dict) -> dict:
|
| 87 |
"""
|
| 88 |
+
Makes a streaming HTTP request to the specified host URL using the OpenAI client and yields response chunks
|
| 89 |
in real-time while handling any exceptions that may occur during the streaming process.
|
| 90 |
|
| 91 |
Args:
|
|
|
|
| 104 |
for chunk in response:
|
| 105 |
if not chunk.choices:
|
| 106 |
continue
|
| 107 |
+
|
| 108 |
# Convert OpenAI response to compatible format
|
| 109 |
yield chunk.model_dump()
|
| 110 |
|
| 111 |
except Exception as e:
|
| 112 |
+
self.logger.error(f"Stream request failed: {e}")
|
| 113 |
raise
|
| 114 |
|
| 115 |
def process(
|
| 116 |
+
self,
|
| 117 |
+
model_name: str,
|
| 118 |
+
req_data: dict,
|
| 119 |
+
max_tokens: int = 2048,
|
| 120 |
+
temperature: float = 1.0,
|
| 121 |
+
top_p: float = 0.7,
|
| 122 |
) -> dict:
|
| 123 |
"""
|
| 124 |
+
Handles chat completion requests by mapping the model name to its endpoint, preparing request parameters
|
| 125 |
+
including token limits and sampling settings, truncating messages to fit character limits, making API calls
|
| 126 |
with built-in retry mechanism, and logging the full request/response cycle for debugging purposes.
|
| 127 |
|
| 128 |
Args:
|
|
|
|
| 144 |
req_data["messages"] = self.truncate_messages(req_data["messages"])
|
| 145 |
for _ in range(self.max_retry_num):
|
| 146 |
try:
|
| 147 |
+
self.logger.info(f"[MODEL] {model_url}")
|
| 148 |
self.logger.info("[req_data]====>")
|
| 149 |
self.logger.info(json.dumps(req_data, ensure_ascii=False))
|
| 150 |
res = self.call_back(model_url, req_data)
|
|
|
|
| 157 |
res = {}
|
| 158 |
if len(res) != 0 and "error" not in res:
|
| 159 |
break
|
| 160 |
+
|
| 161 |
return res
|
| 162 |
|
| 163 |
def process_stream(
|
| 164 |
+
self,
|
| 165 |
+
model_name: str,
|
| 166 |
+
req_data: dict,
|
| 167 |
+
max_tokens: int = 2048,
|
| 168 |
+
temperature: float = 1.0,
|
| 169 |
+
top_p: float = 0.7,
|
| 170 |
) -> dict:
|
| 171 |
"""
|
| 172 |
Processes streaming requests by mapping the model name to its endpoint, configuring request parameters,
|
|
|
|
| 189 |
req_data["temperature"] = temperature
|
| 190 |
req_data["top_p"] = top_p
|
| 191 |
req_data["messages"] = self.truncate_messages(req_data["messages"])
|
| 192 |
+
|
| 193 |
last_error = None
|
| 194 |
for _ in range(self.max_retry_num):
|
| 195 |
try:
|
| 196 |
+
self.logger.info(f"[MODEL] {model_url}")
|
| 197 |
self.logger.info("[req_data]====>")
|
| 198 |
self.logger.info(json.dumps(req_data, ensure_ascii=False))
|
| 199 |
+
|
| 200 |
+
yield from self.call_back_stream(model_url, req_data)
|
|
|
|
| 201 |
return
|
| 202 |
+
|
| 203 |
except Exception as e:
|
| 204 |
last_error = e
|
| 205 |
+
self.logger.error(
|
| 206 |
+
f"Stream request failed (attempt {_ + 1}/{self.max_retry_num}): {e}"
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
self.logger.error("All retry attempts failed for stream request")
|
| 210 |
yield {"error": str(last_error)}
|
| 211 |
|
| 212 |
def cut_chinese_english(self, text: str) -> list:
|
| 213 |
"""
|
| 214 |
+
Segments mixed Chinese and English text into individual components using Jieba for Chinese words
|
| 215 |
+
while preserving English words as whole units, with special handling for Unicode character ranges
|
| 216 |
to distinguish between the two languages.
|
| 217 |
|
| 218 |
Args:
|
|
|
|
| 225 |
en_ch_words = []
|
| 226 |
|
| 227 |
for word in words:
|
| 228 |
+
if word.isalpha() and not any(
|
| 229 |
+
"\u4e00" <= char <= "\u9fff" for char in word
|
| 230 |
+
):
|
| 231 |
en_ch_words.append(word)
|
| 232 |
else:
|
| 233 |
en_ch_words.extend(list(word))
|
|
|
|
| 247 |
"""
|
| 248 |
if not messages:
|
| 249 |
return messages
|
| 250 |
+
|
| 251 |
processed = []
|
| 252 |
total_units = 0
|
| 253 |
+
|
| 254 |
for msg in messages:
|
| 255 |
# Handle two different content formats
|
| 256 |
if isinstance(msg["content"], str):
|
|
|
|
| 259 |
text_content = msg["content"][1]["text"]
|
| 260 |
else:
|
| 261 |
text_content = ""
|
| 262 |
+
|
| 263 |
# Calculate unit count after tokenization
|
| 264 |
units = self.cut_chinese_english(text_content)
|
| 265 |
unit_count = len(units)
|
| 266 |
+
|
| 267 |
+
processed.append(
|
| 268 |
+
{
|
| 269 |
+
"role": msg["role"],
|
| 270 |
+
"original_content": msg["content"], # Preserve original content
|
| 271 |
+
"text_content": text_content, # Extracted plain text
|
| 272 |
+
"units": units,
|
| 273 |
+
"unit_count": unit_count,
|
| 274 |
+
}
|
| 275 |
+
)
|
| 276 |
total_units += unit_count
|
| 277 |
+
|
| 278 |
if total_units <= self.max_char:
|
| 279 |
return messages
|
| 280 |
+
|
| 281 |
# Number of units to remove
|
| 282 |
to_remove = total_units - self.max_char
|
| 283 |
+
|
| 284 |
# 1. Truncate historical messages
|
| 285 |
for i in range(len(processed) - 1, 1):
|
| 286 |
if to_remove <= 0:
|
| 287 |
break
|
| 288 |
+
|
| 289 |
# current = processed[i]
|
| 290 |
if processed[i]["unit_count"] <= to_remove:
|
| 291 |
processed[i]["text_content"] = ""
|
|
|
|
| 303 |
elif isinstance(processed[i]["original_content"], list):
|
| 304 |
processed[i]["original_content"][1]["text"] = new_text
|
| 305 |
to_remove = 0
|
| 306 |
+
|
| 307 |
# 2. Truncate system message
|
| 308 |
if to_remove > 0:
|
| 309 |
system_msg = processed[0]
|
|
|
|
| 323 |
elif isinstance(processed[0]["original_content"], list):
|
| 324 |
processed[0]["original_content"][1]["text"] = new_text
|
| 325 |
to_remove = 0
|
| 326 |
+
|
| 327 |
# 3. Truncate last message
|
| 328 |
if to_remove > 0 and len(processed) > 1:
|
| 329 |
last_msg = processed[-1]
|
|
|
|
| 341 |
last_msg["original_content"] = ""
|
| 342 |
elif isinstance(last_msg["original_content"], list):
|
| 343 |
last_msg["original_content"][1]["text"] = ""
|
| 344 |
+
|
| 345 |
result = []
|
| 346 |
for msg in processed:
|
| 347 |
if msg["text_content"]:
|
| 348 |
+
result.append({"role": msg["role"], "content": msg["original_content"]})
|
| 349 |
+
|
|
|
|
|
|
|
|
|
|
| 350 |
return result
|
| 351 |
|
| 352 |
def embed_fn(self, text: str) -> list:
|
|
|
|
| 359 |
Returns:
|
| 360 |
list: A list of floats representing the embedding.
|
| 361 |
"""
|
| 362 |
+
client = OpenAI(
|
| 363 |
+
base_url=self.embedding_service_url, api_key=self.qianfan_api_key
|
| 364 |
+
)
|
| 365 |
response = client.embeddings.create(input=[text], model=self.embedding_model)
|
| 366 |
return response.data[0].embedding
|
| 367 |
|
|
|
|
| 377 |
"""
|
| 378 |
headers = {
|
| 379 |
"Authorization": "Bearer " + self.qianfan_api_key,
|
| 380 |
+
"Content-Type": "application/json",
|
| 381 |
}
|
| 382 |
|
| 383 |
results = []
|
|
|
|
| 385 |
for query in query_list:
|
| 386 |
payload = {
|
| 387 |
"messages": [{"role": "user", "content": query}],
|
| 388 |
+
"resource_type_filter": [{"type": "web", "top_k": top_k}],
|
| 389 |
}
|
| 390 |
+
response = requests.post(
|
| 391 |
+
self.web_search_service_url, headers=headers, json=payload
|
| 392 |
+
)
|
| 393 |
|
| 394 |
if response.status_code == 200:
|
| 395 |
response = response.json()
|
|
|
|
| 398 |
else:
|
| 399 |
self.logger.info(f"请求失败,状态码: {response.status_code}")
|
| 400 |
self.logger.info(response.text)
|
| 401 |
+
return results
|