基于 Vercel AI SDK 构建 Research Agent:多源检索、事实核验与引文追踪的完整实现指南(Agent-Skills-for-Context-Engineering)
2026/9/13 23:57:39 网站建设 项目流程

基于 Vercel AI SDK 构建 Research Agent:多源检索、事实核验与引文追踪的完整实现指南(Agent-Skills-for-Context-Engineering)

【免费下载链接】Agent-Skills-for-Context-EngineeringA comprehensive collection of Agent Skills for context engineering, multi-agent architectures, and production agent systems. Use when building, optimizing, or debugging agent systems that require effective context management.项目地址: https://gitcode.com/GitHub_Trending/ag/Agent-Skills-for-Context-Engineering

导读:本文以examples/llm-as-judge-skills示例仓库中的 Research Agent 设计文档为主体,系统讲解如何在 Vercel AI SDK 6 的ToolLoopAgent架构上实现一个具备查询分解、多源检索、声明抽取、交叉核验与综合归纳能力的自动化研究智能体。你将掌握其 Agent 定义、五大工具契约、ResearchConfig全部配置项、研究流水线与引用追踪机制,并能结合仓库中的工具规格文档与配置源码直接落地到自己的研究型系统中。

一、Research Agent 在项目中的定位

examples/llm-as-judge-skills(LLM-as-a-Judge 技能示例)中,Research Agent 与 Evaluator Agent、Orchestrator Agent 共同构成一套三 Agent 协作体系。它承担的是多 Agent 流水线的信息上游职责——先收集与核验事实,再由 Evaluator 评估输出质量,由 Orchestrator 负责任务分解与结果汇总。

依据 agents/index.md 的说明,Research Agent 的核心定位是:

Gather, verify, and synthesize information from multiple sources(从多个来源收集、核验并综合信息)。

它最适用于知识库建设、事实核查、市场调研与技术文档撰写四类场景。本文所讲解的 Agent 定义、工具与配置均位于 research-agent.md,其配套的详细工具规格见 tools/research/ 目录。

二、Agent 定义:基于 ToolLoopAgent 的声明式实现

Research Agent 直接复用 Vercel AI SDK 6 的ToolLoopAgent抽象,通过instructions注入研究方法论,通过tools声明工具集,无需手写循环控制逻辑:

import { ToolLoopAgent } from "ai"; import { openai } from "@ai-sdk/openai"; import { researchTools } from "../tools"; export const researchAgent = new ToolLoopAgent({ name: "researcher", model: openai("gpt-4o"), instructions: `You are an expert research analyst. Your role is to: 1. Break down complex research questions into searchable queries 2. Gather information from multiple sources 3. Verify and cross-reference claims 4. Synthesize findings into coherent summaries 5. Provide proper citations for all claims Research Methodology: - Start with broad searches to understand the landscape - Narrow down to specific sources for detailed information - Always verify facts from multiple sources when possible - Distinguish between facts, claims, and opinions - Note the recency and authority of sources Quality Standards: - Never fabricate information or sources - Clearly indicate when information is uncertain - Provide direct quotes when precision matters - Include source URLs/references for verification`, tools: { webSearch: researchTools.webSearch, readUrl: researchTools.readUrl, extractClaims: researchTools.extractClaims, verifyClaim: researchTools.verifyClaim, synthesize: researchTools.synthesize } });

值得注意的两点设计:

  • 模型选择:该示例使用openai("gpt-4o")。仓库中的 src/config/index.ts 表明模型名可通过环境变量OPENAI_MODEL覆盖(默认gpt-4o),而密钥通过OPENAI_API_KEY注入,validateConfig()会在缺少密钥时抛出明确错误。这与 README 中OPENAI_MODEL=gpt-5.2的示例并不冲突——这正说明模型是可配置的。
  • 指令即方法论instructions不是简单的角色描述,而是把"先宽后窄、多源核验、区分事实/主张/观点、标注来源时效与权威性"等研究规范编码进了系统提示,确保模型在工具循环中遵循一致的研究纪律。

三、五大研究工具的能力契约

Research Agent 通过五个工具覆盖"检索 → 阅读 → 抽取 → 核验 → 综合"的完整链路。仓库在 tools/research/web-search.md 与 tools/research/read-url.md 中给出了前两个工具的完整规格,其余工具在 research-agent.md 的能力章节定义了输入输出契约。

3.1 Web Search(webSearch)

输入:搜索查询字符串;可选的时间范围/来源类型过滤器。输出:相关结果列表(含 snippet 与 URL)、来源元数据。

配套规格文档将其参数 Schema 细化为:

parameters: z.object({ query: z.string().describe("Search query - be specific for better results"), maxResults: z.number().min(1).max(20).default(10) .describe("Maximum number of results to return"), filters: z.object({ dateRange: z.enum(["day", "week", "month", "year", "any"]).default("any"), sourceType: z.enum(["all", "news", "academic", "documentation"]).default("all"), excludeDomains: z.array(z.string()).optional() }).optional() })

每个结果包含title / url / snippet / source(域名)/ publishedDate? / relevanceScore,整体返回success / results / totalResults / metadata(metadata 中记录querysearchTimeMs与已生效的filtersApplied)。

规格文档还给出 5 条查询优化建议:使用精确术语、用引号锁定短语、支持site:-termOR操作符、携带上下文词、加年份提升时效性。实现层面则要求做好限流、缓存、低质来源过滤、API 失败优雅降级与查询日志隐私。

3.2 URL Reading(readUrl)

输入:目标 URL;内容类型(article / paper / documentation 等)。输出:抽取后的文本内容、识别出的关键章节、出版元数据。

其 Zod Schema 定义了五个参数:

参数类型默认值说明
urlstring(须为合法 URL)要读取的地址
contentTypeenumautoauto / article / documentation / paper / code,用于优化抽取策略
maxLengthnumber(1000–50000)10000最大返回字符数
extractSectionsbooleantrue是否识别并标注章节标题
includeMetadatabooleantrue是否返回作者、日期等元数据

不同内容类型的抽取策略也不同:article优先主内容、跳过侧栏;documentation保留代码块与结构;paper抽取摘要、章节与参考文献;code保留格式与语法高亮;auto自动探测。输出结构包含content.full、按 heading 分层的content.sections[]metadata(author / publishedDate / lastModified / keywords / source)以及stats(totalCharacters / truncated / sectionsFound)。

错误处理方面定义了标准错误码:URL_NOT_FOUND(404)、ACCESS_DENIED(401/403)、TIMEOUTBLOCKED(robots.txt 或限流)、INVALID_CONTENTUNSUPPORTED_TYPE(如二进制)。实现时还需遵守 robots.txt、限制对同一域名的请求频率、设置 10–30 秒合理超时,并对 JS 重度渲染站点考虑无头浏览器。

3.3 Claim Extraction(extractClaims)

输入:来源文本;要抽取的声明类型。输出:声明列表、每条声明的置信度与支撑上下文。

它负责把一段文本拆解为可独立核验的最小事实单元(claim),并标注置信度——这是后续交叉验证的数据基础。

3.4 Claim Verification(verifyClaim)

输入:待核验的声明;原始来源。输出:核验状态、支持/矛盾的来源列表、置信度评估。

该工具对应了 Agent 指令中"Always verify facts from multiple sources when possible"的质量标准,是防止单一来源偏差的关键环节。

3.5 Synthesis(synthesize)

输入:研究成果;目标格式;需要回答的关键问题。输出:综合摘要、关键洞察、来源引用。

综合环节并非简单拼接,而是要求归纳共识与分歧、标注不确定性并给出可行动结论。仓库在 prompts/research/research-synthesis-prompt.md 中提供了配套的综合提示模板,我们将在第五节详细展开。

四、ResearchConfig:配置项与默认值全解析

research-agent.md给出了完整的ResearchConfig接口及默认值,分为三组:

interface ResearchConfig { // Search configuration maxSearchResults: number; preferredSources: string[]; excludedDomains: string[]; // Verification settings minSourcesForVerification: number; requireRecentSources: boolean; maxSourceAge: "1month" | "6months" | "1year" | "any"; // Output configuration citationStyle: "inline" | "footnote" | "endnote"; summaryLength: "brief" | "standard" | "comprehensive"; includeSourceQuality: boolean; } const defaultConfig: ResearchConfig = { maxSearchResults: 10, preferredSources: [], excludedDomains: [], minSourcesForVerification: 2, requireRecentSources: false, maxSourceAge: "any", citationStyle: "inline", summaryLength: "standard", includeSourceQuality: true };

各配置项含义与实用建议:

配置项默认值作用与建议
maxSearchResults10单次搜索返回结果上限。建议结合场景调整:宽泛背景调研可取更大值,精确事实核验 5–10 条即可。对应 webSearch 工具maxResults(1–20)的上层约束
preferredSources[]优先来源白名单(如arxiv.org)。当研究问题对来源权威性敏感时(如学术主题),应优先配置
excludedDomains[]排除域名黑名单,可直接映射到 webSearch 的filters.excludeDomains,用于过滤低质站点
minSourcesForVerification2声明核验所需的最少独立来源数。取 2 是"至少双源印证"的平衡点,提高它可增强结论可靠性但会显著增加检索成本
requireRecentSourcesfalse是否强制要求近期来源。对时效敏感的主题(技术趋势、市场行情)建议开启
maxSourceAge"any"来源最大可接受时效,枚举1month / 6months / 1year / any。与上项配合使用
citationStyle"inline"引用风格:inline(文中内联)、footnote(脚注)、endnote(尾注)
summaryLength"standard"摘要长度:brief / standard / comprehensive
includeSourceQualitytrue是否在输出中包含来源质量评估,对应综合报告中的 Source Quality Assessment 章节

五、研究综合提示模板与引用机制

综合环节的提示模板(research-synthesis-prompt.md)定义了稳定的输出骨架,确保不同研究任务产出结构一致的报告。模板要求综合必须覆盖:

  1. Executive Summary:2–3 句话的关键发现概览
  2. Key Themes:跨来源涌现的主要主题
  3. Findings by Topic:按研究问题组织的分主题发现
  4. Areas of Consensus:多来源一致之处
  5. Areas of Disagreement:来源冲突或分歧之处
  6. Gaps and Limitations:未回答的问题与信息局限
  7. Actionable Insights:可落地的实用结论
  8. Source Quality Assessment:来源可靠性与相关性评估

模板使用 Mustache 风格变量渲染,核心变量为research_questionfindings数组(每个元素含source / date / type / content)。在判断标准上给出 5 条最佳实践:主题提炼需基于 3 个以上来源、事实类主张以学术来源优先于博客、标注发现可能过时、不夸大来源未支撑的结论、以实用 takeaways 收尾。

三种引用风格

风格格式适用
Inline(默认)"Finding or claim" [Author/Source, Date]通用场景,读者可即时定位出处
Footnote"Finding or claim"[1]+ 文末脚注列表报告、出版物风格
Endnote"Finding or claim" (see Sources: Source Name)+ Sources 列表需要集中引用区时

六、研究流水线:从问题到最终报告

research-agent.md用 Mermaid 图完整定义了八阶段流水线:

  • Query Decomposition(查询分解):对应指令中"Break down complex research questions into searchable queries",把复合问题拆为多个可检索子查询;
  • Initial Search(初始检索):先宽泛搜索以理解领域全貌,对应 webSearch 的"Start with broad searches";
  • Source Selection(来源选择):结合preferredSourcesexcludedDomainsrelevanceScore与来源权威性筛选;
  • Deep Reading(深度阅读):对选中来源执行 readUrl 抽取正文;
  • Claim Extraction(声明抽取):将正文拆解为带置信度的独立声明;
  • Cross-Verification(交叉核验):对每条声明用minSourcesForVerification(默认 2)个独立来源验证;
  • Synthesis(综合归纳):按第五节模板生成结构化报告;
  • Final Report(最终报告):输出含完整引用的结论。

七、使用示例:一次完整的自动调研

research-agent.md给出的调用方式非常简洁——只需传入一个自然语言 prompt,Agent 会在工具循环中自行完成上述流水线:

import { researchAgent } from "./agents/research-agent"; const research = await researchAgent.generate({ prompt: `Research the current state of LLM evaluation methods. I need to understand: 1. What are the main approaches to evaluating LLM outputs? 2. What are the limitations of human evaluation? 3. How reliable are LLM-based evaluators compared to humans? 4. What are best practices for implementing LLM-as-a-Judge? Provide a comprehensive summary with citations.` });

这里展示了一个高质量研究 prompt 的写法:先给出研究主题(LLM evaluation methods 的现状),再以编号问题明确信息需求,最后声明输出要求(comprehensive summary with citations)。ToolLoopAgent会自动循环调用webSearch → readUrl → extractClaims → verifyClaim → synthesize,直到产出满足指令约束的结果。

八、与其他 Agent 的集成方式

8.1 被 Orchestrator 委托调用

Research Agent 是 Orchestrator 声明的四个可委托 Agent(evaluator / researcher / writer / analyst)之一,见 tools/orchestration/delegate-to-agent.md。委托时需传入完整上下文、期望输出格式与成功标准,例如:

await delegateToAgent.execute({ agentName: "researcher", task: "Research current best practices for LLM evaluation", context: { constraints: ["Focus on 2024 publications", "Include citations"] }, expectedOutput: { format: "markdown" } });

8.2 四种典型集成场景

research-agent.md的 Integration Points 章节给出了四类落地场景:

  • Knowledge Base Building(知识库建设):将研究成果沉淀为内部知识存储,可为 skills/context-fundamentals 所讲的上下文工程提供事实底座;
  • Fact Checking(事实核查):核验生成内容中的声明,可与 Evaluator Agent 配合形成"生成—核验—评估"闭环;
  • Market Research(市场调研):采集竞争情报与行业动态;
  • Technical Documentation(技术文档):调研实现方案与最佳实践,支撑文档撰写。

在 Orchestrator 的典型编排中,Research Agent 通常处于流水线首段(Sequential Pipeline 的Task → Research Agent → Analyst → Writer → Evaluator),或在并行扇出模式中与其他 Agent 并行执行后汇聚到合成阶段。

九、落地与运行前提

当前仓库中,Research Agent 以完整的 Agent 定义与工具规格文档形式呈现(agents/research-agent/research-agent.md、tools/research/);而src/tools/目录下目前包含的是evaluation 类工具(direct-score / pairwise-compare / generate-rubric)的 TypeScript 实现,研究类工具(webSearch、readUrl 等)在仓库中停留在规格文档层面,需要按上述 Schema 自行接入具体的搜索与抓取服务。

运行本项目的前提条件(依据 README.md 与 src/config/index.ts):

  1. 在项目根目录创建.env,配置OPENAI_API_KEY(必填,缺失时validateConfig()会抛错)与OPENAI_MODEL(可选,默认gpt-4o);
  2. 执行npm install安装依赖,npm test运行测试套件;
  3. 若要启用 Anthropic 模型(如 Evaluator/Orchestrator 示例中的claude-sonnet-4-20250514),还需配置ANTHROPIC_API_KEY

十、小结

Research Agent 的设计展示了如何用声明式方式构建一个严谨的研究型 Agent:ToolLoopAgent负责循环控制,instructions承载研究方法论与质量标准,五工具契约覆盖"检索—阅读—抽取—核验—综合"全链路,ResearchConfig把来源偏好、核验强度与引用风格参数化,综合提示模板则保证不同任务产出结构一致、可引用的报告。对任何需要可靠信息采集与事实核验能力的 Agent 系统,这套架构都提供了可直接借鉴的完整范式。

【免费下载链接】Agent-Skills-for-Context-EngineeringA comprehensive collection of Agent Skills for context engineering, multi-agent architectures, and production agent systems. Use when building, optimizing, or debugging agent systems that require effective context management.项目地址: https://gitcode.com/GitHub_Trending/ag/Agent-Skills-for-Context-Engineering

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询