收藏必看!从零开始构建自我改进的Agentic RAG系统:大模型实战指南

Agentic RAG:RAG从静态到具有理解、推理、决策的Agentic RAG RAG技术演进:从静态检索到智能代理 RAG(检索增强生成)技术经历了五个关键发展阶段:基础RAG(关键词检索)、高级RAG(语义理解)、模块化RAG(灵活架构)、图RAG(知识图谱)和最新的Agentic RAG(智能代理)。Agentic RAG通过引入自主AI代理,具备反思、规划、工具使用和多代理协作能力,实现了动态决策和自适应工作流。相比传统RAG的静态检索流程,Agentic RAG能处理复杂多步推理任务,通过自我改进机制提高输出质量,并支持多专业代理协作,显著提升了RAG系统在复杂场景下的表现。 阅读详情

本文介绍了一个自我改进的Agentic RAG系统架构,通过专家代理团队协作、多维评价系统、性能诊断和SOP架构代理实现系统自我优化。系统采用帕累托前沿分析方法,在医疗健康领域应用中能够自动调优prompt工程、检索策略等设计维度,解决传统RAG系统难以适应未见数据的问题,为开发者提供了一套可扩展的自进化AI框架。

Agentic RAG 系统可以被视为一个“高维向量空间”,其中每个维度都对应一次设计决策,例如 prompt engineering、agent 协同、retrieval 策略等。手动调优这些维度以找到“正确组合”非常困难,而且上线后的未见数据往往会打破测试时有效的配置。

一个更好的方法是让系统学会“自我优化”。一条典型的、能“自我进化”的 Agentic RAG 流水线,遵循如下思考过程:

Self Improving Agentic RAG System (Created by Fareed Khan)

  • 一个由“专家型代理(specialist agents)”组成的协作团队执行任务。它基于一个高层概念,按照当前 SOP(标准作业程序)生成一份完整的、多来源文档。
  • 一个“多维评价系统(multi-dimensional evaluation system)”对团队输出进行评分,度量准确性、可行性、合规性等多个目标,得到一个性能向量。
  • 一个“性能诊断代理(diagnostician agent)”分析该向量,像咨询顾问一样识别流程中的主要薄弱环节,并追溯根因。
  • 一个“SOP 架构代理(SOP architect agent)”基于诊断洞见更新流程,提出专门用于修复薄弱点的新变体。
  • 每个“SOP 新版本”都会在团队重复执行任务时进行测试,每次输出再被评估,以生成对应的性能向量。
  • 系统识别“Pareto front(帕累托前沿)”,即所有已测 SOP 的最优权衡组合,并将这些优化策略呈现给“人类决策者”,从而闭合进化回路。

在这篇博客中,我们将瞄准“医疗健康(healthcare)”领域。该领域的挑战在于:需要针对输入查询或知识库考虑“多种可能性”,同时“最终决策仍由人类掌握。”

我们将构建一条端到端、可自我改进的 Agentic RAG 流水线,用来生成 RAG 系统的不同设计模式。

完整代码可在我的 GitHub 仓库获取:

GitHub - FareedKhan-dev/autonomous-agentic-rag: Self improving agentic rag pipeline

医学 AI 的知识基础设施

在编写可自进化的 agentic RAG 系统之前,我们需要先建立合适的知识数据库,以及搭建用于构建架构的必要工具。

一套生产级 RAG 系统通常包含多样化的数据库,既包括敏感的组织内部数据,也包含开源数据,用来提升检索质量,并弥补信息过时或不完整的问题。这个基础步骤可以说是最关键的……

因为数据源的质量将直接决定最终输出的质量。

Sourcing the knowledge base (Created by Fareed Khan)

本节我们将组装整套架构的各个组件。计划如下:

  • 安装开源技术栈(Open-Source Stack):搭建环境并安装必要库,坚持本地、开源优先(open-source-first)。
  • 配置安全可观测性(Secure Observability):安全加载 API Key,并配置 LangSmith,从一开始就追踪和调试复杂的代理交互。
  • 搭建本地 LLM 工坊(LLM Foundry):通过 Ollama 构建不同的开源模型组合,为不同任务分配不同模型,以优化表现与成本。
  • 获取并处理多模态数据:下载并准备 4 类真实数据源:PubMed 科学文献、FDA 监管指南、伦理原则,以及一个大型结构化临床数据集(MIMIC-III)。
  • 索引知识库(Index the Knowledge Stores):最终,将原始数据处理为高效可检索的数据库:对非结构化文本使用 FAISS 向量库,对结构化临床数据使用 DuckDB。

安装开源技术栈

第一步是安装所需的 Python 库。可复现的环境是一切严肃项目的基石。我们选择业界标准的开源栈,以便对系统进行完全掌控。包括用于核心 agentic 框架的 langchain 和 langgraph、与本地 LLM 交互的 ollama,以及访问 PubMed 的 biopython、进行高性能临床数据分析的 duckdb 等专业库。

让我们安装需要的模块……

# We uses pip "quiet" (-q) and "upgrade" (-U) flags to install all the required packages.
# - langchain, langgraph, etc.: These form the core of our agentic framework for building and orchestrating agents.
# - ollama: This is the client library that allows our Python code to communicate with a locally running Ollama server.
# - duckdb: An incredibly fast, in-process analytical database perfect for handling our structured MIMIC data without a heavy server setup.
# - faiss-cpu: Facebook AI's library for efficient similarity search, which will power the vector stores for our RAG agents.
# - sentence-transformers: A library for easy access to state-of-the-art models for creating text embeddings.
# - biopython, pypdf, beautifulsoup4: A suite of powerful utilities for downloading and parsing our diverse, real-world data sources.
%pip install -U langchain langgraph langchain_community langchain_openai langchain_core ollama pandas duckdb faiss-cpu sentence-transformers biopython pypdf pydantic lxml html2text beautifulsoup4 matplotlib -qqq

我们一次性准备好所有工具和“建筑材料”。各库各司其职:从用 langgraph 编排 agent 工作流,到用 duckdb 做数据分析。

模块安装完成后,让我们逐一初始化它们。

环境配置与依赖导入

我们需要安全地配置环境。把 API Key 硬编码在笔记本里既有安全风险,也不利于共享代码。

我们使用 .env 文件管理敏感信息,主要是 LangSmith 的 API Key。从一开始就配置 LangSmith 是不可妥协的要求,这将为我们提供深度可观测性,以跟踪、调试并理解 agents 之间的交互。上代码:

import os
import getpass
from dotenv import load_dotenv

# This function from the python-dotenv library searches for a .env file and loads its key-value pairs
# into the operating system's environment variables, making them accessible to our script.
load_dotenv()

# This is a critical check. We verify that our script can access the necessary API keys from the environment.
if"LANGCHAIN_API_KEY"notin os.environ or"ENTREZ_EMAIL"notin os.environ:
    # If the keys are missing, we print an error and halt, as the application cannot proceed.
    print("Required environment variables not set. Please set them in your .env file or environment.")
else:
    # This confirmation tells us our secrets have been loaded securely and are ready for use.
    print("Environment variables loaded successfully.")

# We explicitly set the LangSmith project name. This is a best practice that ensures all traces

# generated by this project are automatically grouped together in the LangSmith user interface for easy analysis.
os.environ["LANGCHAIN_PROJECT"] = "AI_Clinical_Trials_Architect"

load_dotenv() 是敏感凭据与代码之间的一座“安全桥梁”。它读取 .env(绝不要提交到版本库),并将密钥注入环境。

从现在起,我们使用 LangChain 或 LangGraph 的所有操作都会自动被采集,并发送到 LangSmith 的项目中。

配置本地大语言模型

在生产级 agentic 系统中,“一刀切”的模型策略往往不是最佳。大型 SOTA 模型计算开销大且慢,把它用于简单任务会浪费资源(尤其自托管在 GPU 时)。但小模型虽然快速,却可能缺乏做关键决策所需的深度推理能力。

Configuring Local LLMs (Created by Fareed Khan)

关键在于将“合适的模型放在系统的合适位置”。我们将构建一个多模型组合(均由 Ollama 本地服务以保障隐私、可控与成本效益),每个模型在特定角色上发挥所长。

先定义一个配置字典,集中管理每个选定模型的客户端,便于替换与统一管理。

from langchain_community.chat_models import ChatOllama
from langchain_community.embeddings import OllamaEmbeddings

# This dictionary will act as our central registry, or "foundry," for all LLM and embedding model clients.
llm_config = {
    # For the 'planner', we use Llama 3.1 8B. It's a modern, highly capable model that excels at instruction-following.
    # We set `format='json'` to leverage Ollama's built-in JSON mode, ensuring reliable structured output for this critical task.
    "planner": ChatOllama(model="llama3.1:8b-instruct", temperature=0.0, format='json'),
    
    # For the 'drafter' and 'sql_coder', we use Qwen2 7B. It's a nimble and fast model, perfect for
    # tasks like text generation and code completion where speed is valuable.
    "drafter": ChatOllama(model="qwen2:7b", temperature=0.2),
    "sql_coder": ChatOllama(model="qwen2:7b", temperature=0.0),
    
    # For the 'director', the highest-level strategic agent, we use the powerful Llama 3 70B model.
    # This high-stakes task of diagnosing performance and evolving the system's own procedures
    # justifies the use of a larger, more powerful model.
    "director": ChatOllama(model="llama3:70b", temperature=0.0, format='json'),
    # For embeddings, we use 'nomic-embed-text', a top-tier, efficient open-source model.
    "embedding_model": OllamaEmbeddings(model="nomic-embed-text")
}

我们刚刚创建了 llm_config 字典,作为所有模型初始化的“中央枢纽”。通过为不同角色分配不同模型,构建一套按成本-性能权衡优化的层次结构。

  • 快速灵巧(7B–8B):planner、drafter、sql_coder 处理频繁、定义清晰的任务。使用 Qwen2 7B、Llama 3.1 8B 能保证低延迟与高性价比,同时具备足够的指令跟随能力生成计划、撰写文本或编写 SQL。
  • 深度策略(70B):director 需要分析多维性能数据并改写整个 SOP,要求较强的因果推理与全局理解。为这种“低频高风险”任务分配 Llama 3 70B 是合理的。

打印配置以确认:

# Print the configuration to confirm the clients are initialized and their parameters are set correctly.
print("LLM clients configured:")
print(f"Planner ({llm_config['planner'].model}): {llm_config['planner']}")
print(f"Drafter ({llm_config['drafter'].model}): {llm_config['drafter']}")
print(f"SQL Coder ({llm_config['sql_coder'].model}): {llm_config['sql_coder']}")
print(f"Director ({llm_config['director'].model}): {llm_config['director']}")
print(f"Embedding Model ({llm_config['embedding_model'].model}): {llm_config['embedding_model']}")

输出示例:

#### OUTPUT ####
LLM clients configured:
Planner (llama3.1:8b-instruct): ChatOllama(model='llama3.1:8b-instruct', temperature=0.0, format='json')
Drafter (qwen2:7b): ChatOllama(model='qwen2:7b', temperature=0.2)
SQL Coder (qwen2:7b): ChatOllama(model='qwen2:7b', temperature=0.0)
Director (llama3:70b): ChatOllama(model='llama3:70b', temperature=0.0, format='json')
Embedding Model (nomic-embed-text): OllamaEmbeddings(model='nomic-embed-text')

这表明 ChatOllama 和 OllamaEmbeddings 客户端已按指定模型与参数成功初始化。接下来连接知识库。

准备知识库

RAG 的“灵魂”在于一套丰富的多模态知识基座。面对临床试验设计这样的专业任务,通用的网页搜索远远不够。我们需要以权威、领域特定的信息作为根基。

Knowledge store creation (Created by Fareed Khan)

为此,我们将构建一个全面的“知识库”,从四类真实世界数据中采集、下载并处理内容。多源融合对帮助 agents 进行信息综合至关重要,最终输出也会更全面更可靠。

先创建数据目录:

import os

# A dictionary to hold the paths for our different data types. This keeps our file management clean and centralized.
data_paths = {
    "base": "./data",
    "pubmed": "./data/pubmed_articles",
    "fda": "./data/fda_guidelines",
    "ethics": "./data/ethical_guidelines",
    "mimic": "./data/mimic_db"
}
# This loop iterates through our defined paths and uses os.makedirs() to create any directories that don't already exist.
# This prevents errors in later steps when we try to save files to these locations.
for path in data_paths.values():
    ifnot os.path.exists(path):
        os.makedirs(path)
        print(f"Created directory: {path}")

这确保项目从一开始就拥有干净、组织良好的文件结构。

接着从 PubMed 获取真实文献,为 Medical Researcher 提供核心知识:

from Bio import Entrez
from Bio import Medline

defdownload_pubmed_articles(query, max_articles=20):
    """Fetches abstracts from PubMed for a given query and saves them as text files."""
    # The NCBI API requires an email address for identification. We fetch it from our environment variables.
    Entrez.email = os.environ.get("ENTREZ_EMAIL")
    print(f"Fetching PubMed articles for query: {query}")
    
    # Step 1: Use Entrez.esearch to find the PubMed IDs (PMIDs) for articles matching our query.
    handle = Entrez.esearch(db="pubmed", term=query, retmax=max_articles, sort="relevance")
    record = Entrez.read(handle)
    id_list = record["IdList"]
    print(f"Found {len(id_list)} article IDs.")
    
    print("Downloading articles...")
    # Step 2: Use Entrez.efetch to retrieve the full records (in MEDLINE format) for the list of PMIDs.
    handle = Entrez.efetch(db="pubmed", id=id_list, rettype="medline", retmode="text")
    records = Medline.parse(handle)
    
    count = 0
    # Step 3: Iterate through the retrieved records, parse them, and save each abstract to a file.
    for i, record inenumerate(records):
        pmid = record.get("PMID", "")
        title = record.get("TI", "No Title")
        abstract = record.get("AB", "No Abstract")
        if pmid:
            # We name the file after the PMID for easy reference and to avoid duplicates.
            filepath = os.path.join(data_paths["pubmed"], f"{pmid}.txt")
            withopen(filepath, "w") as f:
                f.write(f"Title: {title}\n\nAbstract: {abstract}")
            print(f"[{i+1}/{len(id_list)}] Fetching PMID: {pmid}... Saved to {filepath}")
            count += 1
    return count

该函数按 3 步连接 NCBI,检索符合布尔查询的 PMID、拉取 MEDLINE 记录并保存标题与摘要到本地文本文件。

执行:

# We define a specific, boolean query to find articles highly relevant to our trial concept.
pubmed_query = "(SGLT2 inhibitor) AND (type 2 diabetes) AND (renal impairment)"
num_downloaded = download_pubmed_articles(pubmed_query)
print(f"PubMed download complete. {num_downloaded} articles saved.")

示例输出:

#### OUTPUT ####
Fetching PubMed articles for query: (SGLT2 inhibitor) AND (type 2 diabetes) AND (renal impairment)
Found 20 article IDs.
Downloading articles...
[1/20] Fetching PMID: 38810260... Saved to ./data/pubmed_articles/38810260.txt
[2/20] Fetching PMID: 38788484... Saved to ./data/pubmed_articles/38788484.txt
...
PubMed download complete. 20 articles saved.

现在 Medical Researcher 具备扎实、最新、领域特定的科学依据。

接下来获取监管文件,供 Regulatory Specialist 使用:

import requests
from pypdf import PdfReader
import io

defdownload_and_extract_text_from_pdf(url, output_path):
    """Downloads a PDF from a URL, saves it, and also extracts its text content to a separate .txt file."""
    print(f"Downloading FDA Guideline: {url}")
    try:
        # We use the 'requests' library to perform the HTTP GET request to download the file.
        response = requests.get(url)
        response.raise_for_status() # This is a good practice that will raise an error if the download fails (e.g., a 404 error).
        
        # We save the raw PDF file, which is useful for archival purposes.
        withopen(output_path, 'wb') as f:
            f.write(response.content)
        print(f"Successfully downloaded and saved to {output_path}")
        
        # We then use pypdf to read the PDF content directly from the in-memory response.
        reader = PdfReader(io.BytesIO(response.content))
        text = ""
        # We loop through each page of the PDF and append its extracted text.
        for page in reader.pages:
            text += page.extract_text() + "\n\n"
        
        # Finally, we save the clean, extracted text to a .txt file. This is the file our RAG system will actually use.
        txt_output_path = os.path.splitext(output_path)[0] + '.txt'
        withopen(txt_output_path, 'w') as f:
            f.write(text)
        returnTrue
    except requests.exceptions.RequestException as e:
        print(f"Error downloading file: {e}")
        returnFalse

运行下载 FDA 指南并抽取文本:

# This URL points to a real FDA guidance document for developing drugs for diabetes.
fda_url = "https://www.fda.gov/media/71185/download"
fda_pdf_path = os.path.join(data_paths["fda"], "fda_diabetes_guidance.pdf")
download_and_extract_text_from_pdf(fda_url, fda_pdf_path)

#### OUTPUT ####
Downloading FDA Guideline: https://www.fda.gov/media/71185/download
Successfully downloaded and saved to ./data/fda_guidelines/fda_diabetes_guidance.pdf

现在 Regulatory Specialist 拥有法律与监管文本的基础语料。

接着为 Ethics Specialist 准备一份精要文档(相当于 Belmont Report 的核心原则摘要),以确保其推理建立在最重要概念之上:

# This multi-line string contains a curated summary of the three core principles of the Belmont Report,
# which is the foundational document for ethics in human subject research in the United States.
ethics_content = """
Title: Summary of the Belmont Report Principles for Clinical Research
1. Respect for Persons: This principle requires that individuals be treated as autonomous agents and that persons with diminished autonomy are entitled to protection. This translates to robust informed consent processes. Inclusion/exclusion criteria must not unduly target or coerce vulnerable populations, such as economically disadvantaged individuals, prisoners, or those with severe cognitive impairments, unless the research is directly intended to benefit that population.
2. Beneficence: This principle involves two complementary rules: (1) do not harm and (2) maximize possible benefits and minimize possible harms. The criteria must be designed to select a population that is most likely to benefit and least likely to be harmed by the intervention. The risks to subjects must be reasonable in relation to anticipated benefits.
3. Justice: This principle concerns the fairness of distribution of the burdens and benefits of research. The selection of research subjects must be equitable. Criteria should not be designed to exclude certain groups without a sound scientific or safety-related justification. For example, excluding participants based on race, gender, or socioeconomic status is unjust unless there is a clear rationale related to the drug's mechanism or risk profile.
"""

# We define the path where our ethics document will be saved.
ethics_path = os.path.join(data_paths["ethics"], "belmont_summary.txt")

# We open the file in write mode and save the content.
with open(ethics_path, "w") as f:
    f.write(ethics_content)
print(f"Created ethics guideline file: {ethics_path}")

最后是最复杂的数据源:来自 MIMIC-III 的结构化临床数据,为 Patient Cohort Analyst 提供真实世界人群数据,用以评估招募可行性。

import duckdb
import pandas as pd
import os


defload_real_mimic_data():
    """Loads real MIMIC-III CSVs into a persistent DuckDB database file, processing the massive LABEVENTS table efficiently."""
    print("Attempting to load real MIMIC-III data from local CSVs...")
    db_path = os.path.join(data_paths["mimic"], "mimic3_real.db")
    csv_dir = os.path.join(data_paths["mimic"], "mimiciii_csvs")
    
    # Define the paths to the required compressed CSV files.
    required_files = {
        "patients": os.path.join(csv_dir, "PATIENTS.csv.gz"),
        "diagnoses": os.path.join(csv_dir, "DIAGNOSES_ICD.csv.gz"),
        "labevents": os.path.join(csv_dir, "LABEVENTS.csv.gz"),
    }
    
    # Before starting, we check if all the necessary source files are present.
    missing_files = [path for path in required_files.values() ifnot os.path.exists(path)]
    if missing_files:
        print("ERROR: The following MIMIC-III files were not found:")
        for f in missing_files: print(f"- {f}")
        print("\nPlease download them as instructed and place them in the correct directory.")
        returnNone
    
    print("Required files found. Proceeding with database creation.")
    # Remove any old database file to ensure we are building from scratch.
    if os.path.exists(db_path):
        os.remove(db_path)
    # Connect to DuckDB. If the database file doesn't exist, it will be created.
    con = duckdb.connect(db_path)
    
    # Use DuckDB's powerful `read_csv_auto` to directly load data from the gzipped CSVs into SQL tables.
    print(f"Loading {required_files['patients']} into DuckDB...")
    con.execute(f"CREATE TABLE patients AS SELECT SUBJECT_ID, GENDER, DOB, DOD FROM read_csv_auto('{required_files['patients']}')")
    
    print(f"Loading {required_files['diagnoses']} into DuckDB...")
    con.execute(f"CREATE TABLE diagnoses_icd AS SELECT SUBJECT_ID, ICD9_CODE FROM read_csv_auto('{required_files['diagnoses']}')")
    
    # The LABEVENTS table is enormous. To handle it robustly, we use a two-stage process.
    print(f"Loading and processing {required_files['labevents']} (this may take several minutes)...")
    # 1. Load the data into a temporary 'staging' table, treating all columns as text (`all_varchar=True`).
    #    This prevents parsing errors with mixed data types. We also filter for only the lab item IDs we
    #    care about (50912 for Creatinine, 50852 for HbA1c) and use a regex to ensure VALUENUM is numeric.
    con.execute(f"""CREATE TABLE labevents_staging AS 
                   SELECT SUBJECT_ID, ITEMID, VALUENUM 
                   FROM read_csv_auto('{required_files['labevents']}', all_varchar=True) 
                   WHERE ITEMID IN ('50912', '50852') AND VALUENUM IS NOT NULL AND VALUENUM ~ '^[0-9]+(\\.[0-9]+)?$'
                """)
    # 2. Create the final, clean table by selecting from the staging table and casting the columns to their correct numeric types.
    con.execute("CREATE TABLE labevents AS SELECT SUBJECT_ID, CAST(ITEMID AS INTEGER) AS ITEMID, CAST(VALUENUM AS DOUBLE) AS VALUENUM FROM labevents_staging")
    # 3. Drop the temporary staging table to save space.
    con.execute("DROP TABLE labevents_staging")
    con.close()
    return db_path

这里利用 DuckDB 直接从磁盘处理大型 CSV,而不是用 pandas 全量读入内存;对 LABEVENTS 采用两阶段清洗(先 all_varchar 过滤,再强制转换类型),以稳健应对数据质量问题并得到清洁高效的查询表。

执行并检查:

# Execute the function to build the database.
db_path = load_real_mimic_data()

# If the database was created successfully, connect to it and inspect the schema and some sample data.
if db_path:
    print(f"\nReal MIMIC-III database created at: {db_path}")
    print("\nTesting database connection and schema...")
    con = duckdb.connect(db_path)
    print(f"Tables in DB: {con.execute('SHOW TABLES').df()['name'].tolist()}")
    print("\nSample of 'patients' table:")
    print(con.execute("SELECT * FROM patients LIMIT 5").df())
    print("\nSample of 'diagnoses_icd' table:")
    print(con.execute("SELECT * FROM diagnoses_icd LIMIT 5").df())
    con.close()

示例输出略,显示三张表均已创建成功,可查询。

Pre-processing Step (Created by Fareed Khan)

最后,将所有非结构化文本数据索引为可检索的向量库,以便 RAG 使用:

from langchain_community.document_loaders import DirectoryLoader, TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_core.documents import Document

defcreate_vector_store(folder_path: str, embedding_model, store_name: str):
    """Loads all .txt files from a folder, splits them into chunks, and creates an in-memory FAISS vector store."""
    print(f"--- Creating {store_name} Vector Store ---")
    # Use DirectoryLoader to efficiently load all .txt files from the specified folder.
    loader = DirectoryLoader(folder_path, glob="**/*.txt", loader_cls=TextLoader, show_progress=True)
    documents = loader.load()
    
    ifnot documents:
        print(f"No documents found in {folder_path}, skipping vector store creation.")
        returnNone
    
    # Use RecursiveCharacterTextSplitter to break large documents into smaller, 1000-character chunks with a 100-character overlap.
    # The overlap helps maintain context between chunks.
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
    texts = text_splitter.split_documents(documents)
    
    print(f"Loaded {len(documents)} documents, split into {len(texts)} chunks.")
    print("Generating embeddings and indexing into FAISS... (This may take a moment)")
    # FAISS.from_documents is a convenient function that handles both embedding the text chunks
    # and building the efficient FAISS index in one step.
    db = FAISS.from_documents(texts, embedding_model)
    print(f"{store_name} Vector Store created successfully.")
    return db

defcreate_retrievers(embedding_model):
    """Creates vector store retrievers for all unstructured data sources and consolidates all knowledge stores."""
    # Create a separate, specialized vector store for each type of document.
    pubmed_db = create_vector_store(data_paths["pubmed"], embedding_model, "PubMed")
    fda_db = create_vector_store(data_paths["fda"], embedding_model, "FDA")
    ethics_db = create_vector_store(data_paths["ethics"], embedding_model, "Ethics")
    
    # Return a single dictionary containing all configured data access tools.
    # The 'as_retriever' method converts the vector store into a standard LangChain Retriever object.
    # The 'k' parameter in 'search_kwargs' controls how many top documents are returned by a search.
    return {
        "pubmed_retriever": pubmed_db.as_retriever(search_kwargs={"k": 3}) if pubmed_db elseNone,
        "fda_retriever": fda_db.as_retriever(search_kwargs={"k": 3}) if fda_db elseNone,
        "ethics_retriever": ethics_db.as_retriever(search_kwargs={"k": 2}) if ethics_db elseNone,
        "mimic_db_path": db_path # We also include the file path to our structured DuckDB database.
    }

create_vector_store 封装了“load -> split -> embed -> index”的标准 RAG 构建流程;create_retrievers 则为每类语料构建独立向量库并返回 retriever 字典。我们采用“分域向量库”而非“大一统”,以便各代理只检索各自相关的知识源(例如 Regulatory Specialist 仅使用 fda_retriever)。

执行创建:

# Execute the function to create all our retrievers.
knowledge_stores = create_retrievers(llm_config["embedding_model"])

print("\nKnowledge stores and retrievers created successfully.")

# Print the final dictionary to confirm all components are present.
for name, store in knowledge_stores.items():
    print(f"{name}: {store}")

输出显示各 retriever 创建成功。

至此,数据(下载、处理、索引)与 LLM(配置)均已就绪,可以开始构建系统的第一大组件:Trial Design Guild(试验设计工会)。

构建内部临床试验设计网络

随着知识库就绪,现在构建系统核心。这不是一个简单线性的 RAG chain,而是一套基于 LangGraph 的协作式多代理工作流:一支 AI 专家团队,共同将高层试验概念转化为一份详细、数据支撑的标准化标准文档。

Main Inner Loop RAG (Created by Fareed Khan)

整个架构的行为不是硬编码的,而由一个动态配置对象治理:标准作业程序(Standard Operating Procedure,GuildSOP)。

这个 SOP 是我们 RAG 流水线的“基因组(genome)”,也是外层的“AI Research Director”将要进化与优化的对象。

本节计划:

  • 定义 RAG 基因组:创建 Pydantic 模型 GuildSOP,用于驱动整个工作流架构。
  • 设计共享工作台:定义 GuildState,作为代理共享计划与发现的中央空间。
  • 构建专家型代理:将 Planner、Researchers、SQL Analyst、Synthesizer 分别实现为 Python 函数,作为图中的节点。
  • 编排协作:用 LangGraph 将这些 agent 节点接线成完整端到端工作流。
  • 全量测试:用 baseline SOP 调用完整的 Guild graph,观察其实际运行并生成首版标准文档。

定义公会标准操作规程

先定义控制整体流程行为的结构。我们用 Pydantic BaseModel 创建 GuildSOP。通过强类型、校验、自文档化,让 SOP 稳定可进化。

Guild SOP Design (Created by Fareed Khan)

from pydantic import BaseModel, Field
from typing importLiteral

classGuildSOP(BaseModel):
    """Standard Operating Procedures for the Trial Design Guild. This object acts as the dynamic configuration for the entire RAG workflow."""
    
    # This field holds the system prompt for the Planner Agent, dictating its strategy.
    planner_prompt: str = Field(description="The system prompt for the Planner Agent.")
    
    # This parameter controls how many documents the Medical Researcher retrieves, allowing us to tune the breadth of its search.
    researcher_retriever_k: int = Field(description="Number of documents for the Medical Researcher to retrieve.", default=3)
    
    # This is the system prompt for the final writer, the Synthesizer Agent.
    synthesizer_prompt: str = Field(description="The system prompt for the Criteria Synthesizer Agent.")
    
    # This allows us to dynamically change the model used for the final drafting stage, trading off speed vs. quality.
    synthesizer_model: Literal["qwen2:7b", "llama3.1:8b-instruct"] = Field(description="The LLM to use for the Synthesizer.", default="qwen2:7b")
    
    # These booleans act as "feature flags," allowing the Director to turn entire agent capabilities on or off.
    use_sql_analyst: bool = Field(description="Whether to use the Patient Cohort Analyst agent.", default=True)
    use_ethics_specialist: bool = Field(description="Whether to use the Ethics Specialist agent.", default=True)

GuildSOP 公开了关键参数(如 prompts、researcher_retriever_k、以及 agent 开关),使外层 AI Director 能够拉动这些“策略杠杆”,进而调优整体性能。synthesizer_model 使用 Literal 限定取值集合,保证类型安全。

构建 baseline 版本:

import json

baseline_sop = GuildSOP(
    planner_prompt="""You are a master planner for clinical trial design...""",
    synthesizer_prompt="""You are an expert medical writer...""",
    researcher_retriever_k=3,
    synthesizer_model="qwen2:7b",
    use_sql_analyst=True,
    use_ethics_specialist=True
)

打印:

print("Baseline GuildSOP (v1.0):")
print(json.dumps(baseline_sop.dict(), indent=4))

输出显示 baseline SOP 的全部配置,作为初始“手工工程”的最佳猜测,供 AI Director 后续优化与超越。

定义专业智能体(Specialist Agents)

有了“规则书”(SOP),接下来定义 agents。在 LangGraph 中,agent 是一个节点(Python 函数),输入为当前图状态,输出为状态增量。

Specialist Agents (Created by Fareed Khan)

先定义共享状态 GuildState,充当协作“工作台”,保存初始请求、planner 生成的计划、各专家的发现、以及最终输出。

from typing importList, Dict, Any, Optional
from langchain_core.pydantic_v1 import BaseModel
from typing_extensions import TypedDict

classAgentOutput(BaseModel):
    """A structured output for each agent's findings."""
    agent_name: str
    findings: Any

classGuildState(TypedDict):
    """The state of the Trial Design Guild's workflow, passed between all nodes."""
    initial_request: str
    plan: Optional[Dict[str, Any]]
    agent_outputs: List[AgentOutput]
    final_criteria: Optional[str]
    sop: GuildSOP

接着实现 planner_agent,它读取 SOP 中的 planner_prompt 并产出结构化计划(JSON)指导后续 agents:

def planner_agent(state: GuildState) -> GuildState:
    """Receives the initial request and creates a structured plan for the specialist agents."""
    print("--- EXECUTING PLANNER AGENT ---")

    sop = state['sop']

    planner_llm = ll-config['planner'].with_structured_output(schema={"plan": []})
    
    prompt = f"{sop.planner_prompt}\n\nTrial Concept: '{state['initial_request']}'"
    print(f"Planner Prompt:\n{prompt}")
    
    response = planner_llm.invoke(prompt)
    print(f"Generated Plan:\n{json.dumps(response, indent=2)}")
    
    return {**state, "plan": response}

然后实现通用的“检索型代理”函数 retrieval_agent,供 Medical Researcher、Regulatory Specialist、Ethics Specialist 复用:

def retrieval_agent(task_description: str, state: GuildState, retriever_name: str, agent_name: str) -> AgentOutput:
    """A generic agent function that performs retrieval from a specified vector store based on a task description."""
    print(f"--- EXECUTING {agent_name.upper()} ---")
    print(f"Task: {task_description}")
    
    retriever = knowledge_stores[retriever_name]
    
    if agent_name == "Medical Researcher":
        retriever.search_kwargs['k'] = state['sop'].researcher_retriever_k
        print(f"Using k={state['sop'].researcher_retriever_k} for retrieval.")

    retrieved_docs = retriever.invoke(task_description)
    
    findings = "\n\n---\n\n".join([f"Source: {doc.metadata.get('source', 'N/A')}\n\n{doc.page_content}"for doc in retrieved_docs])
    print(f"Retrieved {len(retrieved_docs)} documents.")
    print(f"Sample Finding:\n{findings[:500]}...")
    
    return AgentOutput(agent_name=agent_name, findings=findings)

Patient Cohort Analyst 是最复杂的代理:Text-to-SQL,将自然语言转为有效 SQL 并在 DuckDB 上执行,给出可招募人群估算:

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

defpatient_cohort_analyst(task_description: str, state: GuildState) -> AgentOutput:
    """Estimates cohort size by generating and then executing a SQL query against the MIMIC database."""
    print("--- EXECUTING PATIENT COHORT ANALYST ---")
    
    ifnot state['sop'].use_sql_analyst:
        print("SQL Analyst skipped as per SOP.")
        return AgentOutput(agent_name="Patient Cohort Analyst", findings="Analysis skipped as per SOP.")
    
    con = duckdb.connect(knowledge_stores['mimic_db_path'])
    schema_query = """
    SELECT table_name, column_name, data_type 
    FROM information_schema.columns 
    WHERE table_schema = 'main' ORDER BY table_name, column_name;
    """
    schema = con.execute(schema_query).df()
    con.close()
    
    sql_generation_prompt = ChatPromptTemplate.from_messages([
        ("system", f"You are an expert SQL writer specializing in DuckDB. ... schema:\n{schema.to_string()}\n\nIMPORTANT: All column names ...\n\nKey Mappings:\n- T2DM ... ICD9_CODE '25000'.\n- Moderate renal impairment ... creatinine ... ITEMID 50912 ... VALUENUM 1.5-3.0.\n- Uncontrolled T2D ... HbA1c ... ITEMID 50852 ... VALUENUM > 8.0."),
        ("human", "Please write a SQL query to count the number of unique patients who meet the following criteria: {task}")
    ])
    
    sql_chain = sql_generation_prompt | llm_config['sql_coder'] | StrOutputParser()
    
    print(f"Generating SQL for task: {task_description}")
    sql_query = sql_chain.invoke({"task": task_description})
    sql_query = sql_query.strip().replace("```sql", "").replace("```", "")
    print(f"Generated SQL Query:\n{sql_query}")
    try:
        con = duckdb.connect(knowledge_stores['mimic_db_path'])
        result = con.execute(sql_query).fetchone()
        patient_count = result[0] if result else0
        con.close()
        
        findings = f"Generated SQL Query:\n{sql_query}\n\nEstimated eligible patient count from the database: {patient_count}."
        print(f"Query executed successfully. Estimated patient count: {patient_count}")
    except Exception as e:
        findings = f"Error executing SQL query: {e}. Defaulting to a count of 0."
        print(f"Error during query execution: {e}")
    return AgentOutput(agent_name="Patient Cohort Analyst", findings=findings)

最后是 criteria_synthesizer,将各专家发现汇织为正式的“入排标准(Inclusion/Exclusion Criteria)”文档。支持在 SOP 中动态切换 synthesizer_model:

def criteria_synthesizer(state: GuildState) -> GuildState:
    """Synthesizes all the structured findings from the specialist agents into the final criteria document."""
    print("--- EXECUTING CRITERIA SYNTHESIZER ---")
    
    sop = state['sop']
    drafter_llm = ChatOllama(model=sop.synthesizer_model, temperature=0.2)

    context = "\n\n---\n\n".join([f"**{out.agent_name} Findings:**\n{out.findings}"for out in state['agent_outputs']])
    
    prompt = f"{sop.synthesizer_prompt}\n\n**Context from Specialist Teams:**\n{context}"
    print(f"Synthesizer is using model '{sop.synthesizer_model}'.")
    
    response = drafter_llm.invoke(prompt)
    print("Final criteria generated.")
    
    return {**state, "final_criteria": response.content}

使用 LangGraph 编排

将以上 agent 节点用 LangGraph 编排:Planner → 专家并行执行 → Synthesizer。

Guild with langgraph (Created by Fareed Khan)

定义“调度节点”,根据 plan 分派任务:

from langgraph.graph import StateGraph, END

defspecialist_execution_node(state: GuildState) -> GuildState:
    """This node acts as a dispatcher, executing all specialist tasks defined in the plan."""
    plan_tasks = state['plan']['plan']
    outputs = []
    
    for task in plan_tasks:
        agent_name = task['agent']
        task_desc = task['task_description']
        
        if"Regulatory"in agent_name:
            output = retrieval_agent(task_desc, state, "fda_retriever", "Regulatory Specialist")
        elif"Medical"in agent_name:
            output = retrieval_agent(task_desc, state, "pubmed_retriever", "Medical Researcher")
        elif"Ethics"in agent_name and state['sop'].use_ethics_specialist:
            output = retrieval_agent(task_desc, state, "ethics_retriever", "Ethics Specialist")
        elif"Cohort"in agent_name:
            output = patient_cohort_analyst(task_desc, state)
        else:
            continue
        
        outputs.append(output)
    return {**state, "agent_outputs": outputs}

构建与编译 graph:

workflow = StateGraph(GuildState)

workflow.add_node("planner", planner_agent)
workflow.add_node("execute_specialists", specialist_execution_node)
workflow.add_node("synthesizer", criteria_synthesizer)

workflow.set_entry_point("planner")
workflow.add_edge("planner", "execute_specialists")
workflow.add_edge("execute_specialists", "synthesizer")
workflow.add_edge("synthesizer", END)

guild_graph = workflow.compile()
print("Graph compiled successfully.")

可选图形化略。至此,“Inner Loop” 多代理 RAG 管线搭建完毕。

完整运行公会工作流图

用 baseline SOP 和真实试验概念进行端到端测试,验证 agents、数据存储与编排逻辑是否协作正常,并产出我们的首个“baseline”输出,供后续评估与进化环路使用。

Run Workflow (Created by Fareed Khan)

test_request = "Draft inclusion/exclusion criteria for a Phase II trial of 'Sotagliflozin', a novel SGLT2 inhibitor, for adults with uncontrolled Type 2 Diabetes (HbA1c > 8.0%) and moderate chronic kidney disease (CKD Stage 3)."

print("Running the full Guild graph with baseline SOP v1.0...")
graph_input = {
    "initial_request": test_request,
    "sop": baseline_sop
}
final_result = guild_graph.invoke(graph_input)
print("\nFinal Guild Output:")
print("---------------------")
print(final_result['final_criteria'])

输出日志显示每个 agent 的执行过程,并最终得到结构良好的入排标准文档。至此,我们已构建并测试了一套基于真实数据源的多代理 RAG 流水线。

多维度评价体系

一个能自我改进的系统,必须能够衡量自己的表现。我们需要的不只是单一分数(如 accuracy),而是多维度质量评估。我们将构建一个多维评估套件,对 Guild 输出在我们最初就确定的“五大支柱”上进行评分。这将为“外层进化环路”提供丰富、可操作的反馈信号。

Multi-dimension Eval (Created by Fareed Khan)

本节计划:

  • LLM-as-a-Judge:用 llama3:70b 构建三个“专家评委”,分别评 Scientific Rigor、Regulatory Compliance、Ethical Soundness。
  • 程序化评估:用两段快速、可靠、客观的程序化函数,评 Recruitment Feasibility 与 Operational Simplicity。
  • 汇总评估器:将五个单项评估封装为一个总评函数,接收 Guild 输出并生成 5D 性能向量,供 AI Director 决策使用。

为每个参数构建自定义评估器

首先定义 LLM 评委的统一输出结构:

from langchain_core.pydantic_v1 import BaseModel, Field

class GradedScore(BaseModel):
    """A Pydantic model to structure the output of our LLM-as-a-Judge evaluators."""
    score: float = Field(description="A score from 0.0 to 1.0")
    reasoning: str = Field(description="A brief justification for the score.")

1. Scientific Rigor:

from langchain_core.prompts import ChatPromptTemplate

def scientific_rigor_evaluator(generated_criteria: str, pubmed_context: str) -> GradedScore:
    evaluator_llm = llm_config['director'].with_structured_output(GradedScore)
    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are an expert clinical scientist. ..."),
        ("human", "Evaluate the following criteria:\n\n**Generated Criteria:**\n{criteria}\n\n**Supporting Scientific Context:**\n{context}")
    ])
    chain = prompt | evaluator_llm
    return chain.invoke({"criteria": generated_criteria, "context": pubmed_context})

2. Regulatory Compliance:

def regulatory_compliance_evaluator(generated_criteria: str, fda_context: str) -> GradedScore:
    evaluator_llm = llm_config['director'].with_structured_output(GradedScore)
    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are an expert regulatory affairs specialist. ..."),
        ("human", "Evaluate the following criteria:\n\n**Generated Criteria:**\n{criteria}\n\n**Applicable FDA Guidelines:**\n{context}")
    ])
    chain = prompt | evaluator_llm
    return chain.invoke({"criteria": generated_criteria, "context": fda_context})

3. Ethical Soundness:

def ethical_soundness_evaluator(generated_criteria: str, ethics_context: str) -> GradedScore:
    evaluator_llm = llm_config['director'].with_structured_output(GradedScore)
    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are an expert on clinical trial ethics. ..."),
        ("human", "Evaluate the following criteria:\n\n**Generated Criteria:**\n{criteria}\n\n**Ethical Principles:**\n{context}")
    ])
    chain = prompt | evaluator_llm
    return chain.invoke({"criteria": generated_criteria, "context": ethics_context})

4. Recruitment Feasibility(程序化):

def feasibility_evaluator(cohort_analyst_output: AgentOutput) -> GradedScore:
    findings_text = cohort_analyst_output.findings
    try:
        count_str = findings_text.split("database: ")[1].replace('.', '')
        patient_count = int(count_str)
    except (IndexError, ValueError):
        return GradedScore(score=0.0, reasoning="Could not parse patient count from analyst output.")
    
    IDEAL_COUNT = 150.0
    score = min(1.0, patient_count / IDEAL_COUNT)
    reasoning = f"Estimated {patient_count} eligible patients. Score is normalized against an ideal target of {int(IDEAL_COUNT)}."
    return GradedScore(score=score, reasoning=reasoning)

5. Operational Simplicity(程序化):

def simplicity_evaluator(generated_criteria: str) -> GradedScore:
    EXPENSIVE_TESTS = ["mri", "genetic sequencing", "pet scan", "biopsy", "echocardiogram", "endoscopy"]
    test_count = sum(1 for test in EXPENSIVE_TESTS if test in generated_criteria.lower())
    score = max(0.0, 1.0 - (test_count * 0.5))
    reasoning = f"Found {test_count} expensive/complex screening procedures mentioned."
    return GradedScore(score=score, reasoning=reasoning)

创建聚合型 LangSmith 评估器

定义总评结果模型与汇总函数:

class EvaluationResult(BaseModel):
    rigor: GradedScore
    compliance: GradedScore
    ethics: GradedScore
    feasibility: GradedScore
    simplicity: GradedScore
def run_full_evaluation(guild_final_state: GuildState) -> EvaluationResult:
    """Orchestrates the entire evaluation process, calling each of the five specialist evaluators."""
    print("--- RUNNING FULL EVALUATION GAUNTLET ---")
    
    final_criteria = guild_final_state['final_criteria']
    agent_outputs = guild_final_state['agent_outputs']
    
    pubmed_context = next((o.findings for o in agent_outputs if o.agent_name == "Medical Researcher"), "")
    fda_context = next((o.findings for o in agent_outputs if o.agent_name == "Regulatory Specialist"), "")
    ethics_context = next((o.findings for o in agent_outputs if o.agent_name == "Ethics Specialist"), "")
    analyst_output = next((o for o in agent_outputs if o.agent_name == "Patient Cohort Analyst"), None)
    
    print("Evaluating: Scientific Rigor...")
    rigor = scientific_rigor_evaluator(final_criteria, pubmed_context)
    print("Evaluating: Regulatory Compliance...")
    compliance = regulatory_compliance_evaluator(final_criteria, fda_context)
    print("Evaluating: Ethical Soundness...")
    ethics = ethical_soundness_evaluator(final_criteria, ethics_context)
    print("Evaluating: Recruitment Feasibility...")
    feasibility = feasibility_evaluator(analyst_output) if analyst_output else GradedScore(score=0, reasoning="Analyst did not run.")
    print("Evaluating: Operational Simplicity...")
    simplicity = simplicity_evaluator(final_criteria)
    
    print("--- EVALUATION GAUNTLET COMPLETE ---")
    return EvaluationResult(rigor=rigor, compliance=compliance, ethics=ethics, feasibility=feasibility, simplicity=simplicity)

对 baseline 输出运行评估,示例结果显示在“Feasibility”维度明显偏低(0.39),这为外层 AI Director 指出了明确改进方向。

进化引擎的外层循环

现在构建系统的“大脑”——“AI Research Director”(外层进化回路)。其职责不是设计试验,而是改进“设计试验”的过程:分析 5D 评分、诊断根因、智能改写 GuildSOP。这是系统学习与自适应的核心。

Outer Loop (Created by Fareed Khan)

本节计划:

  • 创建“基因池(gene pool)”:管理 SOP 演化版本及其评分,形成可追溯的“基因史”。
  • 设计 Director 级别代理:Performance Diagnostician 识别弱点;SOP Architect 提出改良方案。
  • 架构进化循环:定义完整一代的进化过程:Diagnose → Evolve → Evaluate。
  • 运行一次全流程:展示系统如何自主发现“可行性”弱点并产生新的 SOP 变体修复它。

管理配置

定义 SOPGenePool,存储 SOP、评分与“父版本”信息:

class SOPGenePool:
    def__init__(self):
        self.pool: List[Dict[str, Any]] = []
        self.version_counter = 0

    defadd(self, sop: GuildSOP, eval_result: EvaluationResult, parent_version: Optional[int] = None):
        self.version_counter += 1
        entry = {
            "version": self.version_counter,
            "sop": sop,
            "evaluation": eval_result,
            "parent": parent_version
        }
        self.pool.append(entry)
        print(f"Added SOP v{self.version_counter} to the gene pool.")
        
    defget_latest_entry(self) -> Optional[Dict[str, Any]]:
        returnself.pool[-1] ifself.pool elseNone

构建主任级智能体(Director-Level Agents)

先是 Performance Diagnostician,分析 5D 向量并给出结构化诊断:

class Diagnosis(BaseModel):
    primary_weakness: Literal['rigor', 'compliance', 'ethics', 'feasibility', 'simplicity']
    root_cause_analysis: str = Field(...)
    recommendation: str = Field(...)

defperformance_diagnostician(eval_result: EvaluationResult) -> Diagnosis:
    print("--- EXECUTING PERFORMANCE DIAGNOSTICIAN ---")
    diagnostician_llm = llm_config['director'].with_structured_output(Diagnosis)
    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are a world-class management consultant ..."),
        ("human", "Please analyze the following performance evaluation report:\n\n{report}")
    ])
    chain = prompt | diagnostician_llm
    return chain.invoke({"report": eval_result.json()})

再是 SOP Architect,根据诊断与当前 SOP 生成多个“变体” SOP 作为候选:

class EvolvedSOPs(BaseModel):
    mutations: List[GuildSOP]

def sop_architect(diagnosis: Diagnosis, current_sop: GuildSOP) -> EvolvedSOPs:
    print("--- EXECUTING SOP ARCHITECT ---")
    architect_llm = llm_config['director'].with_structured_output(EvolvedSOPs)
    prompt = ChatPromptTemplate.from_messages([
        ("system", f"You are an AI process architect. ... schema: {GuildSOP.schema_json()} ..."),
        ("human", "Here is the current SOP:\n{current_sop}\n\nHere is the performance diagnosis:\n{diagnosis}\n\nBased on the diagnosis, please generate 2-3 new, improved SOPs.")
    ])
    chain = prompt | architect_llm
    return chain.invoke({"current_sop": current_sop.json(), "diagnosis": diagnosis.json()})

运行完整的进化循环

封装一次完整的进化循环:

def run_evolution_cycle(gene_pool: SOPGenePool, trial_request: str):
    print("\n" + "="*25 + " STARTING NEW EVOLUTION CYCLE " + "="*25)
    
    current_best_entry = gene_pool.get_latest_entry()
    parent_sop = current_best_entry['sop']
    parent_eval = current_best_entry['evaluation']
    parent_version = current_best_entry['version']
    print(f"Improving upon SOP v{parent_version}...")
    
    diagnosis = performance_diagnostician(parent_eval)
    print(f"Diagnosis complete. Primary Weakness: '{diagnosis.primary_weakness}'. Recommendation: {diagnosis.recommendation}")

    new_sop_candidates = sop_architect(diagnosis, parent_sop)
    print(f"Generated {len(new_sop_candidates.mutations)} new SOP candidates.")
    for i, candidate_sop inenumerate(new_sop_candidates.mutations):
        print(f"\n--- Testing SOP candidate {i+1}/{len(new_sop_candidates.mutations)} ---")
        guild_input = {"initial_request": trial_request, "sop": candidate_sop}
        final_state = guild_graph.invoke(guild_input)
        
        eval_result = run_full_evaluation(final_state)
        gene_pool.add(sop=candidate_sop, eval_result=eval_result, parent_version=parent_version)
    print("\n" + "="*25 + " EVOLUTION CYCLE COMPLETE " + "="*26)

初始化基因池、加入 baseline、运行一轮进化。示例输出显示:诊断识别“Feasibility”为主要弱项;Architect 生成两个候选 SOP;测试后某个候选(v2)显著提升 Feasibility(例如 0.81),且仅以轻微 Rigor 代价换取巨大实际可行性收益;另一个候选(v3)则未带来改进。

基于五维的帕累托分析

进化循环完成一代。现在需要对结果进行多目标优化分析。在多目标问题中往往不存在单一“最好”解,而是存在“帕累托前沿(Pareto Frontier)”。目标是识别这一前沿并呈现给人类决策者。

本节计划:

  • 分析基因池:打印所有 SOP 及其 5D 评分的摘要,以观察变体的直接影响。
  • 识别 Pareto Front:编写函数程序化识别基因池中的非支配解(non-dominated solutions)。
  • 可视化前沿:用并行坐标图(parallel coordinates plot)展示 5D 维度的权衡,让 trade-off 一目了然。

打印摘要略。然后识别 Pareto 前沿:

import numpy as np

defidentify_pareto_front(gene_pool: SOPGenePool) -> List[Dict[str, Any]]:
    pareto_front = []
    pool_entries = gene_pool.pool
    
    for i, candidate inenumerate(pool_entries):
        is_dominated = False
        cand_scores = np.array([s['score'] for s in candidate['evaluation'].dict().values()])
        
        for j, other inenumerate(pool_entries):
            if i == j: continue
            other_scores = np.array([s['score'] for s in other['evaluation'].dict().values()])
            if np.all(other_scores >= cand_scores) and np.any(other_scores > cand_scores):
                is_dominated = True
                break
        ifnot is_dominated:
            pareto_front.append(candidate)
    return pareto_front

运行后通常得到 v1 与 v2 组成帕累托前沿:v1 为“最大化 Rigor”的策略;v2 为“高 Feasibility”的策略。在实际决策中,如何取舍取决于业务优先级。

识别帕累托前沿

使用 2D 散点图(Rigor vs. Feasibility)与 5D 并行坐标图可视化:

import matplotlib.pyplot as plt
import pandas as pd

defvisualize_frontier(pareto_sops):
    ifnot pareto_sops:
        print("No SOPs on the Pareto front to visualize.")
        return
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 7))
    
    labels = [f"v{s['version']}"for s in pareto_sops]
    rigor_scores = [s['evaluation'].rigor.score for s in pareto_sops]
    feasibility_scores = [s['evaluation'].feasibility.score for s in pareto_sops]
    
    ax1.scatter(rigor_scores, feasibility_scores, s=200, alpha=0.7, c='blue')
    for i, txt inenumerate(labels):
        ax1.annotate(txt, (rigor_scores[i], feasibility_scores[i]), xytext=(10,-10), textcoords='offset points', fontsize=14)
    ax1.set_title('Pareto Frontier: Rigor vs. Feasibility', fontsize=16)
    ax1.set_xlabel('Scientific Rigor Score', fontsize=14)
    ax1.set_ylabel('Recruitment Feasibility Score', fontsize=14)
    ax1.grid(True, linestyle='--', alpha=0.6)
    ax1.set_xlim(min(rigor_scores)-0.05, max(rigor_scores)+0.05)
    ax1.set_ylim(min(feasibility_scores)-0.1, max(feasibility_scores)+0.1)

    data = []
    for s in pareto_sops:
        eval_dict = s['evaluation'].dict()
        scores = {k.capitalize(): v['score'] for k, v in eval_dict.items()}
        scores['SOP Version'] = f"v{s['version']}"
        data.append(scores)
    
    df = pd.DataFrame(data)
    pd.plotting.parallel_coordinates(df, 'SOP Version', colormap=plt.get_cmap("viridis"), ax=ax2, axvlines_kwargs={"linewidth": 1, "color": "grey"})
    ax2.set_title('5D Performance Trade-offs on Pareto Front', fontsize=16)
    ax2.grid(True, which='major', axis='y', linestyle='--', alpha=0.6)
    ax2.set_ylabel('Normalized Score', fontsize=14)
    ax2.legend(loc='lower center', bbox_to_anchor=(0.5, -0.15), ncol=len(labels))
    plt.tight_layout()
    plt.show()

渲染结果直观展示 v1 与 v2 在各维的差异:两者在 Compliance、Ethics、Simplicity 上几乎一致,只在 Rigor 与 Feasibility 上形成明显权衡(典型“交叉”形态)。

可视化前沿并做出决策

我们已经从宏观层面(进化、帕累托前沿)看到了系统如何自我改进。现在从微观层面理解一次“高表现”运行的内部过程:agents 如何协作?瓶颈在哪里?多维得分如何转化为可视化剖面?

Understand the Workflow (Created by Fareed Khan)

计划:

  • 对工作流加仪表(instrumentation):精确记录每个 agent 的开始/结束/耗时。
  • 可视化执行时间线:用甘特图(Gantt chart)呈现工作流,显示并行与串行阶段。
  • 用雷达图(Radar Chart)对比 baseline 与 evolved SOP 的 5D 表现剖面。

理解认知工作流

使用 graph 的 .stream() 方法逐节点获取事件,记录时间戳:

import time
from collections import defaultdict


definvoke_with_timing(graph, sop, request):
    """Invokes the Guild graph while capturing start and end times for each node."""
    print(f"--- Instrumenting Graph Run for SOP: {sop.dict()} ---")
    
    timing_data = []
    start_times = defaultdict(float)
    
    graph_input = {"initial_request": request, "sop": sop}
    
    for event in graph.stream(graph_input, stream_mode="values"):
        node_name = list(event.keys())[0]
        end_time = time.time()
        
        if node_name notin start_times:
            start_times[node_name] = end_time - 0.1
        
        start_time = end_time - duration
        timing_data.append({
            "node": node_name,
            "start_time": start_time,
            "end_time": end_time,
            "duration": duration
        })
        start_times[node_name] = start_time
    overall_start_time = min(d['start_time'] for d in timing_data)
    for data in timing_data:
        data['start_time'] -= overall_start_time
        data['end_time'] -= overall_start_time
        
    final_state = event[list(event.keys())[-1]]
    return final_state, timing_data

对 v2 执行并捕获时序数据(示例输出显示 execute_specialists 是主要耗时阶段,符合预期)。

绘制甘特图:

import matplotlib.pyplot as plt

def plot_gantt_chart(timing_data: List[Dict[str, Any]], title: str):
    """Plots a Gantt chart of the agentic workflow from timing data."""
    fig, ax = plt.subplots(figsize=(12, 4))
    
    labels = [d['node'] for d in timing_data]
    ax.barh(labels, [d['duration'] for d in timing_data], left=[d['start_time'] for d in timing_data], color='skyblue')
    
    ax.set_xlabel('Time (seconds)')
    ax.set_title(title, fontsize=16)
    ax.grid(True, which='major', axis='x', linestyle='--', alpha=0.6)
    ax.invert_yaxis()
    plt.show()

甘特图清晰展示了串行的顶层流程与内部并行机会,提示性能优化应聚焦 execute_specialists 阶段。

使用雷达图剖析输出结果

用雷达图对比 baseline v1 与 evolved v2 的 5D 剖面:

import pandas as pd


defplot_radar_chart(eval_results: List[Dict[str, Any]], labels: List[str]):
    """Creates a radar chart to compare the 5D performance of multiple SOPs."""
    
    categories = ['Rigor', 'Compliance', 'Ethics', 'Feasibility', 'Simplicity']
    num_vars = len(categories)
    angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()
    angles += angles[:1]
    fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True))
    for i, result inenumerate(eval_results):
        values = [res.score for res in result.dict().values()]
        values += values[:1]
        ax.plot(angles, values, linewidth=2, linestyle='solid', label=labels[i])
        ax.fill(angles, values, alpha=0.25)

    ax.set_yticklabels([])
    ax.set_xticks(angles[:-1])
    ax.set_xticklabels(categories, fontsize=12)
    ax.set_title('5D Performance Profile Comparison', size=20, color='blue', y=1.1)
    plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))
    plt.show()

图中可见两者在 Compliance、Ethics、Simplicity 上都很强;v1 在 Rigor 略优,而 v2 在 Feasibility 显著优越,清晰呈现 trade-off。

自主策略

我们已设计、构建并演示了一套可自我改进的 agentic 系统。这不仅是一个解决方案,更是一套可扩展的基础架构:分层代理设计、动态 SOP、多维评估、自动进化。这些原则打开了广阔的未来空间:

  1. 持续运行进化循环:当前完成一代,未来可连续迭代数百代,以发现更丰富、更多样的 Pareto Frontier(经过实战检验的 SOP)。
  2. 将 Director 的推理蒸馏为更小的策略模型:基于成功变体的历史进行训练,用更快、更便宜的专用模型替换 70B Director,使进化更高效。
  3. 让 AI Director 动态改变 Guild 的结构:根据试验概念的需求,学习增删专家(如新增“Biostatistician”),实现团队层面的进化。
  4. 用实时 API 替换静态 MIMIC-III:将 Patient Cohort Analyst 连接到安全的实时 EHR 系统,使可行性评估基于最新患者数据。
  5. 强化 SOP Architect 的进化操作符:引入“crossover”等机制,融合不同成功 SOP 的优势,加速新策略发现。
  6. 融合人类专家反馈:将临床科学家的评分接入评估回路,用专家判断作为最终“奖励信号”,引导系统趋向“技术最优 + 实践卓越”的方案。

如何学习大模型 AI ?

由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。

但是具体到个人,只能说是:

“最先掌握AI的人,将会比较晚掌握AI的人有竞争优势”。

这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。

这份完整版的大模型 AI 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】

https://img-blog.csdnimg.cn/img_convert/05840567e2912bcdcdda7b15cba33d93.jpeg

在这里插入图片描述

为什么要学习大模型?

我国在A大模型领域面临人才短缺,数量与质量均落后于发达国家。2023年,人才缺口已超百万,凸显培养不足。随着AI技术飞速发展,预计到2025年,这一缺口将急剧扩大至400万,严重制约我国AI产业的创新步伐。加强人才培养,优化教育体系,国际合作并进是破解困局、推动AI发展的关键。

在这里插入图片描述

在这里插入图片描述

大模型入门到实战全套学习大礼包

1、大模型系统化学习路线

作为学习AI大模型技术的新手,方向至关重要。 正确的学习路线可以为你节省时间,少走弯路;方向不对,努力白费。这里我给大家准备了一份最科学最系统的学习成长路线图和学习规划,带你从零基础入门到精通!

img


2、大模型学习书籍&文档

学习AI大模型离不开书籍文档,我精选了一系列大模型技术的书籍和学习文档(电子版),它们由领域内的顶尖专家撰写,内容全面、深入、详尽,为你学习大模型提供坚实的理论基础。

在这里插入图片描述

3、AI大模型最新行业报告

2025最新行业报告,针对不同行业的现状、趋势、问题、机会等进行系统地调研和评估,以了解哪些行业更适合引入大模型的技术和应用,以及在哪些方面可以发挥大模型的优势。

img

4、大模型项目实战&配套源码

学以致用,在项目实战中检验和巩固你所学到的知识,同时为你找工作就业和职业发展打下坚实的基础。

img

5、大模型大厂面试真题

面试不仅是技术的较量,更需要充分的准备。在你已经掌握了大模型技术之后,就需要开始准备面试,我精心整理了一份大模型面试题库,涵盖当前面试中可能遇到的各种技术问题,让你在面试中游刃有余。

img

适用人群

在这里插入图片描述

第一阶段(10天):初阶应用

该阶段让大家对大模型 AI有一个最前沿的认识,对大模型 AI 的理解超过 95% 的人,可以在相关讨论时发表高级、不跟风、又接地气的见解,别人只会和 AI 聊天,而你能调教 AI,并能用代码将大模型和业务衔接。

  • 大模型 AI 能干什么?
  • 大模型是怎样获得「智能」的?
  • 用好 AI 的核心心法
  • 大模型应用业务架构
  • 大模型应用技术架构
  • 代码示例:向 GPT-3.5 灌入新知识
  • 提示工程的意义和核心思想
  • Prompt 典型构成
  • 指令调优方法论
  • 思维链和思维树
  • Prompt 攻击和防范
  • …
第二阶段(30天):高阶应用

该阶段我们正式进入大模型 AI 进阶实战学习,学会构造私有知识库,扩展 AI 的能力。快速开发一个完整的基于 agent 对话机器人。掌握功能最强的大模型开发框架,抓住最新的技术进展,适合 Python 和 JavaScript 程序员。

  • 为什么要做 RAG
  • 搭建一个简单的 ChatPDF
  • 检索的基础概念
  • 什么是向量表示(Embeddings)
  • 向量数据库与向量检索
  • 基于向量检索的 RAG
  • 搭建 RAG 系统的扩展知识
  • 混合检索与 RAG-Fusion 简介
  • 向量模型本地部署
  • …
第三阶段(30天):模型训练

恭喜你,如果学到这里,你基本可以找到一份大模型 AI相关的工作,自己也能训练 GPT 了!通过微调,训练自己的垂直大模型,能独立训练开源多模态大模型,掌握更多技术方案。

到此为止,大概2个月的时间。你已经成为了一名“AI小子”。那么你还想往下探索吗?

  • 为什么要做 RAG
  • 什么是模型
  • 什么是模型训练
  • 求解器 & 损失函数简介
  • 小实验2:手写一个简单的神经网络并训练它
  • 什么是训练/预训练/微调/轻量化微调
  • Transformer结构简介
  • 轻量化微调
  • 实验数据集的构建
  • …
第四阶段(20天):商业闭环

对全球大模型从性能、吞吐量、成本等方面有一定的认知,可以在云端和本地等多种环境下部署大模型,找到适合自己的项目/创业方向,做一名被 AI 武装的产品经理。

  • 硬件选型
  • 带你了解全球大模型
  • 使用国产大模型服务
  • 搭建 OpenAI 代理
  • 热身:基于阿里云 PAI 部署 Stable Diffusion
  • 在本地计算机运行大模型
  • 大模型的私有化部署
  • 基于 vLLM 部署大模型
  • 案例:如何优雅地在阿里云私有部署开源大模型
  • 部署一套开源 LLM 项目
  • 内容安全
  • 互联网信息服务算法备案
  • …

学习是一个过程,只要学习就会有挑战。天道酬勤,你越努力,就会成为越优秀的自己。

如果你能在15天内完成所有的任务,那你堪称天才。然而,如果你能完成 60-70% 的内容,你就已经开始具备成为一名大模型 AI 的正确特征了。

这份完整版的大模型 AI 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】

https://img-blog.csdnimg.cn/img_convert/05840567e2912bcdcdda7b15cba33d93.jpeg

深入分析传统RAG与Agentic RAG 文章摘要: RAG技术通过连接LLM与外部知识库解决知识滞后与内容幻觉问题。传统RAG采用线性“检索-生成”流程,适合简单问答但无法处理多跳推理;Agentic RAG引入智能体决策,通过查询优化、工具选择和循环评估应对复杂任务,但开发成本更高。两者并非替代关系:传统RAG适合低延迟简单场景(如客服),Agentic RAG擅长度身定制复杂分析(如行业报告)。未来趋势可能是动态切换两种模式,根据任务复杂度平衡效率与能力。选择时需权衡响应速度、开发成本与任务复杂度。 阅读详情

相关推荐

kubernetes rook 安装 cephfs

ceph root kubernete osd uuid partuuid

天津托的博客 1548

【限时免费】 complex-RAG-guide:构建生产级RAG系统的完整指南

complex-RAG-guide:构建生产级RAG系统的完整指南 项目介绍 complex-RAG-guide是一个开源的RAG(检索增强生成)系统构建指南,专注于解决实际生产环境中面临的复杂挑战。该项目由Fareed Khan基于nirDiamant的早期工作扩展而来,通过结合LangChain、LangGraph和RAGAS等技术栈,提供了一套从数据准备到最终评估的完整解决方案。 项目技术分...

gitblog_00853的博客 409

从DBC到ARXML:详解DaVinci Configurator中通信栈的自动化配置逻辑

本文深入解析了Vector公司DaVinci Configurator工具如何将DBC文件自动转换为符合AUTOSAR标准的ARXML配置,详细介绍了从DBC到ARXML的映射逻辑、自动化配置的边界与陷阱,以及工程实践中的优化策略。帮助工程师高效配置汽车电子系统中的通信协议,提升项目开发效率。

weixin_30279671的博客 722

构建一套可自我改进的 Agentic RAG 系统,大模型入门到精通,收藏这篇就足够了!

Agentic RAG 系统可以被视为一个“高维向量空间”,其中每个维度都对应一次设计决策,例如 prompt engineering、agent 协同、retrieval 策略等。

2301_81888214的博客 908

用VINS-Fusion跑通EuRoC数据集:Ubuntu22.04+ROS2环境下的保姆级评测指南

本文详细介绍了在Ubuntu22.04和ROS2 Humble环境下使用VINS-Fusion处理EuRoC数据集的完整流程。从环境配置、数据集转换到参数调优和性能评估,提供了一套全面的多传感器融合分析方案,帮助开发者在无人机精准定位场景中实现高效部署与优化。

weixin_29212867的博客 523

高分六号GF-6 WFV数据处理全流程:从原始数据解压到经纬度投影转换

本文详细解析了高分六号GF-6 WFV遥感数据的完整处理流程。从原始数据解压与分块结构理解入手,指导如何安装ENVI国产卫星支持工具进行自动拼接,并重点阐述了利用RPC模型进行正射校正以消除几何畸变,以及将UTM投影转换为地理经纬度坐标的关键步骤。文章旨在帮助用户高效地将原始卫星数据转化为可直接用于农业监测、生态环境分析等领域的标准地理空间图像。

weixin_29047919的博客 200

什么是 Agentic RAG?如何构建多 Agent Agentic RAG 系统,大模型入门到精通,收藏这篇就足够了!

本文将探讨 Agentic RAG 的优势以及如何使用 Phidata 和 LangChain 实现 Agentic RAG。

2301_81940605的博客 993

一文搞懂多速率信号处理中信号插值的本质:从插 0、插原值到线性插值!

信号插值在数字信号处理中经常被使用,但“插值”背后究竟发生了什么,却常被忽略。插0、插原值、线性插值看似只是不同的实现方式,实则对应着完全不同的频域效应与滤波特性。本文将结合公式与MATLAB仿真,深入剖析插0、插原值与线性插值三种典型策略的本质区别。

m0_66360845的博客 930

Agentic RAG 实战:用 LangGraph 构建可自我修正的 RAG 系统

标准 RAG 把检索当黑盒,查询丢进去、文档出来,至于相不相关全凭运气。Agentic RAG 打开这个黑盒在关键位置加了质量控制。LangGraph 加 Redis 的组合提供了一个可以直接上生产的骨架。流程编排的复杂度 LangGraph 消化掉了,向量检索的性能 Redis 兜住了,剩下的评分和重写逻辑负责兜底那些简单系统搞不定的边角案例。只要你真心想学习AI大模型技术,这份精心整理的学习资料我愿意无偿分享给你,但是想学技术去乱搞的人别来找我!

2401_85325726的博客 1070

【OAG vs RAG】RAG的“语义崩溃“:为什么你的知识库越大,AI越笨?_语义检索oag-CSDN博客

19.9 元(AI 编程 / Agent 实战 | 本文同主题系统课程)·49.9 元(AI 时代成长方法论)。单篇不过瘾?订阅解锁全量源码、实战与答疑;文末附资料包领取方式 ↓图1:RAG语义崩溃概念图。

78

LSTM在交通流量预测中的应用:优化城市交通管理

我们使用的数据集来自某个城市的交通监测系统,包含多个监测点在不同时间段内的交通流量记录。每个监测点的数据包括时间戳、交通流量、天气状况和道路状态等信息。

斌擎科技 1262

从零开始构建Agentic RAG:结合RAG与AI Agent的大模型新范式实战指南!

本文详细介绍了Agentic RAG这一结合RAG与AI Agent的新范式。首先分别阐述了RAG的检索增强生成原理和AI Agent的感知决策机制,然后通过LangChain和LangGraph框架展示了从文档处理到向量存储,再到智能问答系统的完整实现流程。最后探讨了Agentic RAG在实际应用中面临的挑战,如触发机制优化和幻觉问题,为开发者提供了构建大模型应用的技术路径和思考方向。

2401_85379281的博客 1035

【WRF数据准备】基于Python更新geo_em.d0.nc文件中Albedo/LAI等静态地理数据

基于Python更新geo_em.d0.nc文件中Albedo/LAI等静态地理数据

WW、forever的博客 592

【必学收藏】Agentic RAG实战:基于LangGraph和Qwen构建智能自适应RAG系统

在系统中,状态管理是整个流程的基础,它决定了信息在图结构中的流动方式,也是系统能实现动态自适应决策的核心环节。import os"""表示图中每个节点的状态。属性:question: 用户输入的问题generation: LLM生成的回答web_search: 是否需要进行网络搜索documents: 存放本地或网络检索到的文档列表fallback: 是否由LLM直接生成"""在开始编码前,我们引用了相关的依赖库。然后,我们使用TypedDict来定义图中每个节点的状态。

ytt0523_com的博客 1177

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

收藏必备!从零开始构建智能Agentic RAG系统:LangGraph+Qwen实战指南

在系统中,状态管理是整个流程的基础,它决定了信息在图结构中的流动方式,也是系统能实现动态自适应决策的核心环节。import os表示图中每个节点的状态。属性:question: 用户输入的问题generation: LLM生成的回答web_search: 是否需要进行网络搜索documents: 存放本地或网络检索到的文档列表fallback: 是否由LLM直接生成 "" "在开始编码前,我们引用了相关的依赖库。然后,我们使用TypedDict来定义图中每个节点的状态。

youmaob的博客 975

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

【收藏学习】基于MCP架构的Agentic RAG系统实现:大模型应用开发实战

本文详解了基于MCP架构从零构建Agentic RAG系统的方法。服务端使用LlamaIndex实现RAG管道,客户端用LangGraph构建Agent,支持多种查询功能并采用缓存优化。展示了MCP架构在模块化、技术灵活性和资源共享方面的优势,为开发企业级大模型应用提供参考。

大模型教程的博客 2068

收藏必学 | Agentic RAG实战:从零构建智能检索增强生成系统,提升大模型应用质量

本文详细介绍了Agentic RAG(检索增强生成与Agent结合)技术框架,通过一个基于《个人信息保护法》的实践项目,展示了查询重写、多路召回、质量评估等关键技术。该系统通过智能控制输入问题与检索策略,显著增强查询鲁棒性与准确性,为企业落地RAG系统提供了可行的优化思路和实用参考。

CSDN_224022的博客 1618

收藏!小白程序员必看:从RAG到Agentic RAG,轻松入门大模型进阶玩法

本文介绍了RAG技术如何通过检索资料降低AI幻觉问题,并引出升级版本Agentic RAG。传统RAG通过“先查资料再回答”的模式提升AI可靠性,但存在只检索一次的局限。Agentic RAG则引入智能体(Agent)概念,能理解、拆解任务并多次检索,更接近真正的AI助手。文章对比了两者在动态决策、检索次数、任务拆解等方面的差异,指出Agentic RAG是RAG的进化形态,代表了AI从简单问答向复杂任务执行的转变趋势。

2401_85375186的博客 1393

收藏级指南|传统RAG与Agentic RAG深度解析,小白程序员入门大模型必看

传统RAG作为RAG技术的“基石版本”,凭借简洁高效、低成本落地的特性,在简单问答、固定知识库查询、低延迟需求等场景(如产品说明书问答、企业内部文档检索、小白Demo开发)中仍具有不可替代的价值,是初级程序员入门RAG技术的首选路径。Agentic RAG则代表了RAG技术的“进阶方向”,通过赋予系统“智能体思维”,突破了传统RAG的能力边界,更适合复杂决策、跨数据源整合、高准确性要求的高阶场景(如金融市场实时分析、科研文献综述、企业战略规划)。

大模型教程的博客 1257

【必看收藏】Agentic RAG:让RAG系统拥有自主决策能力的大模型技术

Agentic RAG融合了我们之前介绍的大量基础的RAG技巧。它的出现不仅仅技术演进,更深刻地触及了人工智能、信息科学乃至认知科学等多个交叉学科(Agent的工作模式更是人类社会工作模式的映射。Agentic RAG现在已被大多数厂商采用,如OpenAI,Gemini的Deep Research,甚至于Manus,等通用Agent也可看作是Agentic RAG。

weixin_72959097的博客 1109

大模型RAG实战:RAG原理、应用与系统构建

大模型爆火后的RAG系统发展,大体可以将其分为3个阶段,初级、高级、超级。初级阶段更多的是搭建起系统的pipeline;高级阶段是在召回生成测修修补补,根据badcase反推流程上的优化技巧;超级对应了从Agentic RAG、RAG不存在了、多模态RAG、结构化RAG、GraphRAG、MemoryRAG等技术飞速发展的阶段。

2301_82275412的博客 1513

【值得收藏】大模型RAG技术全栈指南:从Native RAG到Agentic RAG实战

让 LLM 作为“智能体(Agent)”充当控制器,结合一组工具(检索、查看元数据、读取片段等)执行“思考→行动→观察”的循环(Reason–Act–Observe)。在回答之前,按需多轮调用工具,逐步从“找到相关文件”走到“读取关键片段”,最后基于被读取的证据组织答案,并给出引用。好处:更强的适应性(可改写查询/追加搜索)、更深的证据利用(读到再答)、更可审计(引用具体来源)。方法决策机制搜索能力适应性实现复杂度传统 RAG固定流程单次检索低低。

CSDN_430422的博客 764

大模型RAG技术演进:Agentic RAG vs 传统RAG全面对比与实战指南,建议收藏!

RAG (Retrieval-Augmented Generation) 技术通过结合信息检索和文本生成来提升大语言模型的回答质量。随着技术发展,从传统的静态RAG演进到了具备智能决策能力的Agentic RAG。传统RAG的执行逻辑Agentic RAG的执行逻辑Agentic RAG代表了RAG技术的重要进步,通过引入智能代理的概念,大大提升了系统的推理能力和灵活性。虽然在计算成本和复杂性方面有所增加,但在准确性、可解释性和处理复杂查询方面具有显著优势。

kaka0722ww的博客 1308

实战指南:从零构建 MCP 架构下的 Agentic RAG 系统,无第三方MCP Server

RAG是一种借助外部知识来给LLM提供上下文的AI应用范式。从这个角度来说,RAG与MCP有着相似的意义:给大模型补充上下文,以增强其能力。只是MCP以提供外部工具为主,而RAG则是以注入参考知识为主。这就像一个考试的学生,MCP给你提供计算器,而RAG则是给你一本书。 当然,两者的重点并不一样,

qq_46094651的博客 1107

必收藏!Agentic RAG从入门到架构吃透,小白&程序员必学的大模型核心技术

结合前面的内容,大家应该能猜到——Agentic RAG,本质就是「传统RAG与AI智能体的深度融合」。我们已经知道,传统RAG的最大短板是“没有自主性”,只能按固定流程走;而AI智能体的核心优势就是“自主性”,能自主规划、动态调整。于是,开发者们就想到:把AI智能体引入传统RAG的工作流程中,既保留传统RAG“精准检索外部数据、减少幻觉”的优点,又借助AI智能体的自主性,解决传统RAG的灵活性不足、检索能力有限等问题。

CSDN_224022的博客 1748

收藏备用!一文搞懂RAG与Agentic RAG:大模型进阶必备知识

RAG(检索增强生成)是提升生成式AI模型性能的核心框架,核心逻辑是通过实时检索外部知识源,为AI补充“新鲜且精准”的信息,从而解决大模型“知识滞后、易 hallucinate(产生幻觉)”的问题,让生成内容更靠谱、更丰富。而AI Agent(智能体)则是具备自主感知、逻辑推理、执行动作与持续学习能力的软件系统,能独立应对复杂场景下的任务。当RAG与AI Agent相结合,就能打造出功能更全面、适配性更强的AI系统。

EnjoyEDU的博客 1087
上一篇: 2025大模型技术全景:GPT、Claude、Gemini、文心一言等主流模型深度对比与选择(建议收藏)
下一篇: 干货收藏!10个精选AI大模型应用架构设计问题及解决方案全解析,助你轻松应对技术挑战
冻感糕人~
博客等级 码龄3年 8927粉丝 2442原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址