Velamuvi AIAcademy

Lesson 6 of 6 · Project

Project: Multi-Agent Research System

Build a multi-agent research system: a lead agent briefs workers, workers search a library on a shared budget and a checker removes unsupported claims.

  • 8 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Combine a lead agent, research workers and a checking agent into one system
  • Give workers search and read tools, a brief and a shared search budget
  • Collect findings in shared state with clear ownership
  • Verify every claim against its cited source before it reaches the report
  • Swap the stand-in workers for real model-driven agents

What you'll build

A research system that answers: “How can Riverton cool its city centre in summer, and what would it cost?” Riverton is a made-up city, and its documents are a small sample library, so the whole system runs in your browser.

The system has four roles:

  1. Lead agent: plans three research topics and writes a brief for each.
  2. Research workers: one per topic. Each searches the library, reads documents and keeps relevant sentences, with their sources, within a shared search budget.
  3. Writer step: the lead turns findings into claims with citations, each fact once.
  4. Citation checker: a separate agent that checks every claim against the document it cites, and removes what it can't verify.

This uses every lesson in the course: workers with focused contexts and briefs (lessons 1 and 2), results passed back as structured data (lesson 4), and shared state with ownership (lesson 5).

The complete system

Read the code from top to bottom: the library and its two tools, the shared board, the lead's plan, the workers, the writer and the checker.

Try it yourselfPython
import re

# ---------- The library the agents can search (sample documents about a made-up city) ----------
DOCS = {
    "tree-survey": "Streets with mature trees in Riverton were up to 4°C cooler on hot afternoons than streets without trees. Tree shade lowered pavement surface temperatures by over 10°C. Newly planted trees take 10 to 15 years to give full shade.",
    "cool-roofs-pilot": "In the 2023 cool roofs pilot, 40 flat roofs were painted with a reflective coating. Top-floor indoor temperatures under the coated roofs fell by 1.5 to 3°C during heatwaves. Coated roofs have to be recoated about every 10 years.",
    "pavement-study": "Light-coloured reflective pavements stayed cooler than dark asphalt. On narrow streets, reflective pavements bounced heat onto pedestrians and walls. Reflective pavements work best on wide squares and car parks.",
    "budget-2025": "The 2025 climate budget sets aside 2.4 million euros for heat measures. Planting a street tree costs about 1,200 euros, including five years of watering. Reflective roof coating costs about 25 euros per square metre.",
    "parks-note": "Small pocket parks with grass and trees cooled the surrounding block by about 1°C. Water fountains gave short-term relief but used a lot of water during droughts.",
    "regional-fund": "The regional climate fund pays up to half the cost of planting and greening projects in towns under 200,000 people. Applications to the fund close on 31 March each year.",
    "bus-timetable": "Summer bus timetables start on 1 July. Route 4 runs every 15 minutes in the city centre.",
    "green-roofs-guide": "Green roofs insulate buildings and slow rainwater run-off. Green roofs cost about 80 to 120 euros per square metre, more than reflective coatings. Buildings need roofs strong enough to carry the extra weight of soil and plants.",
}
STOP = {"the", "a", "of", "in", "and", "to", "for", "on", "by", "how", "what", "do", "does", "much"}

def words(text):
    return [w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP]

def search(query, k=3):
    """Tool: rank documents by how many query words they contain."""
    q = set(words(query))
    scored = sorted(((len(q & set(words(t))), d) for d, t in DOCS.items()), reverse=True)
    return [d for score, d in scored[:k] if score > 0]

def sentences(doc_id):
    """Tool: read a document, split into sentences."""
    return re.split(r"(?<=\.) ", DOCS[doc_id])

# ---------- Shared state: each worker owns one entry, so workers never overwrite each other ----------
board = {"searches": 0, "docs_read": set(), "findings": {}}
MAX_SEARCHES = 8                                   # budget for the whole team

# ---------- Lead agent, step 1: plan (a stand-in for the lead model's plan) ----------
QUESTION = "How can Riverton cool its city centre in summer, and what would it cost?"
BRIEFS = [
    {"topic": "Trees and green space", "queries": ["trees shade cooler streets", "pocket parks grass cooling"],
     "keywords": ["trees", "shade", "pocket"]},
    {"topic": "Cool roofs and pavements", "queries": ["reflective roofs coating", "reflective pavements asphalt", "green roofs"],
     "keywords": ["roofs", "pavements"]},
    {"topic": "Costs and funding", "queries": ["cost euros budget", "fund applications cost"],
     "keywords": ["euros", "cost", "costs", "fund"]},
]

# ---------- Worker agents: search, read, keep relevant sentences with their source ----------
def researcher(brief):
    found = []
    for query in brief["queries"]:
        if board["searches"] >= MAX_SEARCHES:
            break
        board["searches"] += 1
        for doc_id in search(query):
            board["docs_read"].add(doc_id)
            for s in sentences(doc_id):
                if any(k in words(s) for k in brief["keywords"]) and (s, doc_id) not in found:
                    found.append((s, doc_id))
    board["findings"][brief["topic"]] = found        # write only to its own entry

for brief in BRIEFS:                                   # in production: in parallel
    researcher(brief)

# ---------- Lead agent, step 2: write claims with citations (a stand-in for the writing model) ----------
claims, used = [], set()
for topic, found in board["findings"].items():
    for s, doc in found:
        if s not in used:                             # each fact once, under the first topic that found it
            used.add(s)
            claims.append((topic, s, doc))
claims.append(("Cool roofs and pavements",              # a typical writing slip: right fact, wrong source
               "Streets with mature trees in Riverton were up to 4°C cooler on hot afternoons than streets without trees.",
               "cool-roofs-pilot"))

# ---------- Citation checker agent: every claim must appear in the source it cites ----------
checked = [(t, s, d) for t, s, d in claims if s in DOCS[d]]
removed = [(t, s, d) for t, s, d in claims if s not in DOCS[d]]

# ---------- Final report ----------
print("Question:", QUESTION, "\n")
for topic in [b["topic"] for b in BRIEFS]:
    print(topic)
    for t, s, d in checked:
        if t == topic:
            print(f"  - {s} [{d}]")
print(f"\nCitation check: {len(claims)} claims, {len(removed)} removed")
for t, s, d in removed:
    print(f"  removed: '{s[:45]}...' is not in [{d}]")
unused = sorted(set(DOCS) - {d for _, _, d in checked})
print(f"Work: {board['searches']} searches, {len(board['docs_read'])} documents read, never cited: {unused}")

How it works

The tools. search ranks documents by how many query words they contain; sentences reads a document. Real systems use web search or the vector search from the RAG course, but the workers would use them the same way.

The briefs. Each brief gives a worker its topic, the searches to try and the words that mark a relevant sentence. In a real system, the lead model writes these briefs, and the worker model decides what's relevant by reading.

The budget. MAX_SEARCHES is shared by the whole team through the board. A worker that runs out of budget stops searching, even if its brief listed more queries. Seven searches were used out of eight.

Shared state with ownership. Each worker writes only board["findings"][its topic], so parallel workers can never overwrite each other. The search counter and the set of documents read are shared too; with real parallel workers, the counter would need the version check from lesson 5.

The writer. The lead keeps each fact once, under the first topic that found it, so a fact found by two workers isn't repeated.

The checker. The writer made a typical mistake: it attributed the tree-shade finding to the cool-roofs pilot. The citation checker looked for that sentence in the cited document, didn't find it, and removed the claim. The tree-survey version of the same fact, correctly cited, stayed in.

The report ends with a record of the work: searches used, documents read and documents never cited. The bus timetable was never even returned by a search, which shows the search tool did its job.

With real models

To make the workers real agents, replace researcher() with a model in a tool-calling loop (the same loop as in the Introduction to AI Agents and Tool Calling courses). The worker gets the two tools and its brief, and must return findings as JSON with exact quotes:

import json
import anthropic

client = anthropic.Anthropic()          # reads ANTHROPIC_API_KEY from the environment

WORKER_TOOLS = [
    {"name": "search", "description": "Search the document library. Returns up to 3 document IDs.",
     "input_schema": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}},
    {"name": "read_document", "description": "Read a document's full text by its ID.",
     "input_schema": {"type": "object", "properties": {"doc_id": {"type": "string"}}, "required": ["doc_id"]}},
]
FUNCTIONS = {"search": lambda query: search(query),               # the tools from the demo above
             "read_document": lambda doc_id: DOCS.get(doc_id, "No such document")}

WORKER_PROMPT = """You are a research worker. Objective: {topic}.
Use search and read_document (at most {max_searches} searches). When done, answer with JSON only:
a list of findings, each {{"claim": "...", "quote": "exact sentence from the document", "doc_id": "..."}}.
Only include facts you read in a document. Copy each quote exactly."""

def run_worker(brief, max_steps=10):
    messages = [{"role": "user", "content": WORKER_PROMPT.format(
        topic=brief["topic"], max_searches=len(brief["queries"]) + 1)}]
    for _ in range(max_steps):
        response = client.messages.create(model="MODEL_NAME", max_tokens=1500,
                                          tools=WORKER_TOOLS, messages=messages)
        messages.append({"role": "assistant", "content": response.content})
        if response.stop_reason != "tool_use":
            text = "".join(b.text for b in response.content if b.type == "text")
            return json.loads(text)                 # the lead still checks every quote afterwards
        results = [{"type": "tool_result", "tool_use_id": b.id,
                    "content": json.dumps(FUNCTIONS[b.name](**b.input))}
                   for b in response.content if b.type == "tool_use"]
        messages.append({"role": "user", "content": results})
    return []                                       # step limit: report no findings, never guesses

Keep the rest of the system as it is. The citation checker stays in code: real models occasionally misquote or misattribute, which is exactly what it catches. In production you would also run the workers in parallel (for example with Python's asyncio), cap each worker's tool calls in code, and log every brief, tool call and result so you can trace any claim back to the search that found it.

Common mistakes

Practice exercise

Build the citation checker: a claim only stays in the report if the document it cites really contains its quote.

Your solutionPython
DOCS = {"d1": "Tree shade cooled streets by 4°C. New trees need 10 years.",
        "d2": "Cool roofs cut indoor temperatures by 2°C."}
claims = [
    {"quote": "Tree shade cooled streets by 4°C.", "doc": "d1"},
    {"quote": "Cool roofs cut street temperatures by 4°C.", "doc": "d2"},
    {"quote": "Cool roofs cut indoor temperatures by 2°C.", "doc": "d9"},
]

# For each claim, print "supported" if its doc exists and contains the quote exactly,
# otherwise print "UNSUPPORTED: " followed by the quote.
Knowledge check

In the project, why was the claim about trees cooling streets by 4°C removed from the cool roofs section?

Summary

  • A lead agent plans topics and briefs; workers search and read within a shared budget.
  • Findings go into shared state with ownership, so parallel workers can't overwrite each other.
  • The writer builds claims with citations from findings only, each fact once.
  • A citation checker removes claims whose sources don't contain them.
  • Real model-driven workers slot in without changing the checks.

Course complete

You can now decide when several agents are worth their cost, build lead agents that brief and check workers, pass conversations between specialists with handoffs, design reliable messages between agents, share state without losing updates, and combine all of it into a research system whose every claim is checked against its source. Next, the AI Agent Evaluation course shows how to measure whether agents like these are doing a good job.

Finished reading? Tick it off to track your progress.