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 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
| """ 交互式多模态RAG系统 支持PDF上传、多种检索模式和网页爬取功能 """
import os import sys import json import requests import io import numpy as np from typing import List, Dict, Any, Optional from dotenv import load_dotenv from sklearn.metrics.pairwise import cosine_similarity
from camel.models import ModelFactory from camel.types import ModelPlatformType
try: from pypdf import PdfReader except ImportError: print("缺少pypdf库,请运行: pip install pypdf") sys.exit(1)
try: from unstructured.partition.auto import partition from unstructured.documents.elements import Text, Image, Table except ImportError: print("缺少unstructured库,请运行: pip install unstructured") sys.exit(1)
try: from sentence_transformers import SentenceTransformer EMBEDDING_AVAILABLE = True except ImportError: print("缺少sentence-transformers库") EMBEDDING_AVAILABLE = False
try: from RAG_WEB_TOPIC_Enhanced import EnhancedInteractiveResearchSystem WEB_RESEARCH_AVAILABLE = True print("Web research system available") except ImportError: print("Web research system not available") WEB_RESEARCH_AVAILABLE = False
class SimpleLLMInterface: """LLM接口 - 使用CAMEL ModelFactory""" def __init__(self, api_key: str, model_name: str = "Qwen/Qwen2.5-72B-Instruct", use_camel: bool = True): if not api_key: raise ValueError("API key is required") self.api_key = api_key self.model_name = model_name self.use_camel = use_camel self.model = None if use_camel: try: self.model = ModelFactory.create( model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL, model_type=model_name, url='https://api-inference.modelscope.cn/v1/', api_key=api_key ) print(f"CAMEL LLM initialized: {model_name}") print(f"API key: {api_key[:10]}...{api_key[-4:]}") except Exception as e: print(f"CAMEL initialization failed, using fallback: {e}") self.model = None else: print(f"Direct API LLM initialized: {model_name}") print(f"API key: {api_key[:10]}...{api_key[-4:]}")
def generate(self, prompt: str, max_tokens: int = 500) -> str: """生成文本回答 - 使用CAMEL模型或直接API调用""" if self.model is not None: try: print(f"Generating response with CAMEL model...") from camel.messages import BaseMessage user_message = BaseMessage.make_user_message( role_name="user", content=prompt ) response = self.model.run([user_message]) if response: if hasattr(response, 'content'): return response.content elif isinstance(response, list) and len(response) > 0: first_response = response[0] if hasattr(first_response, 'content'): return first_response.content else: return str(first_response) elif isinstance(response, str): return response else: return str(response) else: raise Exception("No response generated from CAMEL model") except Exception as e: print(f"CAMEL generation failed, using fallback: {str(e)[:100]}...") return self._fallback_generate(prompt, max_tokens) else: print(f"Generating response with direct API call...") return self._fallback_generate(prompt, max_tokens)
def _fallback_generate(self, prompt: str, max_tokens: int = 500) -> str: """降级方案:直接API调用 - 增加重试机制和超时处理""" max_retries = 3 timeout_seconds = 60 for attempt in range(max_retries): try: import requests headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } data = { "model": self.model_name, "messages": [{"role": "user", "content": prompt}], "max_tokens": max_tokens, "temperature": 0.7 } print(f"API调用 {attempt + 1}/{max_retries}...") response = requests.post( "https://api-inference.modelscope.cn/v1/chat/completions", headers=headers, json=data, timeout=timeout_seconds ) if response.status_code == 200: result = response.json() if 'choices' in result and len(result['choices']) > 0: content = result['choices'][0]['message']['content'] print(f"√ API调用成功") return content else: raise Exception(f"API响应格式错误: {result}") else: raise Exception(f"API调用失败 (状态码: {response.status_code}): {response.text}") except requests.exceptions.Timeout: print(f"API调用超时 (尝试 {attempt + 1}/{max_retries})") if attempt == max_retries - 1: return f"抱歉,由于网络超时,无法生成回答。请稍后重试。" continue except requests.exceptions.ConnectionError: print(f"网络连接错误 (尝试 {attempt + 1}/{max_retries})") if attempt == max_retries - 1: return f"抱歉,网络连接失败,无法生成回答。请检查网络连接。" continue except Exception as e: print(f"API调用失败 (尝试 {attempt + 1}/{max_retries}): {str(e)[:100]}...") if attempt == max_retries - 1: return f"生成答案时出现错误: {str(e)}" continue return "抱歉,多次尝试后仍无法生成回答,请稍后重试。"
class SimpleEmbeddingModel: """简化的嵌入模型""" def __init__(self, model_name: str = 'intfloat/e5-large-v2'): if not EMBEDDING_AVAILABLE: raise ImportError("sentence-transformers not available") try: self.model = SentenceTransformer(model_name) print(f"√ Embedding model loaded: {model_name}") except Exception as e: print(f"Failed to load embedding model: {e}") raise
def encode(self, texts: List[str]) -> np.ndarray: """文本编码""" try: return self.model.encode(texts, convert_to_numpy=True) except Exception as e: print(f"Encoding failed: {e}") return np.array([])
class SimpleVectorRetriever: """简化的向量检索器""" def __init__(self, embedding_model: SimpleEmbeddingModel): self.embedding_model = embedding_model self.documents = [] self.doc_metadata = [] self.document_ids = [] self.doc_embeddings = None print("√ Simple vector retriever initialized") def add_documents(self, texts: List[str], metadata: List[Dict[str, Any]]): """添加文档""" if not texts: return try: new_ids = [f"doc_{len(self.documents) + i}" for i in range(len(texts))] self.documents.extend(texts) self.doc_metadata.extend(metadata) self.document_ids.extend(new_ids) print(f"Computing embeddings for {len(texts)} documents...") new_embeddings = self.embedding_model.encode(texts) if self.doc_embeddings is None: self.doc_embeddings = new_embeddings else: self.doc_embeddings = np.vstack([self.doc_embeddings, new_embeddings]) print(f"Added {len(texts)} documents to retriever") except Exception as e: print(f"Error adding documents: {e}") raise def query(self, query_text: str, top_k: int = 5, filter_type: Optional[str] = None) -> List[Dict[str, Any]]: """检索相关文档""" if not self.documents or self.doc_embeddings is None: print("No documents in retriever") return [] try: query_embedding = self.embedding_model.encode([query_text]) similarities = cosine_similarity(query_embedding, self.doc_embeddings)[0] top_indices = np.argsort(similarities)[::-1][:top_k * 2] results = [] for idx in top_indices: if idx >= len(self.documents): continue doc_type = self.doc_metadata[idx].get('type', 'unknown') if filter_type and doc_type != filter_type: continue results.append({ 'text': self.documents[idx], 'similarity': float(similarities[idx]), 'metadata': self.doc_metadata[idx], 'id': self.document_ids[idx] }) if len(results) >= top_k: break print(f"Retrieved {len(results)} documents") return results except Exception as e: print(f"Query failed: {e}") return []
class SimpleRAGSystem: """简化的RAG系统 - 集成CAMEL ModelFactory""" def __init__(self, api_key: str, model_name: str = "Qwen/Qwen2.5-72B-Instruct", use_camel: bool = True): if not api_key: raise ValueError("错误:API key required") try: if use_camel: print("Initializing Simple RAG System with CAMEL...") else: print("Initializing Simple RAG System with direct API...") self.llm = SimpleLLMInterface(api_key=api_key, model_name=model_name, use_camel=use_camel) self.embedding_model = SimpleEmbeddingModel() self.vector_retriever = SimpleVectorRetriever(self.embedding_model) self.knowledge_base_initialized = False self.multimodal_content_store = {} print("√ Simple RAG System initialized successfully!") except Exception as e: print(f"错误:Initialization failed: {e}") raise
def setup_knowledge_base(self, pdf_url: Optional[str] = None, pdf_path: Optional[str] = None): """设置知识库""" try: if pdf_url: print(f"↓ Loading PDF from URL: {pdf_url}") response = requests.get(pdf_url, timeout=30) response.raise_for_status() pdf_bytes = response.content print(f"√ PDF downloaded ({len(pdf_bytes)} bytes)") pdf_file = io.BytesIO(pdf_bytes) elements = partition(file=pdf_file) elif pdf_path: print(f"Loading PDF from: {pdf_path}") if not os.path.exists(pdf_path): raise FileNotFoundError(f"错误:PDF not found: {pdf_path}") elements = partition(filename=pdf_path) print(f"√ PDF loaded successfully") else: raise ValueError("错误:Either pdf_url or pdf_path required") except Exception as e: print(f"错误:PDF loading error: {e}") raise
texts_to_embed = [] metadata_to_embed = [] multimodal_id_counter = 0
for element in elements: element_text = str(element).strip() if not element_text or len(element_text) < 10: continue multimodal_id = f"multimodal_{multimodal_id_counter}" multimodal_id_counter += 1 if isinstance(element, Text): texts_to_embed.append(element_text) metadata_to_embed.append({ 'type': 'text', 'source': 'pdf', 'multimodal_id': multimodal_id }) elif isinstance(element, Image): image_description = f"图像内容: {element_text}" texts_to_embed.append(image_description) metadata_to_embed.append({ 'type': 'image', 'source': 'pdf', 'multimodal_id': multimodal_id }) self.multimodal_content_store[multimodal_id] = { 'type': 'image', 'data': element_text } elif isinstance(element, Table): table_description = f"表格内容: {element_text}" texts_to_embed.append(table_description) metadata_to_embed.append({ 'type': 'table', 'source': 'pdf', 'multimodal_id': multimodal_id }) self.multimodal_content_store[multimodal_id] = { 'type': 'table', 'data': element_text } else: texts_to_embed.append(element_text) metadata_to_embed.append({ 'type': 'text', 'source': 'pdf', 'multimodal_id': multimodal_id })
if texts_to_embed: self.vector_retriever.add_documents(texts_to_embed, metadata_to_embed) self.knowledge_base_initialized = True text_count = sum(1 for meta in metadata_to_embed if meta.get('type') == 'text') image_count = sum(1 for meta in metadata_to_embed if meta.get('type') == 'image') table_count = sum(1 for meta in metadata_to_embed if meta.get('type') == 'table') print(f"√ Knowledge base setup complete: {len(texts_to_embed)} elements") print(f" Content: {text_count} text, {image_count} images, {table_count} tables") else: raise ValueError("No content extracted from PDF")
def get_available_retrieval_methods(self) -> List[str]: """获取可用的检索方法""" return ["Vector", "Enhanced"]
def _query_rewriting(self, original_query: str) -> str: """查询重写 - 使用CAMEL模型""" try: prompt = f"""请重写以下查询,使其更适合文档检索和信息提取:
原始查询:{original_query}
重写要求: 1. 保持查询的核心意图 2. 使用更具体和明确的词汇 3. 适合向量检索和语义匹配 4. 只返回重写后的查询,不要其他解释
重写后的查询:""" rewritten_query = self.llm.generate(prompt, max_tokens=100) if rewritten_query and not rewritten_query.startswith("抱歉") and not rewritten_query.startswith("生成答案时出现错误"): lines = rewritten_query.strip().split('\n') for line in lines: line = line.strip() if line and not line.startswith('重写后的查询') and not line.startswith('原始查询'): rewritten_query = line break print(f"Query rewritten: {original_query} -> {rewritten_query[:50]}...") return rewritten_query.strip() else: print(f"警告:Query rewriting failed, using original query") return original_query except Exception as e: print(f"警告:Query rewriting failed: {e}") return original_query
def _hyde_generation(self, query: str) -> str: """HyDE假设文档生成 - 使用CAMEL模型""" try: prompt = f"""基于以下查询,生成一个假设性的文档片段,该片段可能包含查询的答案:
查询:{query}
要求: 1. 生成一个200-300字的文档片段 2. 内容应该直接回答查询问题 3. 使用专业和准确的语言 4. 包含相关的技术细节和概念
假设文档:""" hyde_doc = self.llm.generate(prompt, max_tokens=300) if hyde_doc and not hyde_doc.startswith("抱歉") and not hyde_doc.startswith("生成答案时出现错误"): print(f"📝 HyDE document generated: {len(hyde_doc)} characters") return hyde_doc.strip() else: print(f"警告:HyDE generation failed, using original query") return query except Exception as e: print(f"警告:HyDE generation failed: {e}") return query
def _rrf_fusion(self, all_results: List[List[Dict]], k: int = 60) -> List[Dict[str, Any]]: """RRF融合多个检索结果""" try: doc_scores = {} for results in all_results: for rank, doc in enumerate(results): doc_id = doc.get('id', '') if doc_id: rrf_score = 1.0 / (k + rank + 1) if doc_id in doc_scores: doc_scores[doc_id]['score'] += rrf_score else: doc_scores[doc_id] = { 'doc': doc, 'score': rrf_score } sorted_docs = sorted(doc_scores.values(), key=lambda x: x['score'], reverse=True) final_docs = [] for item in sorted_docs: doc = item['doc'].copy() doc['rrf_score'] = item['score'] final_docs.append(doc) return final_docs except Exception as e: print(f"警告:RRF fusion failed: {e}") return all_results[0] if all_results else []
def enhanced_query(self, original_query: str, use_rewriting: bool = True, use_hyde: bool = True, use_rrf: bool = True, top_k: int = 5, rrf_k: int = 60, multimodal_preference: Optional[List[str]] = None) -> Dict[str, Any]: """执行增强型RAG查询""" if not self.knowledge_base_initialized: raise RuntimeError("Knowledge base not initialized")
if use_rewriting and use_hyde and use_rrf: print("\n执行深度检索...") print("="*60) print("开始执行深度RAG查询") print("="*60) else: print("\n执行检索...") print("="*40)
query_for_retrieval = original_query rewritten_query = None hyde_doc = None retrieval_method = "Vector" all_retrieved_results = []
if use_rewriting: print("\n步骤1: 查询重写") print("-" * 30) print(f"原始查询: {original_query}") rewritten_query = self._query_rewriting(original_query) query_for_retrieval = rewritten_query print(f"重写查询: {rewritten_query}") retrieval_method += "+Rewriting"
print("\n步骤2: 文档检索") print("-" * 30) if use_hyde and use_rrf: print("使用HyDE+RRF组合方法进行检索...") print("使用RRF算法进行混合检索(HyDE增强向量检索)...") else: print("使用基础向量检索...")
if use_hyde: print("执行HyDE增强向量检索...") hyde_doc = self._hyde_generation(query_for_retrieval) print("生成的假设文档:") print(hyde_doc) retrieval_method += "+HyDE"
text_results = self.vector_retriever.query(query_for_retrieval, top_k=top_k, filter_type='text') all_retrieved_results.append(text_results) print(f"✓ HyDE向量检索完成,获得 {len(text_results)} 个结果")
if multimodal_preference: if 'image' in multimodal_preference: image_results = self.vector_retriever.query(query_for_retrieval, top_k=top_k, filter_type='image') all_retrieved_results.append(image_results) print(f"✓ 图像检索完成,获得 {len(image_results)} 个结果") retrieval_method += "+Image" if 'table' in multimodal_preference: table_results = self.vector_retriever.query(query_for_retrieval, top_k=top_k, filter_type='table') all_retrieved_results.append(table_results) print(f"✓ 表格检索完成,获得 {len(table_results)} 个结果") retrieval_method += "+Table"
if hyde_doc: print("执行BM25检索(使用原始查询)...") hyde_results = self.vector_retriever.query(hyde_doc, top_k=top_k) all_retrieved_results.append(hyde_results) print(f"✓ BM25检索成功,获得 {len(hyde_results)} 个结果")
if use_rrf and len(all_retrieved_results) > 1: print("使用RRF算法融合检索结果...") final_retrieved_docs = self._rrf_fusion(all_retrieved_results, k=rrf_k) retrieval_method += "+RRF" unique_doc_ids = set() for res_list in all_retrieved_results: for doc in res_list: unique_doc_ids.add(doc.get('id', '')) print(f"RRF融合完成,共处理 {len(unique_doc_ids)} 个唯一文档,返回前 {top_k} 个结果") print(f"HyDE+RRF检索完成,返回 {len(final_retrieved_docs)} 个文档") else: unique_docs = {} for res_list in all_retrieved_results: for doc in res_list: if doc.get('id') not in unique_docs: unique_docs[doc.get('id')] = doc final_retrieved_docs = list(unique_docs.values()) print(f"文档合并完成,返回 {len(final_retrieved_docs)} 个文档")
final_retrieved_docs = final_retrieved_docs[:top_k]
for i, doc in enumerate(final_retrieved_docs, 1): similarity = doc.get('similarity', 0) rrf_score = getattr(doc, 'rrf_score', similarity) text_preview = doc.get('text', '')[:200] + "..." if len(doc.get('text', '')) > 200 else doc.get('text', '') print(f"文档 {i} (RRF分数: {rrf_score:.4f}):") print(f"{text_preview}") print()
print("步骤3: 答案生成") print("-" * 30) print()
context_texts = [] for doc in final_retrieved_docs: context_texts.append(doc['text'])
separator = '\n---\n' context_str = separator.join(context_texts) prompt_for_llm = f"""你是一个专业的文档分析助手。请基于以下PDF文档内容回答用户问题。
文档内容: {context_str}
用户问题:{original_query}
回答要求: 1. 仔细阅读并理解文档内容 2. 基于文档内容提供准确、详细的答案 3. 如果文档中没有相关信息,请明确说明 4. 使用清晰的结构组织答案 5. 引用具体的文档内容支持你的回答
请提供详细的答案:""" print("正在生成最终答案...") final_answer = self.llm.generate(prompt_for_llm, max_tokens=800) if final_answer and not final_answer.startswith("抱歉") and not final_answer.startswith("生成答案时出现错误"): print("√ 答案生成成功") print("最终答案:") print(final_answer) else: print("警告:答案生成失败,提供基于检索文档的简化回答") simple_answer = f"基于检索到的文档内容,关于'{original_query}'的相关信息如下:\n\n" for i, doc in enumerate(final_retrieved_docs[:3], 1): simple_answer += f"{i}. {doc['text'][:200]}...\n\n" final_answer = simple_answer print("最终答案:") print(final_answer)
return { 'original_query': original_query, 'rewritten_query': rewritten_query, 'hyde_doc': hyde_doc, 'retrieved_docs': final_retrieved_docs, 'final_answer': final_answer, 'retrieval_method': retrieval_method }
class InteractiveMultimodalRAG: """交互式多模态RAG系统 - 集成CAMEL ModelFactory""" def __init__(self): self.api_key = None self.rag_system = None self.web_research_system = None self.knowledge_base_loaded = False self.current_pdf_source = None def initialize_system(self): """初始化系统 - 使用CAMEL ModelFactory""" print("初始化交互式多模态RAG系统...") load_dotenv() self.api_key = os.getenv('MODELSCOPE_SDK_TOKEN') if not self.api_key: print("错误:错误:请设置MODELSCOPE_SDK_TOKEN环境变量") print("提示:在.env文件中添加 MODELSCOPE_SDK_TOKEN=your_api_key") return False try: self.rag_system = SimpleRAGSystem(api_key=self.api_key, model_name="Qwen/Qwen2.5-72B-Instruct") print("√ 集成CAMEL的RAG系统初始化成功") if WEB_RESEARCH_AVAILABLE: try: self.web_research_system = EnhancedInteractiveResearchSystem() print("√ 网页研究系统初始化成功") except Exception as e: print(f"!警告: 网页研究系统初始化失败: {e}") self.web_research_system = None return True except Exception as e: print(f"!错误:系统初始化失败: {e}") return False def load_pdf_knowledge_base(self): """加载PDF知识库""" print("\nPDF知识库设置") print("="*50) print("1. 在线PDF (输入URL)") print("2. 本地PDF (输入文件路径)") print("3. 使用默认示例PDF") choice = input("\n请选择PDF来源 (1-3): ").strip() try: if choice == "1": pdf_url = input("请输入PDF的URL: ").strip() if not pdf_url: print("错误:URL不能为空") return False print(f"↓ 正在加载在线PDF: {pdf_url}") self.rag_system.setup_knowledge_base(pdf_url=pdf_url) self.current_pdf_source = f"在线PDF: {pdf_url}" elif choice == "2": pdf_path = input("请输入PDF文件路径: ").strip() if not pdf_path: print("错误:文件路径不能为空") return False if not os.path.exists(pdf_path): print(f"错误:文件不存在: {pdf_path}") return False print(f"状态查询: 正在加载本地PDF: {pdf_path}") self.rag_system.setup_knowledge_base(pdf_path=pdf_path) self.current_pdf_source = f"本地PDF: {pdf_path}" elif choice == "3": pdf_url = "https://arxiv.org/pdf/2303.17760.pdf" print(f"↓ 正在加载默认示例PDF: {pdf_url}") self.rag_system.setup_knowledge_base(pdf_url=pdf_url) self.current_pdf_source = f"示例PDF: CAMEL论文" else: print("错误:无效选择") return False self.knowledge_base_loaded = True print("√ PDF知识库加载成功!") return True except Exception as e: print(f"错误:PDF加载失败: {e}") return False def execute_query(self, query: str, retrieval_mode: str) -> Dict[str, Any]: """执行查询""" if not self.knowledge_base_loaded: return {"error": "知识库未加载,请先加载PDF"} print(f"\n执行查询: {query}") print(f"检索模式: {retrieval_mode}") try: if retrieval_mode == "快速检索": return self.quick_retrieval(query) elif retrieval_mode == "深度检索": results = self.rag_system.enhanced_query( original_query=query, use_rewriting=True, use_hyde=True, use_rrf=True, top_k=5, multimodal_preference=['text', 'image', 'table'] ) elif retrieval_mode == "主题检索": return self.topic_retrieval(query) else: return {"error": f"未知检索模式: {retrieval_mode}"} return results except Exception as e: return {"error": f"查询执行失败: {e}"} def quick_retrieval(self, query: str) -> Dict[str, Any]: """快速检索 - 基础向量检索直接生成答案""" print("\n执行快速检索...") print("="*40) try: print("正在进行向量检索...") retrieved_docs = self.rag_system.vector_retriever.query(query, top_k=3, filter_type='text') if not retrieved_docs: return {"error": "未找到相关文档"} print(f"√ 检索到 {len(retrieved_docs)} 个相关文档") for i, doc in enumerate(retrieved_docs, 1): similarity = doc.get('similarity', 0) text_preview = doc.get('text', '')[:150] + "..." if len(doc.get('text', '')) > 150 else doc.get('text', '') print(f"文档 {i} (相似度: {similarity:.3f}):") print(f" {text_preview}") print() context_texts = [doc['text'] for doc in retrieved_docs] context_str = '\n---\n'.join(context_texts) print("正在生成答案...") prompt = f"""基于以下文档内容回答问题:
文档内容: {context_str}
问题:{query}
请提供简洁明确的答案:""" final_answer = self.rag_system.llm.generate(prompt, max_tokens=400) print("√ 快速检索完成") return { 'original_query': query, 'retrieved_docs': retrieved_docs, 'final_answer': final_answer, 'retrieval_method': 'Quick Vector Retrieval' } except Exception as e: return {"error": f"快速检索失败: {e}"}
def topic_retrieval(self, query: str) -> Dict[str, Any]: """主题检索 - 集成网页研究系统""" print("\n执行网页检索...") print("="*40) try: if not self.web_research_system: print("警告:网页研究系统不可用,使用备用方案") return self.perform_fallback_topic_search(query) print("正在进行网页研究...") web_content = "" web_sources = [] try: if hasattr(self.web_research_system, 'research_and_analyze'): research_result = self.web_research_system.research_and_analyze(query) if isinstance(research_result, dict): web_content = research_result.get('content', '') web_sources = research_result.get('sources', []) else: web_content = str(research_result) web_sources = ["网页研究结果"] print("√ 网页研究完成") elif hasattr(self.web_research_system, 'toolkit') and hasattr(self.web_research_system.toolkit, 'search_web_for_topic'): search_result = self.web_research_system.toolkit.search_web_for_topic(query, "") web_content = search_result web_sources = ["网页搜索结果"] print("√ 网页搜索完成") elif hasattr(self.web_research_system, 'run_interactive_session'): print("警告:使用交互式研究系统,但无法直接调用") web_content = f"关于'{query}'的网页研究信息需要交互式操作" web_sources = ["交互式研究系统"] else: print("警告:网页研究系统方法不可用") web_content = f"关于'{query}'的网页搜索信息暂时不可用" web_sources = [] except Exception as e: print(f"警告:网页搜索失败: {e}") web_content = f"网页搜索遇到错误: {str(e)}" web_sources = [] print("正在检索PDF文档...") pdf_docs = self.rag_system.vector_retriever.query(query, top_k=3, filter_type='text') combined_context = "" if pdf_docs: pdf_context = "\n".join([doc['text'] for doc in pdf_docs]) combined_context += f"PDF文档内容:\n{pdf_context}\n\n" print(f"√ 检索到 {len(pdf_docs)} 个PDF文档") if web_content and web_content.strip() and not web_content.startswith("关于") and not web_content.startswith("网页搜索遇到错误"): combined_context += f"网页搜索内容:\n{web_content}\n\n" if not combined_context.strip(): print("警告:未找到相关信息,使用备用方案") return self.perform_fallback_topic_search(query) print("正在生成综合答案...") prompt = f"""基于以下PDF文档和网页搜索的信息,回答问题:
{combined_context}
问题:{query}
请提供综合性的详细答案:""" final_answer = self.rag_system.llm.generate(prompt, max_tokens=800) print("主题检索完成") return { 'original_query': query, 'pdf_docs': pdf_docs, 'web_sources': web_sources, 'final_answer': final_answer, 'retrieval_method': 'PDF+Web Topic Retrieval' } except Exception as e: print(f"警告:主题检索失败,使用备用方案: {e}") return self.perform_fallback_topic_search(query)
def perform_web_research(self, query: str) -> Dict[str, Any]: """执行网页研究""" print("正在进行网页研究...") try: web_content = f"基于网页搜索的{query}相关信息:\n" web_content += "- 网页来源1的相关内容\n" web_content += "- 网页来源2的相关内容\n" web_content += "- 网页来源3的相关内容" return { "web_content": web_content, "sources": ["网页来源1", "网页来源2", "网页来源3"], "method": "web_research" } except Exception as e: print(f"网页研究失败: {e}") return {"error": f"网页研究失败: {e}"}
def perform_fallback_topic_search(self, query: str) -> Dict[str, Any]: """备用主题搜索 - 仅使用PDF检索""" print("执行备用主题搜索(仅PDF检索)...") try: print("正在检索PDF文档...") pdf_docs = self.rag_system.vector_retriever.query(query, top_k=5, filter_type='text') if not pdf_docs: return {"error": "未找到相关PDF文档"} print(f"检索到 {len(pdf_docs)} 个PDF文档") for i, doc in enumerate(pdf_docs, 1): similarity = doc.get('similarity', 0) text_preview = doc.get('text', '')[:150] + "..." if len(doc.get('text', '')) > 150 else doc.get('text', '') print(f"文档 {i} (相似度: {similarity:.3f}):") print(f" {text_preview}") print() pdf_context = "\n".join([doc['text'] for doc in pdf_docs]) print("正在生成答案...") prompt = f"""基于以下PDF文档内容回答问题:
PDF文档内容: {pdf_context}
问题:{query}
请提供详细的答案,特别关注CAMEL框架的特性和工具:""" final_answer = self.rag_system.llm.generate(prompt, max_tokens=800) print("√ 备用主题搜索完成") return { 'original_query': query, 'retrieved_docs': pdf_docs, 'final_answer': final_answer, 'retrieval_method': 'Fallback PDF Topic Retrieval' } except Exception as e: print(f"备用主题搜索失败: {e}") return {"error": f"备用主题搜索失败: {e}"} def merge_web_and_pdf_results(self, web_results: Dict, pdf_results: Dict, query: str) -> Dict[str, Any]: """合并网页和PDF检索结果""" try: combined_context = "" if 'retrieved_docs' in pdf_results: pdf_context = "\n".join([doc['text'] for doc in pdf_results['retrieved_docs']]) combined_context += f"PDF文档内容:\n{pdf_context}\n\n" if 'web_content' in web_results: combined_context += f"网页搜索内容:\n{web_results['web_content']}\n\n" prompt = f"基于以下PDF文档和网页搜索的信息,回答问题:\n\n{combined_context}\n\n问题:{query}\n\n请提供综合性的详细答案。" final_answer = self.rag_system.llm.generate(prompt, max_tokens=800) return { 'original_query': query, 'pdf_docs': pdf_results.get('retrieved_docs', []), 'web_sources': web_results.get('sources', []), 'final_answer': final_answer, 'retrieval_method': 'PDF+Web主题检索' } except Exception as e: return {"error": f"结果合并失败: {e}"} def display_results(self, results: Dict[str, Any]): """显示查询结果""" if 'error' in results: print(f"错误: {results['error']}") return
print("\n" + "="*20 + " 深度检索结果 " + "="*20) print(f"原结始查询: {results.get('original_query', 'N/A')}") if results.get('rewritten_query'): print(f"重写查询: {results['rewritten_query']}") print(f"检索方法: {results.get('retrieval_method', 'N/A')}") retrieved_docs = results.get('retrieved_docs', []) if retrieved_docs: print(f"\n检索到的文档 (共{len(retrieved_docs)}个):") print() for i, doc in enumerate(retrieved_docs, 1): rrf_score = doc.get('rrf_score', doc.get('similarity', 0)) text_preview = doc.get('text', '')[:200] + "..." if len(doc.get('text', '')) > 200 else doc.get('text', '') print(f"文档 {i}:") print(f"相关度分数: {rrf_score}") print(f"内容预览: {text_preview}") print() final_answer = results.get('final_answer', 'N/A') print("💡 生成答案:") print(final_answer) print("="*60) save_choice = input("\n询问:是否保存结果到文件?(y/n): ").strip().lower() if save_choice == 'y': self._save_results_to_file(results)
def _save_results_to_file(self, results: Dict[str, Any]): """保存结果到文件""" try: from datetime import datetime timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') filename = f"rag_query_result_{timestamp}.txt" with open(filename, 'w', encoding='utf-8') as f: f.write("="*60 + "\n") f.write("RAG查询结果报告\n") f.write("="*60 + "\n\n") f.write(f"查询时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") f.write(f"原始查询: {results.get('original_query', 'N/A')}\n") if results.get('rewritten_query'): f.write(f"重写查询: {results['rewritten_query']}\n") f.write(f"检索方法: {results.get('retrieval_method', 'N/A')}\n\n") retrieved_docs = results.get('retrieved_docs', []) if retrieved_docs: f.write(f"检索到的文档 (共{len(retrieved_docs)}个):\n") f.write("-" * 40 + "\n") for i, doc in enumerate(retrieved_docs, 1): rrf_score = doc.get('rrf_score', doc.get('similarity', 0)) f.write(f"\n文档 {i}:\n") f.write(f"相关度分数: {rrf_score}\n") f.write(f"内容: {doc.get('text', '')}\n") f.write("-" * 40 + "\n") f.write(f"\n生成答案:\n") f.write(results.get('final_answer', 'N/A')) f.write("\n\n" + "="*60) print(f"√ 结果已保存到: {filename}") except Exception as e: print(f"错误:保存失败: {e}") def run_interactive_session(self): """运行交互式会话""" if not self.initialize_system(): return print("\n交互式多模态RAG系统") print("="*60) print("功能特性:") print("- 支持在线/本地PDF加载") print("- 三种检索模式") print("- 网页爬取集成") print("- 多模态内容处理") print("="*60) if not self.load_pdf_knowledge_base(): print("知识库加载失败,退出系统") return print(f"\n当前知识库: {self.current_pdf_source}") print(f"🔧 可用检索方法: {', '.join(self.rag_system.get_available_retrieval_methods())}") while True: try: print("\n" + "="*60) print("查询选项") print("="*60) query = input("请输入您的问题 (输入 'quit' 退出, 'reload' 重新加载PDF): ").strip() if query.lower() == 'quit': break elif query.lower() == 'reload': if self.load_pdf_knowledge_base(): print(f"√ 知识库已重新加载: {self.current_pdf_source}") continue elif not query: print("问题不能为空") continue print("\n选择检索模式:") print("1. 快速检索 (基础向量检索)") print("2. 深度检索 (重写+HyDE+RRF)") print("3. 主题检索 (PDF+网页爬取)") mode_choice = input("请选择模式 (1-3): ").strip() mode_map = { "1": "快速检索", "2": "深度检索", "3": "主题检索" } retrieval_mode = mode_map.get(mode_choice) if not retrieval_mode: print("无效选择,使用默认快速检索") retrieval_mode = "快速检索" results = self.execute_query(query, retrieval_mode) self.display_results(results) continue_choice = input("\n是否继续查询?(y/n): ").strip().lower() if continue_choice != 'y': break except KeyboardInterrupt: print("\n\n用户中断,退出系统") break except Exception as e: print(f"系统错误: {e}") continue print("\n感谢使用交互式多模态RAG系统!")
def main(): """主函数""" try: interactive_rag = InteractiveMultimodalRAG() interactive_rag.run_interactive_session() except Exception as e: print(f"系统启动失败: {e}") sys.exit(1)
if __name__ == "__main__": main()
|