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
| """ 完整的Agentic RAG系统实现 包含:路由、改写、纠错、自省所有模式 """
import asyncio from typing import List, Dict, Optional from dataclasses import dataclass from enum import Enum
class RAGMode(Enum): ROUTING = "routing" QUERY_REWRITING = "query_rewriting" CORRECTIVE = "corrective" SELF_RAG = "self_rag" ADAPTIVE = "adaptive"
@dataclass class RetrievalResult: content: str source: str score: float metadata: dict
@dataclass class AgenticResponse: answer: str mode_used: RAGMode sources: List[RetrievalResult] reasoning_steps: List[str] confidence: float execution_time: float
class AgenticRAGSystem: """ 完整的Agentic RAG系统 特点: - 自动选择最佳策略 - 多轮检索验证 - 自我纠错机制 """ def __init__( self, llm, vector_store, embed_model, enable_web_search: bool = True ): self.llm = llm self.vector_store = vector_store self.embed_model = embed_model self.enable_web_search = enable_web_search self.routing_rag = RoutingRAG(llm, vector_store) self.query_rewriting_rag = QueryRewritingRAG(llm, vector_store, embed_model) self.corrective_rag = CorrectiveRAG(llm, vector_store, enable_web_search) self.self_rag = SelfRAG(llm, vector_store) self.stats = {mode: {'count': 0, 'avg_time': 0} for mode in RAGMode} async def query( self, query: str, mode: Optional[RAGMode] = None, user_context: dict = None ) -> AgenticResponse: """ 主查询接口 Args: query: 用户查询 mode: 指定RAG模式,None则自动选择 user_context: 用户上下文(历史对话等) """ import time start_time = time.time() if mode is None: mode = await self._select_mode(query, user_context) if mode == RAGMode.ROUTING: result = await self.routing_rag.process(query) elif mode == RAGMode.QUERY_REWRITING: result = await self.query_rewriting_rag.process(query) elif mode == RAGMode.CORRECTIVE: result = await self.corrective_rag.process(query) elif mode == RAGMode.SELF_RAG: result = await self.self_rag.process(query) else: result = await self._adaptive_process(query) execution_time = time.time() - start_time self._update_stats(mode, execution_time) response = AgenticResponse( answer=result['answer'], mode_used=mode, sources=result.get('sources', []), reasoning_steps=result.get('reasoning_steps', []), confidence=result.get('confidence', 0.8), execution_time=execution_time ) return response async def _select_mode(self, query: str, context: dict) -> RAGMode: """ 自动选择最佳RAG模式 决策逻辑: 1. 简单明确的问题 → ROUTING 2. 需要多角度理解 → QUERY_REWRITING 3. 知识库可能不完整 → CORRECTIVE 4. 需要深度推理 → SELF_RAG 5. 复杂多变的场景 → ADAPTIVE """ features = await self._analyze_query(query) if features['complexity'] <= 3: return RAGMode.ROUTING elif features['ambiguity'] > 0.7: return RAGMode.QUERY_REWRITING elif features['knowledge_coverage'] < 0.5: return RAGMode.CORRECTIVE elif features['requires_reasoning']: return RAGMode.SELF_RAG else: return RAGMode.ADAPTIVE async def _analyze_query(self, query: str) -> dict: """分析查询特征""" return { 'complexity': len(query.split()) / 10, 'ambiguity': 0.5, 'knowledge_coverage': 0.7, 'requires_reasoning': any(kw in query.lower() for kw in ['为什么', '如何', '分析']) } async def _adaptive_process(self, query: str) -> dict: """ 自适应处理 动态调整策略,多次尝试直到满意 """ reasoning_steps = [] step1 = "第1轮:尝试直接检索" reasoning_steps.append(step1) result = await self.routing_rag.process(query) quality = await self._evaluate_quality(query, result) if quality >= 0.8: reasoning_steps.append(f"质量评分: {quality:.2f},直接返回") result['reasoning_steps'] = reasoning_steps return result step2 = f"第2轮:质量不够({quality:.2f}),尝试查询改写" reasoning_steps.append(step2) result = await self.query_rewriting_rag.process(query) quality = await self._evaluate_quality(query, result) if quality >= 0.7: reasoning_steps.append(f"质量评分: {quality:.2f},返回结果") result['reasoning_steps'] = reasoning_steps return result step3 = f"第3轮:仍不满意({quality:.2f}),启用纠错机制" reasoning_steps.append(step3) result = await self.corrective_rag.process(query) result['reasoning_steps'] = reasoning_steps return result async def _evaluate_quality(self, query: str, result: dict) -> float: """评估回答质量""" if not result.get('sources'): return 0.3 if len(result['sources']) < 2: return 0.5 answer = result.get('answer', '') if len(answer) < 50: return 0.6 return 0.8 def _update_stats(self, mode: RAGMode, execution_time: float): """更新性能统计""" stats = self.stats[mode] stats['count'] += 1 alpha = 0.1 stats['avg_time'] = (1 - alpha) * stats['avg_time'] + alpha * execution_time def get_stats(self) -> dict: """获取性能统计""" return self.stats
class RoutingRAG: """简单的路由式RAG""" def __init__(self, llm, vector_store): self.llm = llm self.vector_store = vector_store async def process(self, query: str) -> dict: """处理查询""" results = await self.vector_store.similarity_search(query, k=5) context = "\n\n".join([ f"[{i+1}] {doc.page_content}" for i, doc in enumerate(results) ]) prompt = f""" 基于以下信息回答问题: {context} 问题:{query} 请提供简洁准确的答案。 """ answer = await self.llm.acomplete(prompt) return { 'answer': answer.text, 'sources': [ RetrievalResult( content=doc.page_content[:200], source=doc.metadata.get('source', 'unknown'), score=1.0, metadata=doc.metadata ) for doc in results ] }
class QueryRewritingRAG: """查询改写RAG""" def __init__(self, llm, vector_store, embed_model): self.llm = llm self.vector_store = vector_store self.embed_model = embed_model async def process(self, query: str) -> dict: """处理查询""" variants = await self._generate_variants(query) all_results = [] for variant in [query] + variants: results = await self.vector_store.similarity_search(variant, k=5) all_results.extend(results) unique_results = self._deduplicate(all_results) reranked = unique_results[:5] context = "\n\n".join([doc.page_content for doc in reranked]) answer = await self._generate_answer(query, context) return { 'answer': answer, 'sources': [ RetrievalResult( content=doc.page_content[:200], source=doc.metadata.get('source', 'unknown'), score=1.0, metadata=doc.metadata ) for doc in reranked ], 'rewritten_queries': variants } async def _generate_variants(self, query: str) -> List[str]: """生成查询变体""" prompt = f""" 为以下查询生成2个语义相同但表述不同的变体: 原查询:{query} 要求: 1. 保持核心意图不变 2. 使用不同的词汇和句式 3. 每行一个变体 变体: """ response = await self.llm.acomplete(prompt) variants = [line.strip() for line in response.text.strip().split('\n') if line.strip()] return variants[:2] def _deduplicate(self, docs: List) -> List: """去重""" seen = set() unique = [] for doc in docs: content_hash = hash(doc.page_content) if content_hash not in seen: seen.add(content_hash) unique.append(doc) return unique async def _generate_answer(self, query: str, context: str) -> str: """生成答案""" prompt = f""" 基于以下信息回答问题: {context} 问题:{query} 答案: """ response = await self.llm.acomplete(prompt) return response.text
class CorrectiveRAG: """纠错式RAG,自动评估和改进检索质量""" def __init__(self, llm, vector_store, enable_web_search: bool = True): self.llm = llm self.vector_store = vector_store self.enable_web_search = enable_web_search async def process(self, query: str) -> dict: """处理查询""" initial_results = await self.vector_store.similarity_search(query, k=10) quality_scores = await self._evaluate_results(query, initial_results) avg_score = sum(quality_scores) / len(quality_scores) if quality_scores else 0 if avg_score >= 0.7: final_results = initial_results[:5] decision = "直接使用知识库结果" elif avg_score >= 0.4: final_results = await self._refine_retrieval(query, initial_results, quality_scores) decision = "改进检索策略" else: if self.enable_web_search: final_results = await self._web_search(query) decision = "使用网络搜索" else: final_results = initial_results[:5] decision = "知识库结果不理想,但无法使用网络搜索" context = "\n\n".join([doc.page_content for doc in final_results]) answer = await self._generate_answer(query, context) return { 'answer': answer, 'sources': [ RetrievalResult( content=doc.page_content[:200], source=doc.metadata.get('source', 'unknown'), score=quality_scores[i] if i < len(quality_scores) else 0.5, metadata=doc.metadata ) for i, doc in enumerate(final_results) ], 'decision': decision, 'quality_scores': quality_scores } async def _evaluate_results(self, query: str, results: List) -> List[float]: """评估检索结果质量""" scores = [] for doc in results: query_words = set(query.lower().split()) doc_words = set(doc.page_content.lower().split()) overlap = len(query_words & doc_words) score = min(overlap / len(query_words), 1.0) if query_words else 0.0 scores.append(score) return scores async def _refine_retrieval( self, query: str, initial_results: List, quality_scores: List[float] ) -> List: """改进检索""" good_docs = [ doc for doc, score in zip(initial_results, quality_scores) if score >= 0.5 ] if not good_docs: return initial_results[:5] key_concepts = [] for doc in good_docs[:2]: words = doc.page_content.split() concepts = [w for w in words if len(w) > 5] key_concepts.extend(concepts[:3]) expanded_query = f"{query} {' '.join(key_concepts[:5])}" refined_results = await self.vector_store.similarity_search(expanded_query, k=5) return refined_results async def _web_search(self, query: str) -> List: """网络搜索(模拟)""" return [] async def _generate_answer(self, query: str, context: str) -> str: """生成答案""" prompt = f""" 基于以下信息回答问题: {context} 问题:{query} 答案: """ response = await self.llm.acomplete(prompt) return response.text
class SelfRAG: """自省式RAG,动态决定何时检索和生成""" def __init__(self, llm, vector_store): self.llm = llm self.vector_store = vector_store async def process(self, query: str) -> dict: """处理查询""" reasoning_steps = [] need_retrieval = await self._should_retrieve(query) reasoning_steps.append(f"需要检索: {need_retrieval}") if not need_retrieval: answer = await self.llm.acomplete(query) return { 'answer': answer.text, 'sources': [], 'reasoning_steps': reasoning_steps, 'retrieval_used': False } docs = await self.vector_store.similarity_search(query, k=5) reasoning_steps.append(f"检索到 {len(docs)} 个文档") context = "\n\n".join([doc.page_content for doc in docs]) answer_parts = [] segment = await self._generate_segment(query, context) answer_parts.append(segment) reasoning_steps.append("生成第一段") for i in range(2): reflection = await self._reflect(query, answer_parts, context) reasoning_steps.append(f"反思 {i+1}: {reflection['status']}") if reflection['is_complete']: break if reflection['need_more_info']: new_query = reflection['refined_query'] new_docs = await self.vector_store.similarity_search(new_query, k=3) context += "\n\n" + "\n\n".join([doc.page_content for doc in new_docs]) reasoning_steps.append(f"补充检索: {new_query}") next_segment = await self._generate_segment( query, context, previous=" ".join(answer_parts) ) answer_parts.append(next_segment) final_answer = " ".join(answer_parts) return { 'answer': final_answer, 'sources': [ RetrievalResult( content=doc.page_content[:200], source=doc.metadata.get('source', 'unknown'), score=1.0, metadata=doc.metadata ) for doc in docs ], 'reasoning_steps': reasoning_steps, 'retrieval_used': True } async def _should_retrieve(self, query: str) -> bool: """判断是否需要检索""" factual_keywords = ['什么', '哪些', '多少', '何时', '谁'] return any(kw in query for kw in factual_keywords) async def _generate_segment( self, query: str, context: str, previous: str = "" ) -> str: """生成一段回答""" if previous: prompt = f""" 问题: {query} 上下文: {context[:1000]} 已生成内容: {previous} 继续生成下一段(保持连贯): """ else: prompt = f""" 问题: {query} 上下文: {context[:1000]} 开始回答: """ response = await self.llm.acomplete(prompt) return response.text.strip() async def _reflect( self, query: str, answer_parts: List[str], context: str ) -> dict: """自我反思""" current_answer = " ".join(answer_parts) if len(current_answer) > 200: return { 'is_complete': True, 'need_more_info': False, 'status': '内容充分' } return { 'is_complete': False, 'need_more_info': True, 'refined_query': f"{query} 详细说明", 'status': '需要更多信息' }
async def main(): """完整使用示例""" from llama_index.llms.openai import OpenAI from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.embeddings.openai import OpenAIEmbedding documents = SimpleDirectoryReader("./data").load_data() index = VectorStoreIndex.from_documents(documents) llm = OpenAI(model="gpt-4") embed_model = OpenAIEmbedding() rag_system = AgenticRAGSystem( llm=llm, vector_store=index, embed_model=embed_model, enable_web_search=False ) queries = [ "什么是机器学习?", "机器学习和深度学习有什么区别?", "如何从零开始学习AI?", "为什么Transformer模型这么有效?" ] for query in queries: print(f"\n{'='*60}") print(f"查询: {query}") print(f"{'='*60}") response = await rag_system.query(query) print(f"\n使用模式: {response.mode_used.value}") print(f"执行时间: {response.execution_time:.2f}s") print(f"置信度: {response.confidence:.2f}") print(f"\n回答: {response.answer}") if response.reasoning_steps: print(f"\n推理步骤:") for step in response.reasoning_steps: print(f" - {step}") print(f"\n来源数量: {len(response.sources)}") print(f"\n{'='*60}") print("性能统计:") print(f"{'='*60}") stats = rag_system.get_stats() for mode, stat in stats.items(): if stat['count'] > 0: print(f"{mode.value}: {stat['count']}次, 平均{stat['avg_time']:.2f}s")
if __name__ == "__main__": asyncio.run(main())
|