本文介绍了一个自我改进的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、多维评估、自动进化。这些原则打开了广阔的未来空间:
- 持续运行进化循环:当前完成一代,未来可连续迭代数百代,以发现更丰富、更多样的 Pareto Frontier(经过实战检验的 SOP)。
- 将 Director 的推理蒸馏为更小的策略模型:基于成功变体的历史进行训练,用更快、更便宜的专用模型替换 70B Director,使进化更高效。
- 让 AI Director 动态改变 Guild 的结构:根据试验概念的需求,学习增删专家(如新增“Biostatistician”),实现团队层面的进化。
- 用实时 API 替换静态 MIMIC-III:将
Patient Cohort Analyst连接到安全的实时 EHR 系统,使可行性评估基于最新患者数据。 - 强化
SOP Architect的进化操作符:引入“crossover”等机制,融合不同成功 SOP 的优势,加速新策略发现。 - 融合人类专家反馈:将临床科学家的评分接入评估回路,用专家判断作为最终“奖励信号”,引导系统趋向“技术最优 + 实践卓越”的方案。
如何学习大模型 AI ?
由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。
但是具体到个人,只能说是:
“最先掌握AI的人,将会比较晚掌握AI的人有竞争优势”。
这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。
我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。
我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。
这份完整版的大模型 AI 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】


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


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

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

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

4、大模型项目实战&配套源码
学以致用,在项目实战中检验和巩固你所学到的知识,同时为你找工作就业和职业发展打下坚实的基础。

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

适用人群

第一阶段(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%免费】


1548



被折叠的 条评论
为什么被折叠?



