Swarms Logo
指南工程

通过 API 实现智能体式 RAG:会检查自己答案的检索智能体

一份用 Python 实现智能体式 RAG(Agentic RAG)的教程:规划智能体编写搜索查询,回答智能体只依据检索到的段落作答并标注引用,验证智能体逐条核对每个论断,发现缺乏依据时要求再次检索。基于 Swarms API 构建,并与普通 RAG 并排比较。

Kye Gomez12 分钟阅读
通过 API 实现智能体式 RAG:会检查自己答案的检索智能体

普通的检索增强生成(RAG)是一条固定流水线:把用户问题向量化,取回最相关的几个片段,贴进提示词,模型写什么就返回什么。当问题和文档用词相同、答案就在某一个片段里时,它工作得很好。但在三种常见情况下,它会悄无声息地失败:

  1. 问题的措辞与文档不同。 当员工手册写的是“公司场所内的动物”时,“我能带狗去上班吗?”检索不到任何有用的内容。
  2. 答案需要来自多处的事实。 对一个复合问题只搜索一次,返回的片段往往只涉及其中一半。
  3. 模型用记忆填补空白。 检索落空时,答案听起来依然很自信,而流水线里没有任何环节会察觉。

智能体式 RAG(Agentic RAG) 用智能体取代固定流水线,由它们做出一个细心的人会做的判断:该搜索什么,检索到的段落是否真的回答了问题,答案的每一句是否都有来源支撑。本教程在 Swarms API 上用 Python 构建这个循环,包括三个智能体和一个小型本地搜索索引,并在相同的问题上与普通 RAG 并排运行,让你在自己的数据上看到差别。

设计

question │ ▼ Query Planner ── 2 to 4 search queries ──► your index (BM25 here, any vector DB in production) │ passages with ids ▼ Answer Writer ── answer with [doc#chunk] citations │ ▼ Verifier ── supported? ──yes──► return answer │ no └── follow-up queries ──► retrieve again, rewrite (max 2 rounds)

检索留在你的代码里,所以索引、权限和数据都完全由你掌控。智能体负责决定检索 什么,以及 结果是否足够好。每个智能体都是对 POST /v1/agent/completions 的一次调用,各自使用适合自己工作的模型:规划和核查用小而快的模型,写作用更强的模型。

第一步:一个小型搜索索引

为了让示例自成一体,索引使用 rank-bm25 包,对一个 Markdown 文件夹做 BM25 检索。在生产环境中,把 search() 换成你的向量数据库或混合检索即可,其余部分都不用改。

Python
# pip install requests rank-bm25
import json
import os
import re
from pathlib import Path

import requests
from rank_bm25 import BM25Okapi


def load_chunks(folder: str, size: int = 120) -> list[dict]:
    """Split every .md file into chunks of about `size` words, each with a stable id."""
    chunks = []
    for path in sorted(Path(folder).glob("*.md")):
        words = path.read_text(encoding="utf-8").split()
        for i in range(0, len(words), size):
            chunks.append({"id": f"{path.stem}#{i // size}", "text": " ".join(words[i : i + size])})
    return chunks


CHUNKS = load_chunks("docs")
TOKENIZE = lambda s: re.findall(r"\w+", s.lower())
INDEX = BM25Okapi([TOKENIZE(c["text"]) for c in CHUNKS])


def search(query: str, k: int = 4) -> list[dict]:
    scores = INDEX.get_scores(TOKENIZE(query))
    ranked = sorted(range(len(CHUNKS)), key=lambda i: scores[i], reverse=True)[:k]
    return [CHUNKS[i] for i in ranked if scores[i] > 0]

第二步:所有智能体共用的调用函数

三个智能体都是对同一个端点的单次调用,所以一个辅助函数就够了。它返回智能体的文本,并把 usage 中的费用累加到总计里。

Python
API = "https://api.swarms.world/v1/agent/completions"
HEADERS = {"x-api-key": os.environ["SWARMS_API_KEY"], "Content-Type": "application/json"}
COST = {"total": 0.0}


def run_agent(name: str, model: str, system_prompt: str, task: str, max_tokens: int = 1500) -> str:
    payload = {
        "agent_config": {
            "agent_name": name,
            "model_name": model,
            "system_prompt": system_prompt,
            "max_loops": 1,
            "max_tokens": max_tokens,
            "temperature": 0,
        },
        "task": task,
    }
    resp = requests.post(API, headers=HEADERS, json=payload, timeout=120)
    resp.raise_for_status()
    data = resp.json()
    COST["total"] += data["usage"]["total_cost"]
    turns = [t for t in data["outputs"] if str(t.get("role", "")).lower() not in ("user", "system")]
    return str(turns[-1]["content"])


def parse_json(text: str) -> dict:
    match = re.search(r"\{.*\}", text, re.S)
    return json.loads(match.group(0)) if match else {}


def format_passages(passages: list[dict]) -> str:
    return "\n\n".join(f"[{p['id']}] {p['text']}" for p in passages)

第三步:三个智能体

查询规划者(Query Planner) 把一个问题变成几次搜索。它用文档常用的词汇改写问题,并把复合问题拆成几部分。

Python
PLANNER = """You write search queries for a keyword search engine over a company's internal documents.
Given a question, return 2 to 4 short queries that together cover everything needed to answer it.
Use the formal terms a policy document would use, and split compound questions into separate queries.
Return only JSON: {"queries": ["...", "..."]}"""

回答撰写者(Answer Writer) 只能使用给定的段落。每一句都带引用,段落里找不到答案时就如实说明。

Python
WRITER = """Answer the question using only the passages provided. Cite the passage id in square brackets
after every sentence, like [handbook#3]. If the passages do not contain the answer, say exactly
"I could not find this in the documents." and nothing else. Do not use outside knowledge."""

验证者(Verifier) 逐条对照段落检查答案。发现缺乏依据的内容时,它会说明下一步该搜索什么。

Python
VERIFIER = """You check whether an answer is fully supported by the passages it cites.
For each sentence, confirm the cited passage actually states that claim.
Return only JSON:
{"supported": true | false,
 "unsupported_claims": ["<claim>", ...],
 "missing_information": "<what the answer still needs, or empty>",
 "follow_up_queries": ["<search query that could find it>", ...]}"""

第四步:智能体循环

循环依次规划、检索、撰写和验证。如果验证者发现问题,它的后续查询会取回更多段落,撰写者再结合验证者的反馈重写一次。把轮数上限设为两轮,可以让难题的费用保持可控。

Python
def agentic_rag(question: str, max_rounds: int = 2) -> dict:
    plan = parse_json(run_agent("Query Planner", "gpt-5.4-mini", PLANNER, question, max_tokens=300))
    queries = plan.get("queries") or [question]

    passages: dict[str, dict] = {}
    for q in queries:
        for p in search(q):
            passages[p["id"]] = p

    feedback, answer, check = "", "", {}
    for round_no in range(1, max_rounds + 1):
        task = f"Question: {question}\n\nPassages:\n{format_passages(list(passages.values()))}"
        if feedback:
            task += f"\n\nA reviewer found problems with your previous answer:\n{feedback}\nFix them."
        answer = run_agent("Answer Writer", "claude-sonnet-5", WRITER, task)

        if answer.startswith("I could not find"):
            check = {"supported": True, "abstained": True}
            break

        check = parse_json(run_agent(
            "Verifier", "gpt-5.4", VERIFIER,
            f"Question: {question}\n\nAnswer:\n{answer}\n\nPassages:\n{format_passages(list(passages.values()))}",
            max_tokens=600,
        ))
        if check.get("supported"):
            break

        new = 0
        for q in check.get("follow_up_queries", []):
            for p in search(q):
                if p["id"] not in passages:
                    passages[p["id"]] = p
                    new += 1
        feedback = json.dumps({k: check.get(k) for k in ("unsupported_claims", "missing_information")})
        if new == 0 and round_no < max_rounds:
            feedback += "\nNo new passages were found. Remove any claim the passages do not support."

    return {
        "answer": answer,
        "supported": bool(check.get("supported")),
        "queries": queries,
        "sources": sorted(passages),
        "rounds": round_no,
    }

价值主要来自三个细节:

  • 规划者的查询会合并去重,复合问题的每一部分都能取回段落。
  • 撰写者可以拒答。 当文档没有覆盖这个问题时,“I could not find this”就是正确答案,远好过一个自信的猜测。
  • 检索不到新内容时,撰写者会被要求删掉无法支撑的内容,而不是无限循环下去。

第五步:用于对比的普通 RAG

基准就是大多数教程止步的那条流水线:用原始问题搜索一次,调用一次回答,并使用相同的撰写提示词和模型,这样唯一的区别就是智能体循环。

Python
def plain_rag(question: str) -> dict:
    passages = search(question)
    task = f"Question: {question}\n\nPassages:\n{format_passages(passages)}"
    return {"answer": run_agent("Answer Writer", "claude-sonnet-5", WRITER, task),
            "sources": [p["id"] for p in passages]}

第六步:在你自己的问题上比较

写下 20 到 30 个用户真正会问的问题,包括几个复合问题,以及几个文档无法回答的问题。然后运行两条流水线,并用同一个验证者为两者评分,这样分数的含义就是“每个论断都有段落支撑”:

Python
QUESTIONS = [
    "Can I bring my dog to the office?",
    "How many vacation days do I get in my first year, and do unused days carry over?",
    "What is the reimbursement limit for a home office chair?",
    "Do we offer a stipend for learning Japanese?",  # not in the docs: the right answer is to abstain
]

def grade(question: str, answer: str, sources: list[str]) -> bool:
    if answer.startswith("I could not find"):
        return True
    passages = [c for c in CHUNKS if c["id"] in set(sources)]
    verdict = parse_json(run_agent("Verifier", "gpt-5.4", VERIFIER,
        f"Question: {question}\n\nAnswer:\n{answer}\n\nPassages:\n{format_passages(passages)}", 600))
    return bool(verdict.get("supported"))

for q in QUESTIONS:
    p = plain_rag(q)
    a = agentic_rag(q)
    print(f"{q}\n  plain:   supported={grade(q, p['answer'], p['sources'])}  sources={p['sources']}"
          f"\n  agentic: supported={a['supported']}  rounds={a['rounds']}  queries={a['queries']}\n")

print(f"Total cost: ${COST['total']:.4f}")

在输出中要关注什么:对简单的查找问题,两条流水线通常给出相同的答案,智能体式 RAG 只是多花几次调用。差距出现在普通 RAG 本来就不擅长的问题上。措辞不匹配的问题由规划者改写的查询解决,复合问题的每一部分都能取回段落,无法回答的问题会得到如实的拒答,而不是一条编造出来的政策。对于失败的样本,看 queries 这一列:它准确展示了规划者是如何理解这个问题的。

如果想用来自不同供应商的评委小组和多数投票做更正式的评分,可以把答案接入 LLM-as-a-Judge:构建评估流水线 中的流水线。

费用与延迟

普通 RAG 每个问题调用一次模型。智能体式 RAG 在常见情况下调用三次(规划、撰写、验证),需要第二轮时调用五次。两个选择能让它保持实惠:

  • 小任务用小模型。 规划者只写几条简短查询,验证者做文本比对,gpt-5.4-mini 这类模型都能胜任。把预算花在撰写者上。
  • 查看每个问题的费用。 每个响应都带有 usage.total_cost,脚本会在 COST 中累加。如果想在运行前估算,GET /v1/models/pricing 列出了每个模型每百万 token 的价格。

延迟是各次调用之和,通常每次几秒。如果这对你的界面很重要,可以用 streaming_on 流式返回撰写者的答案,之后再运行验证者,在它工作时显示“正在核对来源”的状态。

更进一步

  • 让智能体自己调用搜索。 把 search() 放到一个小型 MCP 服务器后面,并在智能体配置中把它的 URL 作为 mcp_url 传入。智能体就能在一次请求中、在自己的运行过程里按需多次搜索。如何用 Python 把 AI 智能体变成 MCP 服务器 展示了服务端的写法。
  • 同时搜索网页。 在请求中加上 "tools_enabled": ["auto_search"],智能体就能通过 Exa 搜索网页,每个请求 $0.04,适合内部文档引用外部标准的场景。
  • 一次处理大量问题。 在 Pro 方案中,POST /v1/agent/batch/completions 可以并发运行一组智能体请求,把几百个问题的评估变成少数几个请求。

开始使用

在 cloud.swarms.world 创建 API 密钥,把你自己的几份文档放进 docs/,然后运行对比脚本。每次调用都会连同 token 数和费用一起出现在 Swarms Cloud 的请求日志中。Swarms API 文档 完整介绍了智能体端点,价格页面 列出了每个方案包含的内容。

更多文章

Swarms v18「Multiplex」:自组织 swarm、A2A、原生异步智能体、结构化输出,以及每个结构都能报告的 token 用量
工程

Swarms v18「Multiplex」:自组织 swarm、A2A、原生异步智能体、结构化输出,以及每个结构都能报告的 token 用量

Swarms v18(代号 Multiplex)的完整技术更新日志。SelfOrganizingSwarm 运行一支没有领导者、靠消息协调的团队;MessageBoard 给智能体一个通过工具来使用的论坛;A2AServer 和 A2AClient 让任何智能体接入 A2A 协议;Agent.arun 原生运行在事件循环上;output_schema 返回经过校验的 Pydantic 对象;每一个多智能体结构都会报告自己的 token 用量;七个结构强制要求它们所依赖的那次工具调用;图片终于真正送到了模型那里;遥测默认关闭;导入 swarms 并构建第一个 Agent 的时间减半。2026 年 11 月 2 日到 12 月 1 日之间的每一项新特性、改进、缺陷修复和删除,逐日记录。

无需服务器部署 AI 智能体:一次 API 调用实现定时与事件驱动的智能体
指南

无需服务器部署 AI 智能体:一次 API 调用实现定时与事件驱动的智能体

在 Vercel Cron、AWS Lambda 或 Cloudflare Workers 上按计划或响应 webhook 运行 AI 智能体,无需维护 Python 运行时、常驻 worker 或队列。每次智能体运行都只是对 Swarms API 的一次 HTTPS 请求。附三个平台的 TypeScript 代码。

OpenAI Assistants API 已经关停:如何把你的智能体迁移到 Swarms API
指南

OpenAI Assistants API 已经关停:如何把你的智能体迁移到 Swarms API

OpenAI 已于 2026 年 8 月 26 日停用 Assistants API。本指南把 assistant、thread、run、函数工具和文件检索逐一对应到 Swarms API,附 Python 迁移前后的对照代码、一个由你自己掌控的会话存储、用 MCP 替代函数调用,以及给已在使用 OpenAI SDK 的代码准备的一行改动方案。