Swarms Logo
GuidesEngineering

Agentic RAG via API: Retrieval Agents That Check Their Own Answers

An agentic RAG tutorial in Python: a planner agent writes the search queries, an answer agent writes only from retrieved passages with citations, and a verifier agent checks every claim and asks for another search when something is unsupported. Built on the Swarms API, compared side by side with plain RAG.

Kye Gomez12 min read
Agentic RAG via API: Retrieval Agents That Check Their Own Answers

Plain retrieval-augmented generation (RAG) is a fixed pipeline: embed the user's question, fetch the top few chunks, paste them into a prompt, return whatever the model writes. It works well when the question uses the same words as the documents and the answer sits in one chunk. It fails quietly in three common cases:

  1. The question is phrased differently from the documents. "Can I bring my dog to work?" retrieves nothing useful when the handbook says "animals on company premises".
  2. The answer needs facts from several places. One search for a compound question returns chunks about only one half of it.
  3. The model fills gaps from memory. When retrieval misses, the answer still sounds confident, and nothing in the pipeline notices.

Agentic RAG replaces the fixed pipeline with agents that make the decisions a careful person would: what to search for, whether the passages actually answer the question, and whether each sentence of the answer is backed by a source. This tutorial builds that loop in Python on the Swarms API, with three agents and a small local search index, and runs it next to plain RAG on the same questions so you can see the difference on your own data.

The design

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)

Retrieval stays in your code, so you keep full control of the index, permissions and data. The agents decide what to retrieve and whether the result is good enough. Each agent is one call to POST /v1/agent/completions, and each one uses the model that fits its job: small and fast for planning and checking, stronger for writing.

Step 1: a tiny search index

To keep the example self-contained, the index is BM25 over a folder of Markdown files, using the rank-bm25 package. In production, replace search() with your vector database or hybrid search; nothing else changes.

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]

Step 2: one helper for every agent call

All three agents are single calls to the same endpoint, so one helper covers them. It returns the agent's text and adds the cost from the usage block to a running total.

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)

Step 3: the three agents

The Query Planner turns one question into a few searches. It rewrites the question in the vocabulary documents tend to use, and splits compound questions into parts.

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": ["...", "..."]}"""

The Answer Writer may only use the passages. Every sentence carries a citation, and when the passages do not contain the answer it says so.

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."""

The Verifier checks the answer against the passages, claim by claim. When something is unsupported, it says what to search for next.

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>", ...]}"""

Step 4: the agentic loop

The loop plans, retrieves, writes and verifies. If the verifier finds a problem, its follow-up queries fetch more passages and the writer tries again with the verifier's feedback. Capping it at two rounds keeps the cost of a hard question bounded.

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,
    }

Three details carry most of the value:

  • The planner's queries are merged and deduplicated, so compound questions get passages for every part.
  • The writer may abstain. "I could not find this" is a correct answer when the documents do not cover the question, and it is much better than a confident guess.
  • When retrieval finds nothing new, the writer is told to drop what it cannot support instead of looping forever.

Step 5: plain RAG for comparison

The baseline is the pipeline most tutorials stop at: one search with the raw question and one answer call, using the same writer prompt and model so the only difference is the agentic loop.

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]}

Step 6: compare them on your own questions

Write 20 to 30 questions your users actually ask, including a few compound ones and a few your documents cannot answer. Then run both pipelines and grade both with the same verifier, so the score means "every claim is backed by a passage":

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}")

What to look for in the output: on simple lookups both pipelines usually give the same answer, and agentic RAG just costs a few more calls. The gap shows up on the questions plain RAG was never built for. Phrasing mismatches get fixed by the planner's rewritten queries, compound questions get passages for every part, and unanswerable questions get an honest abstention instead of an invented policy. Read the queries column for the failures: it shows exactly how the planner interpreted the question.

To grade more formally, with a panel of judges from different providers and majority voting, plug the answers into the pipeline from LLM-as-a-Judge: Build an Evaluation Pipeline.

Cost and latency

Plain RAG is one model call per question. Agentic RAG is three calls in the common case (plan, write, verify) and five when a second round is needed. Two choices keep that affordable:

  • Use small models where the job is small. The planner writes a few short queries and the verifier compares text; gpt-5.4-mini and similar models handle both. Spend on the writer.
  • Read the cost per question. Every response carries usage.total_cost, and the script totals it in COST. GET /v1/models/pricing lists every model's price per million tokens if you want to estimate before running.

Latency is the sum of the calls, typically a few seconds each. If that matters for your UI, stream the writer's answer with streaming_on and run the verifier after it, showing a "checking sources" state while it works.

Going further

  • Let the agent call search itself. Put search() behind a small MCP server and pass its URL as mcp_url in the agent config. The agent then searches during its own run, as many times as it needs, in a single request. How to Turn an AI Agent into an MCP Server shows the server side.
  • Search the web as well. Add "tools_enabled": ["auto_search"] to a request and the agent can search the web through Exa for $0.04 per request, useful when internal documents link to external standards.
  • Run many questions at once. On the Pro plan, POST /v1/agent/batch/completions runs a list of agent requests concurrently, which turns an evaluation over hundreds of questions into a handful of requests.

Get started

Create an API key at cloud.swarms.world, put a few of your own documents in docs/, and run the comparison script. Every call shows up in your request logs on Swarms Cloud with its tokens and cost. The Swarms API docs cover the agent endpoint in full, and the pricing page shows what each plan includes.

More from the blog

Swarms v18 'Collective': Self-Organizing Swarms, A2A, Native Async Agents, Structured Output, and Token Usage on Every Structure
Engineering

Swarms v18 'Collective': Self-Organizing Swarms, A2A, Native Async Agents, Structured Output, and Token Usage on Every Structure

The complete technical changelog for Swarms v18, code-named Collective. SelfOrganizingSwarm runs a leaderless team that coordinates by message, MessageBoard gives agents a forum they work through tools, A2AServer and A2AClient put any agent on the A2A protocol, Agent.arun runs natively on the event loop, output_schema returns a validated Pydantic object, every multi-agent structure reports its token usage, seven structures force the tool call they depend on, images actually reach the model, telemetry is off by default, and importing swarms and building the first Agent takes half the time. Every new feature, improvement, bug fix and removal from November 2 to December 1, 2026, day by day.

Deploy AI Agents Without Servers: Scheduled and Event-Driven Agents With One API Call
Guides

Deploy AI Agents Without Servers: Scheduled and Event-Driven Agents With One API Call

Run AI agents on a schedule or in response to webhooks from Vercel Cron, AWS Lambda or Cloudflare Workers, with no Python runtime, worker process or queue to maintain. Each agent run is one HTTPS request to the Swarms API. TypeScript code for all three platforms.

The OpenAI Assistants API Has Shut Down: How to Migrate Your Agents to the Swarms API
Guides

The OpenAI Assistants API Has Shut Down: How to Migrate Your Agents to the Swarms API

OpenAI sunset the Assistants API on August 26, 2026. This guide maps assistants, threads, runs, function tools and file search to the Swarms API, with before-and-after Python code, a thread store you own, MCP in place of function calling, and a one-line route for code that already uses the OpenAI SDK.