使用Pydantic构建结构化研究自动化系统

使用Pydantic构建结构化研究自动化系统

在快节奏的学术研究领域,高效地收集、综合和展示信息至关重要。手动查找和总结文献可能会非常乏味,从而分散研究人员对深入分析和发现的注意力。这就是使用 Pydantic 的多代理研究助理系统的用武之地–在这个智能架构中,专业代理通过模块化和可扩展性协作处理复杂的任务。然而,管理多个代理会带来数据一致性、验证和结构化通信方面的挑战。使用 Pydantic 的多代理研究助理系统通过执行清晰的数据模式、确保稳健处理和降低系统复杂性提供了一种解决方案。

在本文中,我们将介绍如何使用 Pydantic 构建结构化的多代理研究助理,并集成 Pydantic-ai 和 arxiv 等工具,同时提供分步代码说明和预期成果。

  • 了解结构化数据建模在使用 Pydantic 的多代理研究助理系统中的作用,以确保智能代理之间可靠、一致的通信。
  • 使用 Pydantic 多代理研究助理系统定义和实施清晰的结构化数据模式,以实现无缝集成、模块化代理协调和高效的自动化研究工作流。
  • 设计和协调模块化代理,每个代理负责特定任务,如查询细化、数据检索、关键词提取和总结。
  • 利用结构化的代理交互,将外部应用程序接口(如 arXiv)无缝集成到自动工作流中。
  • 直接从结构化代理输出生成专业质量的输出(如 PDF 报告),显著提高自动化研究工作流的实际可用性。

用Pydantic定义清晰的数据模型

在多代理系统中,定义明确的结构化数据模型是基础。当多个智能代理交互时,每个代理都依赖于接收和发送定义明确、可预测的数据。如果没有结构化的模式,即使是微小的不一致也会导致整个系统出错,而这是众所周知的调试难点。

利用 Pydantic,我们可以优雅地应对这一挑战。Pydantic 为在 Python 中定义数据模式提供了一种简单而强大的方法。它能确保数据的一致性,大大减少潜在的运行时错误,并促进在代理工作流的每一步进行无缝验证。

下面是一个使用 Pydantic 定义结构化数据模型的实用示例,我们的代理将使用该模型进行清晰的通信:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from pydantic import BaseModel, Field
class PaperMetadata(BaseModel):
title: str = Field(..., description="Title of the paper")
abstract: str = Field(..., description="Abstract of the paper")
authors: list[str] = Field(..., description="List of authors")
publication_date: str = Field(..., description="Publication date")
from pydantic import BaseModel, Field class PaperMetadata(BaseModel): title: str = Field(..., description="Title of the paper") abstract: str = Field(..., description="Abstract of the paper") authors: list[str] = Field(..., description="List of authors") publication_date: str = Field(..., description="Publication date")
from pydantic import BaseModel, Field
class PaperMetadata(BaseModel):
title: str = Field(..., description="Title of the paper")
abstract: str = Field(..., description="Abstract of the paper")
authors: list[str] = Field(..., description="List of authors")
publication_date: str = Field(..., description="Publication date")

每个字段的说明

  • title:检索到的研究论文的标题。它对于各种代理的快速参考、组织和显示至关重要。
  • abstract:包含论文作者提供的简明摘要或摘要。该摘要对关键词提取和摘要代理至关重要。
  • authors: 列出论文的作者。该元数据有助于进一步查询、特定作者分析或引文跟踪。
  • publication_date:代表论文发表或提交的日期。这对于排序、筛选和确保研究的最新性非常重要。

我们的多代理系统中的每个代理都依赖于这些结构化字段。让我们简要介绍一下我们将围绕这个数据模型建立的代理。在我们的系统中,我们将设计五个专门的代理:

  • 提示处理器代理
  • 论文检索代理
  • 关键词提取代理
  • 总结代理
  • 路由器(协调器)代理

每个代理都根据我们使用 Pydantic 定义的模型精确传递数据结构,从而实现无缝通信。这种清晰的结构确保了每个代理的输入和输出都是可预测和经过验证的,从而大大减少了运行时的错误,增强了系统的稳健性。

使用 Pydantic 定义的模型精确传递数据结构

接下来,我们将深入研究每个代理,清楚地解释它们的实现、作用和预期输出。

构建多代理框架

有了使用 Pydantic 定义的清晰且经过验证的数据模型,我们现在开始设计多代理框架的结构。我们框架中的每个代理都有专门的职责,并与其他代理无缝互动,共同完成复杂的任务。

在我们的系统中,我们定义了五个专门的代理,每个代理都有明确而独特的职责:

提示处理器代理

提示处理器代理是工作流程的第一步。它的主要职责是接收用户的原始输入或查询(如 “强化学习中的人工智能代理”),并将其细化为更精确、结构化的搜索查询。这种细化可大大提高外部研究数据库返回结果的相关性。

职责

  • 接收用户的初始查询。
  • 生成精炼的结构化搜索查询,以实现最大相关性。

论文检索代理

论文检索代理接收来自提示处理器的细化查询。它直接与外部学术数据库(如 arXiv)通信,根据细化查询检索相关学术论文列表。

责任:

  • 与外部 API(如 arXiv API)交互。
  • 检索结构化的论文列表,每篇论文都使用 PaperMetadata 模型来表示。

关键词提取代理

收到论文摘要后,关键词提取代理会自动识别并提取最相关的关键词。这些关键词有助于研究人员快速评估每篇论文的重点和相关性。

职责

  • 从摘要中提取有意义的关键词。
  • 帮助对论文进行快速评估和分类。

摘要代理

摘要代理可提取每篇论文的摘要,并生成简明、翔实的摘要。摘要为研究人员提供快速见解,节省大量阅读时间和精力。

职责

  • 根据论文摘要生成简洁明了的摘要。
  • 更快地评估论文内容的相关性。

路由器代理(协调器)

路由器代理是我们多代理系统的核心。它负责协调整个工作流程,管理所有其他代理之间的通信和数据流。它启动提示处理器,将完善的查询传递给论文检索代理,并进一步将论文摘要传递给关键词提取和摘要代理。最后,路由器将所有结果编译成结构化的最终报告。

职责

  • 协调所有代理之间的交互和数据流。
  • 管理代理工作流程的异步协调。
  • 将输出结果(关键字、摘要、论文元数据)汇总到结构化最终报告中。

代理互动简述

我们的代理以清晰、有序的工作流程进行交互:

  • 提示处理器代理接收并改进用户查询。
  • 改进后的查询被发送到论文检索代理,检索相关论文。
  • 对于检索到的每篇论文,路由器代理都会同时向其发送摘要:
  • 一旦生成了关键词和摘要,路由器代理就会将其编译并汇总到最终的结构化报告中。

通过这种代理结构,我们实现了一个模块化、可维护和高度可扩展的研究助理系统。每个代理都可以单独进行增强、调试,甚至替换,而不会影响整个系统的稳定性。接下来,我们将深入探讨每个代理的实际实现细节,以及清晰解释的代码片段和预期输出。

使用提示处理器代理完善研究查询

在搜索庞大的学术数据库(如 arXiv)时,查询的质量和具体性会直接影响返回结果的相关性和实用性。像“人工智能代理”这样模糊或宽泛的查询可能会产生成千上万篇松散的相关论文,使研究人员难以识别真正有价值的内容。因此,将初始查询细化为精确、结构化的搜索语句至关重要。

提示处理器代理正是为了应对这一挑战。它的主要职责是将用户的一般研究主题转化为更具体、范围更明确的查询。这种改进大大提高了检索论文的质量和精确度,为研究人员节省了大量精力。

下面,我们将介绍“提示处理器”的实现过程,利用基本的启发式方法来创建结构化查询:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@prompt_processor_agent.tool
async def process_prompt(ctx: RunContext[ResearchContext], topic: str) -> str:
topic = topic.strip().lower()
# Basic heuristic refinement
if ' in ' in topic:
# Split the topic into key parts if it contains 'in', to form precise queries.
subtopics = topic.split(' in ')
main_topic = subtopics[0].strip()
context = subtopics[1].strip()
refined_query = f"all:{main_topic} AND cat:{context.replace(' ', '_')}"
else:
# Fallback: Assume it's a broader topic
refined_query = f"ti:\"{topic}\" OR abs:\"{topic}\""
return refined_query
@prompt_processor_agent.tool async def process_prompt(ctx: RunContext[ResearchContext], topic: str) -> str: topic = topic.strip().lower() # Basic heuristic refinement if ' in ' in topic: # Split the topic into key parts if it contains 'in', to form precise queries. subtopics = topic.split(' in ') main_topic = subtopics[0].strip() context = subtopics[1].strip() refined_query = f"all:{main_topic} AND cat:{context.replace(' ', '_')}" else: # Fallback: Assume it's a broader topic refined_query = f"ti:\"{topic}\" OR abs:\"{topic}\"" return refined_query
@prompt_processor_agent.tool
async def process_prompt(ctx: RunContext[ResearchContext], topic: str) -> str:
topic = topic.strip().lower()
# Basic heuristic refinement
if ' in ' in topic:
# Split the topic into key parts if it contains 'in', to form precise queries.
subtopics = topic.split(' in ')
main_topic = subtopics[0].strip()
context = subtopics[1].strip()
refined_query = f"all:{main_topic} AND cat:{context.replace(' ', '_')}"
else:
# Fallback: Assume it's a broader topic
refined_query = f"ti:\"{topic}\" OR abs:\"{topic}\""
return refined_query

改进实施的说明

  • 输入规范化:代理首先对输入主题进行修剪并转换为小写,以确保一致性。
  • 上下文解析:如果用户的主题包含关键词“in * ”(例如,“AI agents in reinforcement learning”),代理就会将其分成两个清晰的部分:
    • 一级主题(人工智能代理)
    • 特定的上下文或子领域(强化学习)
  • 结构化查询构建:使用这些解析的组件,代理生成一个精确的查询,明确搜索所有领域的主要主题(all:),并将搜索限制在与指定上下文分类或密切相关的论文上。
  • 回退处理:如果主题没有明确包含上下文线索,代理会生成一个结构化查询,直接在标题(ti:)和摘要(abs:)字段内进行搜索,从而提高一般搜索的相关性。

预期输出示例

当用户提供以下查询时:“AI agents in reinforcement learning”

提示处理器代理会将精炼后的查询输出为:all:ai agents AND cat:reinforcement_learning

对于更宽泛的查询,例如“multi-agent systems”

代理的精炼查询将是:ti:”multi-agent systems” OR abs:”multi-agent systems

虽然这种实现方式已经大大提高了搜索的具体性,但仍有进一步提高的空间,其中包括

  • 自然语言处理(NLP)技术,以更好地理解语义。
  • 纳入同义词和相关术语,智能扩展查询。
  • 利用大型语言模型(LLM) 来解释用户意图并形成高度优化的查询。

这些精炼的查询结构可优化搜索相关性,并检索到极具针对性的学术论文。

利用论文检索代理高效检索研究论文

完善搜索查询以实现最大相关性后,下一步就是检索合适的学术论文。论文检索代理正是发挥了这一作用:它可以查询外部学术数据库(如 arXiv),根据我们的精炼查询来收集相关的研究论文。

通过与外部应用程序接口(如 arXiv 的应用程序接口)无缝集成,论文检索代理自动完成了在海量学术文献中搜索和筛选的繁琐人工任务。它使用结构化数据模型(早先使用 Pydantic 定义),确保数据流一致、干净、有效,并流向下游的其他代理,如摘要器和关键词提取器。

以下是论文检索代理实施的一个实例:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@paper_retrieval_agent.tool
async def fetch_papers(ctx: RunContext[ResearchContext]) -> list[PaperMetadata]:
search = arxiv.Search(
query=ctx.deps.query,
max_results=5,
sort_by=arxiv.SortCriterion.SubmittedDate
)
results = list(search.results())
papers = []
for result in results:
published_str = (
result.published.strftime("%Y-%m-%d")
if hasattr(result, "published") and result.published is not None
else "Unknown"
)
paper = PaperMetadata(
title=result.title,
abstract=result.summary,
authors=[author.name for author in result.authors],
publication_date=published_str
)
papers.append(paper)
return papers
@paper_retrieval_agent.tool async def fetch_papers(ctx: RunContext[ResearchContext]) -> list[PaperMetadata]: search = arxiv.Search( query=ctx.deps.query, max_results=5, sort_by=arxiv.SortCriterion.SubmittedDate ) results = list(search.results()) papers = [] for result in results: published_str = ( result.published.strftime("%Y-%m-%d") if hasattr(result, "published") and result.published is not None else "Unknown" ) paper = PaperMetadata( title=result.title, abstract=result.summary, authors=[author.name for author in result.authors], publication_date=published_str ) papers.append(paper) return papers
@paper_retrieval_agent.tool
async def fetch_papers(ctx: RunContext[ResearchContext]) -> list[PaperMetadata]:
search = arxiv.Search(
query=ctx.deps.query,
max_results=5,
sort_by=arxiv.SortCriterion.SubmittedDate
)
results = list(search.results())
papers = []
for result in results:
published_str = (
result.published.strftime("%Y-%m-%d")
if hasattr(result, "published") and result.published is not None
else "Unknown"
)
paper = PaperMetadata(
title=result.title,
abstract=result.summary,
authors=[author.name for author in result.authors],
publication_date=published_str
)
papers.append(paper)
return papers

实施说明

  • 该代理使用从 Prompt Processor 代理接收的精炼查询 (ctx.deps.query) 通过 arXiv API 发起搜索。
  • 它指定 max_results=5 来检索与查询相关的五篇最新论文,并按论文提交日期排序。
  • 从 arXiv 检索到的每个结果都使用我们之前定义的 Pydantic 模型明确地结构化为一个 PaperMetadata 对象。这种结构化方法可确保验证和数据一致性。
  • 结构化数据被收集到一个列表中并返回,供下游代理使用。

突出 Pydantic 的作用

使用 Pydantic 模型对来自外部 API 的响应进行结构化处理可带来显著的优势:

  • 数据验证:确保始终提供所有必填字段(标题、摘要、作者、出版日期)且格式正确。
  • 一致性:保证下游代理接收统一结构的数据,简化处理逻辑。
  • 调试和维护:结构化模式可大大减少错误,提高可维护性并简化调试。

预期输出示例

使用细化查询(如“all:ai agents AND cat:reinforcement_learning”)执行检索代理后,您会得到类似的结构化输出:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[
{
"title": "Deep Reinforcement Learning with Agentic Systems",
"abstract": "This paper discusses advancements in agentic reinforcement
learning...",
"authors": ["Alice Smith", "John Doe"],
"publication_date": "2025-03-20"
},
{
"title": "Agent Coordination in Reinforcement Learning Environments",
"abstract": "We explore methods for improving multi-agent coordination...",
"authors": ["Jane Miller", "Bob Johnson"],
"publication_date": "2025-03-18"
}
// (three additional similar structured results)
]
[ { "title": "Deep Reinforcement Learning with Agentic Systems", "abstract": "This paper discusses advancements in agentic reinforcement learning...", "authors": ["Alice Smith", "John Doe"], "publication_date": "2025-03-20" }, { "title": "Agent Coordination in Reinforcement Learning Environments", "abstract": "We explore methods for improving multi-agent coordination...", "authors": ["Jane Miller", "Bob Johnson"], "publication_date": "2025-03-18" } // (three additional similar structured results) ]
[
{
"title": "Deep Reinforcement Learning with Agentic Systems",
"abstract": "This paper discusses advancements in agentic reinforcement 
learning...",
"authors": ["Alice Smith", "John Doe"],
"publication_date": "2025-03-20"
},
{
"title": "Agent Coordination in Reinforcement Learning Environments",
"abstract": "We explore methods for improving multi-agent coordination...",
"authors": ["Jane Miller", "Bob Johnson"],
"publication_date": "2025-03-18"
}
// (three additional similar structured results)
]

这种结构化输出有助于后续代理进行进一步的自动分析,从而实现高效的关键词提取和总结。

使用关键词提取代理提取有价值的关键词

检索到相关论文后,对其内容进行有效分类和总结至关重要。研究人员通常需要快速识别大量文献中的核心概念和关键观点,而无需详细阅读每篇摘要。

这就是关键词提取发挥关键作用的地方。从摘要中自动提取关键词有助于研究人员快速确定每篇论文的重点,并更有效地识别新兴趋势或与群体相关的研究。

关键词提取代理明确针对这一需求。给定一篇论文的摘要,它就能识别出代表摘要内容的一组基本术语。

代码片段(关键词提取代理):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@keyword_extraction_agent.tool
async def extract_keywords(ctx: RunContext[ResearchContext], abstract: str)
-> KeywordResult:
# Basic keyword extraction logic (placeholder implementation)
words = abstract.split()
seen = set()
unique_words = []
for word in words:
normalized = word.strip('.,;:"()').lower()
if normalized and normalized not in seen:
seen.add(normalized)
unique_words.append(normalized)
if len(unique_words) >= 5:
break
return KeywordResult(keywords=unique_words)
@keyword_extraction_agent.tool async def extract_keywords(ctx: RunContext[ResearchContext], abstract: str) -> KeywordResult: # Basic keyword extraction logic (placeholder implementation) words = abstract.split() seen = set() unique_words = [] for word in words: normalized = word.strip('.,;:"()').lower() if normalized and normalized not in seen: seen.add(normalized) unique_words.append(normalized) if len(unique_words) >= 5: break return KeywordResult(keywords=unique_words)
@keyword_extraction_agent.tool
async def extract_keywords(ctx: RunContext[ResearchContext], abstract: str) 
-> KeywordResult:
# Basic keyword extraction logic (placeholder implementation)
words = abstract.split()
seen = set()
unique_words = []
for word in words:
normalized = word.strip('.,;:"()').lower()
if normalized and normalized not in seen:
seen.add(normalized)
unique_words.append(normalized)
if len(unique_words) >= 5:
break
return KeywordResult(keywords=unique_words)

实施说明

  • 代理将论文摘要作为输入。
  • 它将摘要文本拆分成单个单词,进行规范化处理以去除标点符号,并将其转换为小写字母。
  • 然后,它收集前五个唯一的单词作为关键词。这是一个简化的实现,目的是清楚地演示关键词提取。
  • 最后,它会返回一个包含这些提取关键词的结构化 KeywordResult。

突出 Pydantic 的优势

通过使用 Pydantic 明确定义的模式 (KeywordResult),关键词输出保持了结构化和一致性,使下游代理(如汇总或协调代理)可以轻松地消费这些数据,而不会产生歧义。

预期输出示例

给定一个摘要样本:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"This paper discusses advancements in agentic reinforcement learning,
focusing on deep learning techniques for enhancing agent cooperation."
"This paper discusses advancements in agentic reinforcement learning, focusing on deep learning techniques for enhancing agent cooperation."
"This paper discusses advancements in agentic reinforcement learning, 
focusing on deep learning techniques for enhancing agent cooperation."

关键词提取代理会产生类似的输出结果:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
["this", "paper", "discusses", "advancements"]
["this", "paper", "discusses", "advancements"]
["this", "paper", "discusses", "advancements"]

注:这种简单的提取逻辑是演示基本关键字提取的占位符。实际生产实施通常会采用更先进的自然语言处理 (NLP) 技术(如 TF-IDF、RAKE 或基于语言模型的提取)来生成相关性更高的关键词。

使用摘要代理简明扼要地总结论文

在学术研究环境中,时间效率至关重要。研究人员经常要面对数量庞大的论文和摘要。自动摘要可以快速扫描和识别最相关的研究,而无需通读整篇摘要或论文。

摘要代理可直接应对这一挑战。它能从论文摘要中生成简洁而有意义的摘要,使研究人员能够快速确定每篇论文的相关性,并决定是否需要进行更深入的研究。

代码片段(摘要代理)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@summary_agent.tool
async def summarize_paper(ctx: RunContext[ResearchContext], abstract: str)
-> PaperSummary:
summary_text = abstract[:150] + "..." if len(abstract) > 150 else abstract
return PaperSummary(summary=summary_text)
@summary_agent.tool async def summarize_paper(ctx: RunContext[ResearchContext], abstract: str) -> PaperSummary: summary_text = abstract[:150] + "..." if len(abstract) > 150 else abstract return PaperSummary(summary=summary_text)
@summary_agent.tool
async def summarize_paper(ctx: RunContext[ResearchContext], abstract: str) 
-> PaperSummary:
summary_text = abstract[:150] + "..." if len(abstract) > 150 else abstract
return PaperSummary(summary=summary_text)

实施说明

  • 代理接受论文摘要作为输入。
  • 它从摘要中提取前 150 个字符生成简短摘要,如果摘要超过此长度,则附加“…”。
  • 然后,摘要将作为结构化的 PaperSummary 对象返回,以确保格式的一致性,并方便进一步的自动化或报告任务。

这种简单的摘要方法可快速概括每篇论文的内容。虽然简单明了,但它对初步评估非常有效,能让研究人员快速筛选多篇摘要。

预期输出示例(仅文本)

给出摘要:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"This paper discusses advancements in agentic reinforcement learning,
focusing on deep learning techniques for enhancing agent cooperation in
multi-agent environments. We propose novel algorithms and evaluate their
effectiveness through extensive simulations."
"This paper discusses advancements in agentic reinforcement learning, focusing on deep learning techniques for enhancing agent cooperation in multi-agent environments. We propose novel algorithms and evaluate their effectiveness through extensive simulations."
"This paper discusses advancements in agentic reinforcement learning, 
focusing on deep learning techniques for enhancing agent cooperation in 
multi-agent environments. We propose novel algorithms and evaluate their 
effectiveness through extensive simulations."

总结代理将产生:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"This paper discusses advancements in agentic reinforcement learning,
focusing on deep learning techniques for enhancing agent cooperation in
multi-age..."
"This paper discusses advancements in agentic reinforcement learning, focusing on deep learning techniques for enhancing agent cooperation in multi-age..."
"This paper discusses advancements in agentic reinforcement learning, 
focusing on deep learning techniques for enhancing agent cooperation in 
multi-age..."

高级摘要技术的潜力

虽然我们的实施方案具有直接价值,但整合高级摘要模型–如基于转换器的语言模型(如 GPT 模型、T5 或 BART)–可显著提高摘要质量、连贯性和上下文准确性。

利用先进的摘要技术可以产生信息量更大、上下文更精确的摘要,从而进一步提高研究人员评估论文的效率和准确性。

现在,我们可以进入系统的最后一个核心部分: 路由器代理(协调器)。

将这一切结合在一起:代理协调

多代理系统的核心是协调逻辑。该组件可确保各种专业代理之间的顺畅协调与沟通,管理工作流程、依赖关系以及任务的顺序或并行执行。

在我们的研究助理系统中,路由器代理(协调者)扮演着这一核心角色。它负责协调各个代理(如提示处理器、论文检索、关键词提取和摘要代理)之间的数据流。这样做可以确保高效处理用户查询、检索相关研究、提取有意义的见解并清晰呈现结果。

现在让我们来看看路由器代理是如何协调整个工作流程的:

代码片段(路由器代理协调)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@router_agent.tool
async def orchestrate_workflow(ctx: RunContext[ResearchContext]) -> str:
print("Starting prompt processing...")
refined_query = await prompt_processor_agent.run(ctx.deps.query,
deps=ctx.deps)
print(f"Refined Query: {refined_query.data}")
print("Fetching papers...")
papers = await paper_retrieval_agent.run(refined_query.data, deps=ctx.deps)
print(f"Fetched {len(papers.data)} papers.")
response = "Final Report:\n"
for paper in papers.data:
print(f"\nProcessing paper: {paper.title}")
print("Extracting keywords...")
keywords = await keyword_extraction_agent.run(paper.abstract,
deps=ctx.deps)
print(f"Extracted Keywords: {keywords.data.keywords}")
print("Generating summary...")
summary = await summary_agent.run(paper.abstract, deps=ctx.deps)
print(f"Generated Summary: {summary.data.summary}")
response += (
f"\nTitle: {paper.title}\n"
f"Keywords: {keywords.data.keywords}\n"
f"Summary: {summary.data.summary}\n"
)
return response
@router_agent.tool async def orchestrate_workflow(ctx: RunContext[ResearchContext]) -> str: print("Starting prompt processing...") refined_query = await prompt_processor_agent.run(ctx.deps.query, deps=ctx.deps) print(f"Refined Query: {refined_query.data}") print("Fetching papers...") papers = await paper_retrieval_agent.run(refined_query.data, deps=ctx.deps) print(f"Fetched {len(papers.data)} papers.") response = "Final Report:\n" for paper in papers.data: print(f"\nProcessing paper: {paper.title}") print("Extracting keywords...") keywords = await keyword_extraction_agent.run(paper.abstract, deps=ctx.deps) print(f"Extracted Keywords: {keywords.data.keywords}") print("Generating summary...") summary = await summary_agent.run(paper.abstract, deps=ctx.deps) print(f"Generated Summary: {summary.data.summary}") response += ( f"\nTitle: {paper.title}\n" f"Keywords: {keywords.data.keywords}\n" f"Summary: {summary.data.summary}\n" ) return response
@router_agent.tool
async def orchestrate_workflow(ctx: RunContext[ResearchContext]) -> str:
print("Starting prompt processing...")
refined_query = await prompt_processor_agent.run(ctx.deps.query, 
deps=ctx.deps)
print(f"Refined Query: {refined_query.data}")
print("Fetching papers...")
papers = await paper_retrieval_agent.run(refined_query.data, deps=ctx.deps)
print(f"Fetched {len(papers.data)} papers.")
response = "Final Report:\n"
for paper in papers.data:
print(f"\nProcessing paper: {paper.title}")
print("Extracting keywords...")
keywords = await keyword_extraction_agent.run(paper.abstract, 
deps=ctx.deps)
print(f"Extracted Keywords: {keywords.data.keywords}")
print("Generating summary...")
summary = await summary_agent.run(paper.abstract, deps=ctx.deps)
print(f"Generated Summary: {summary.data.summary}")
response += (
f"\nTitle: {paper.title}\n"
f"Keywords: {keywords.data.keywords}\n"
f"Summary: {summary.data.summary}\n"
)
return response

协调逻辑分步说明

  • 提示处理:
    • 路由器代理首先将初始用户查询传递给提示处理器代理。
    • 提示处理器对查询进行细化,然后路由器清楚地记录细化后的查询。
  • 纸张检索:
    • 路由器使用改进后的查询,调用论文检索代理从 arXiv 获取相关学术论文。
    • 检索完成后,路由器会记录检索到的论文数量,以确保系统活动的可视性。
  • 处理每篇论文: 对于检索到的每篇论文,路由器都会同时执行两项关键任务:
    • 关键词提取: 它将每篇摘要传递给关键词提取代理,并记录提取的关键词。
    • 总结: 它还会调用每个摘要的摘要代理,记录获得的简明摘要。
  • 汇总结果: 路由器将所有信息–标题、关键词、摘要–汇总成结构化的、人类可读的 “最终报告”。
  • 协调的异步(async/await)特性允许同时执行任务,大大提高了工作流程的效率,尤其是在处理外部 API 调用时。
  • 每个步骤的结构化日志提供了工作流程的清晰可视性,便于调试、追溯以及系统的未来维护或扩展。

在明确了协调之后,我们现在就可以通过生成专业的结构化报告来结束管道。

利用结构化数据生成专业输出结果

归根结底,自动化研究助手的价值不仅在于其效率,还在于其最终输出的清晰度和专业性。研究人员通常更喜欢结构化、易读的文件,这些文件能清晰地整合关键见解。将我们多智能体系统中的结构化数据转换成专业报告(如 PDF),可以提高可读性和实用性。

利用路由器代理的结构化数据输出,我们可以直接生成精美的 PDF 报告。下面是我们如何利用结构化数据,使用 Python 创建清晰、视觉效果好的 PDF 报告:

代码片段(生成 PDF)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def generate_pdf_report(report_text: str, output_filename: str = "Final_Report.pdf"):
import markdown2
from xhtml2pdf import pisa
# Convert the structured markdown text to HTML
html_text = markdown2.markdown(report_text)
# Create and save the PDF file
with open(output_filename, "w+b") as result_file:
pisa.CreatePDF(html_text, dest=result_file)
def generate_pdf_report(report_text: str, output_filename: str = "Final_Report.pdf"): import markdown2 from xhtml2pdf import pisa # Convert the structured markdown text to HTML html_text = markdown2.markdown(report_text) # Create and save the PDF file with open(output_filename, "w+b") as result_file: pisa.CreatePDF(html_text, dest=result_file)
def generate_pdf_report(report_text: str, output_filename: str = "Final_Report.pdf"):
import markdown2
from xhtml2pdf import pisa
# Convert the structured markdown text to HTML
html_text = markdown2.markdown(report_text)
# Create and save the PDF file
with open(output_filename, "w+b") as result_file:
pisa.CreatePDF(html_text, dest=result_file)

PDF 生成逻辑说明

  • 标记符转换:路由器代理生成的结构化最终报告最初是结构化文本或标记符格式。我们使用 markdown2 库将 markdown 文本转换为 HTML。
  • 生成 PDF:xhtml2pdf 库将转换后的 HTML 内容生成专业外观的 PDF 文件,格式整洁,便于阅读。
  • 结构化数据带来的便利:我们的代理通过 Pydantic 数据模型实现结构化输出,确保标记符内容格式一致。这种一致性简化了向高质量 PDF 的转换,无需人工干预或额外的复杂解析。

预期输出

以我们的结构化报告为输入,运行片段后会生成专业的 PDF。该 PDF 将清晰地显示每篇论文的标题、关键词和摘要,方便研究人员快速审阅、分发或归档其研究成果。

通过这一步,我们的多代理研究助手管道就完成了,有效地以结构化、高效和专业的方式实现了文献发现、处理和报告的自动化。接下来,我们将介绍磁性框架的几个实际案例。

行动中的多代理系统:实际案例

让我们探索一下我们的多代理研究助手在不同研究场景中的表现。我们将通过三个不同的提示来展示系统的有效性。每个示例都展示了简单的用户查询如何转变为全面、有条理、格式专业的研究报告。

示例 1: 强化学习代理

在第一个场景中,我们探讨了将强化学习应用于机器人技术的最新研究。

用户提示:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"Reinforcement learning agents in robotics"
"Reinforcement learning agents in robotics"
"Reinforcement learning agents in robotics"

下面是多代理工作流程输出的截图,清楚地说明了如何完善提示、检索相关论文、提取关键词和生成摘要。

Starting prompt processing...Refined Query: all:reinforcement learning agents AND cat: roboticsFetching papers...<ipython-input-5-08d1ccafd1dc>:46: DeprecationWarning: The 'Search.results' method is deprecated, use 'Client.results' insteadresultsFetchedlist(search.results())papers.Starting prompt processing...Refined Query: all: ("reinforcement learning agents" OR "reinforcement learning" OR "RL agents") AND cat: robotics Fetching papers...Fetchedpapers.Starting prompt processing... Starting prompt processing.... Starting prompt processing.... Starting prompt processing...Starting prompt processing...Refined Query: all: ("reinforcement learning agents" OR "RL agents") AND cat: roboticsFetching papers...Refined Query: ti:"reinforcement learning agents robotics" OR abs: "reinforcement learning agents robotics"Fetching papers...Refined Query: all: ("reinforcement learning agents" OR "reinforcement learning" OR "RL agents") AND cat: roboticsFetching papers...Refined Query: all: ("reinforcement learning agents" OR "RL agents") AND cat: roboticsFetching papers...Refined Query: ti: "reinforcement learning agents" OR ti:"reinforcement learning" OR ti: "RL agents" OR abs: "reinforcement learning agents" OR abs: "reinforcement learning" OR abs: "RL agents" AND cat: robotics Fetching papers...

请注意上面的用户提示是如何不断改进以提高搜索能力的。

Fetched 1 papers.Processing paper: An Architecture for Unattended Containerized (Deep) Reinforcement Learning with Webots Extracting keywords...Extracted Keywords: ['data science', 'reinforcement learning', '3D worlds', 'simulation software', 'Robotino', 'model development', 'unattended training', 'Webots', 'Robot Operating System', 'APIs', 'container technology', 'robot tasks'] Generating summary... Summary: This paper reviews tools and approaches for training reinforcement learning agents in 3D environments, specifically for the Robotino robot. It addresses the challenge of separating the simulation environment from the model development envi Starting prompt processing... Refined Query: ti: "reinforcement learning agents for robotics" OR abs: "reinforcement learning agents for robotics"Fetching papers...Fetched 1 papers.Processing paper: An Architecture for Unattended Containerized (Deep) Reinforcement Learning with Webots Extracting keywords...Extracted Keywords: ['data science', 'reinforcement learning', '3D simulation', 'Robotino', 'simulation software', 'Webots', 'Robot Operating System', 'unattended training pipelines', 'APIS', 'model development', 'container technology', 'virtual wo Generating summary... Summary: This paper reviews tools and approaches for training reinforcement learning agents in 3D worlds, focusing on the Robotino robot. It highlights the challenge of integrating simulation environments for virtual world creators and model develo Final Report:### Comprehensive Report on "Reinforcement Learning Agents for Robotics"#### Title:An Architecture for Unattended Containerized (Deep) Reinforcement Learning with Webots#### Authors:Tobias Haubold, Petra Linke#### Publication Date: February 6, 2024 #### Abstract:As data science applications gain traction across various industries, the tooling landscape is evolving to support the lifecycle of these applications, addressing challenges to enhance productivity. In this context, reinforcement learning (RL) for This paper reviews various tools and strategies for training reinforcement learning agents specifically for robotic applications in 3D spaces, utilizing the Robotino robot. It examines the critical issue of separating the simulation environment for The authors propose a solution that isolates data scientists from the complexities of simulation software by using Webots for simulation, the Robot Operating System (ROS) for robot communication, and container technology to create a clear division #### Keywords:Data ScienceReinforcement Learning- 3D Worlds- Simulation SoftwareRobotinoModel Development

多代理系统从 arxiv 中提取信息并整理成一份报告。

您可以在下面下载完整的结构化 PDF 报告:下载

示例 2:量子机器学习

在第二个场景中,我们将研究量子机器学习的当前发展情况。

用户提示:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"Quantum machine learning techniques"
"Quantum machine learning techniques"
"Quantum machine learning techniques"

下面的截图展示了系统如何完善查询、检索相关论文、进行关键词提取并提供简明摘要。

Starting prompt processing...Refined Query: ti: "quantum machine learning techniques" OR abs: "quantum machine learning techniques"Fetching papers...<ipython-input-5-08d1ccafd1dc>:46: DeprecationWarning: The 'Search.results' method is deprecated, use 'Client.results' insteadresults list (search.results())Fetched 5 papers.Processing paper: Experimental demonstration of enhanced quantum tomography via quantum reservoir processing Extracting keywords...Extracted Keywords: ['quantum machine learning', 'quantum reservoir processing', 'continuous-variable state reconstruction', 'bosonic circuit quantum electrodynamics', 'measurement outcomes', 'reconstruction Generating summary...Summary: This paper presents an experimental demonstration of quantum reservoir processing for continuous-variable state reconstruction using bosonic quantum circuits. It shows that the method efficiently lea Processing paper: Detection states of ions in a Paul trap via conventional and quantum machine learning algorithms Extracting keywords...Extracted Keywords: ['trapped ions', 'quantum technologies', 'quantum computing', 'state detection', 'high-fidelity readouts', 'machine learning', 'convolution', 'support vector machine', 'quantum annealing', Generating summary... Summary: This work develops and benchmarks methods for detecting quantum states of trapped ytterbium ions using images from a sensitive camera and machine learning techniques. By applying conventional and qua Processing paper: Satellite image classification with neural quantum kernels Extracting keywords...Extracted Keywords: ['quantum machine learning', 'satellite image classification', 'earth observation', 'solar panels', 'neural quantum kernels', 'quantum neural networks', 'classical pre-processing', 'dimens Generating summary... Summary: This paper presents a novel quantum machine learning approach for classifying satellite images, particularly those with solar panels, relevant to earth observation. It combines classical pre-processi Processing paper: Harnessing Quantum Extreme Learning Machines for image classificationExtracting keywords...Extracted Keywords: ['quantum machine learning', 'image classification', 'quantum extreme learning machine', 'quantum reservoir', 'feature map', 'dataset preparation', 'Principal Component Analysis', 'Auto-En Generating summary... Summary: This research explores quantum machine learning techniques for image classification, focusing on a quantum extreme learning machine that utilizes a quantum reservoir. It analyzes various encoding met Processing paper: Quantum Generative Adversarial Networks: Generating and Detecting Quantum Product States Extracting keywords...Extracted Keywords: ['quantum machine learning', 'QGAN', 'quantum product states', 'image generation', 'decoherence', 'NISQ devices', 'GAN MinMax', 'quantum style parameters', 'generator', 'discriminator'] Generating summary... Summary: The paper introduces a Quantum Generative Adversarial Network (OGAN), leveraging quantum machine learning to generate and discriminate quantum product states, a task with no classical analog. It util

下载 PDF 报告全文,了解详细内容:Quantum_Machine_Learning_Report.pdf

示例 3:人工智能代理

在第三个场景中,我们将研究如何应用多代理系统。

用户提示:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"Multi-agent systems"
"Multi-agent systems"
"Multi-agent systems"

下图是我们系统的输出截图,其中显示了结构化查询细化、相关研究论文检索、关键词提取和摘要。

Starting prompt processing...Refined Query: ti:"ai agents" OR abs: "ai agents"Fetching papers...<ipython-input-5-08d1ccafd1dc>:46: DeprecationWarning: The 'Search.results' method is deprecated, use 'Client.results' insteadresults list (search.results())Fetched 5 papers.Processing paper: Verbal Process Supervision Elicits Better Coding Agents Extracting keywords...Extracted Keywords: ['large language models', 'AI agents', 'code generation', 'software engineering', 'CURA', 'code understanding', 'reasoning agent', 'verbal process supervision', 'benchmark improvement', 'BigC Generating summary...Summary: This work introduces CURA, a code understanding and reasoning agent system enhanced with verbal process supervision (VPS), which achieves a 3.65% improvement on challenging benchmarks. When combined witProcessing paper: How to Capture and Study Conversations Between Research Participants and ChatGPT: GPT for Researchers (g4r.org) Extracting keywords...Extracted Keywords: ['large language models', 'LLMs', 'GPT for Researchers', 'G4R', 'AI systems', 'human-AI communication', 'consumer interactions', 'AI-assisted decision-making', 'GPT Interface', 'research tool Generating summary... Summary: The paper introduces GPT for Researchers (G4R), a free online platform designed to aid researchers in studying interactions with large language models (LLMs) like ChatGPT. G4R allows researchers to enab Processing paper: Collaborating with AI Agents: Field Experiments on Teamwork, Productivity, and Performance Extracting keywords...Extracted Keywords: ['AI agents', 'productivity', 'performance', 'work processes', 'MindMeld', 'experimentation platform', 'human-AI teams', 'communication', 'collaboration', 'multimodal workflows', 'AI personal Generating summary... Summary: This study introduces MindMeld, a platform for human-AI collaboration, showing that AI agents can significantly improve productivity and performance in team settings. In an experiment with 2310 particip Processing paper: Metacognition in Content-Centric Computational Cognitive C4 Modeling Extracting keywords...Extracted Keywords: ['AI agents', 'human behavior', 'metacognition', 'C4 modeling', 'cognitive robotic applications', 'neuro symbolic processing', 'LEIA Lab', 'cognitive capabilities', 'information storage', 'LL Generating summary... Summary: This paper discusses the necessity of metacognition for AI agents to replicate human behavior through effective information processing. It introduces content-centric computational cognitive (C4) modelin Processing paper: OvercookedV2: Rethinking Overcooked for Zero-Shot CoordinationExtracting keywords...Extracted Keywords: ['AI agents', 'zero-shot coordination (ZSC)', 'Overcooked', 'state augmentation', 'coordination capabilities', 'out-of-distribution challenge', 'OvercookedV2', 'asymmetric information', 'stoc Generating summary... Summary: This paper explores the challenges of zero-shot coordination (ZSC) in AI agents using the Overcooked environment. It introduces a state augmentation mechanism to improve training by incorporating states Starting prompt processing...Refined Query: ti: "ai agents" OR abs: "ai agents"Fetching papers...Fetched 5 papers.Processing paper: Verbal Process Supervision Elicits Better Coding AgentsExtracting keywords...

您可以从以下链接下载格式专业的 PDF 报告:Multi_Agent_Systems_Report.pdf

每个示例都清楚地说明了我们的多代理框架能够迅速有效地实现研究工作流程的自动化–从完善初始查询到生成结构化的专业报告,所有这些都利用了 Pydantic 的结构化数据验证功能。

小结

在本文中,我们利用 Pydantic 探索了结构化、可扩展和高效的多代理研究助理系统的设计和实施。通过明确定义结构化数据模型,我们确保了多个智能代理之间交互的一致性和可靠性–从完善用户提示、检索相关学术论文、提取有意义的关键词、总结复杂的摘要,到无缝协调整个工作流程。通过实际案例,我们展示了这一强大的框架如何实现复杂学术研究任务的自动化和大幅简化,最终形成专业品质的即用报告。

  • Pydantic 可确保结构化数据处理,显著减少错误并简化代理交互。
  • 明确的代理角色和职责使多代理系统具有模块化、可维护性和可扩展性。
  • 精细化和结构化的查询大大提高了检索研究的相关性和实用性。
  • 自动关键词提取和总结为研究人员节省了宝贵的时间,实现了快速内容评估。
  • 利用结构化日志和异步工作流进行有效的协调,可提高系统效率并方便调试。

通过采用这种结构化的多代理方法,开发人员和研究人员可以显著提高研究自动化管道的生产力、清晰度和效率。

注:为了保持博客的篇幅,将每个代码块的详细输出都包括在内是一项挑战,但这里讨论的代理系统的全部代码都已开源,以便读者更好地学习和使用!查看完整代码

评论留言