GyaanStack. Blog

Articles / agentsprojects

CrewAI market research agents: hierarchical crews, typed reports and a claim check

A CrewAI market research crew run both sequential and hierarchical, with a Pydantic report, a citation guardrail and an eval that flags unsupported claims.

By Raghunath · · 21 min read

A market research crew is the standard CrewAI demo: a researcher, a competitor analyst and a writer, run in order, ending in a report that reads well. The weak spot is the report. Nothing in that demo tells you which sentences came from your data and which ones the model made up, and a report with one invented market share number is worse than no report.

This post builds that crew on CrewAI 1.15.44 and spends its time on the parts the usual tutorial skips. It runs the same three tasks under Process.sequential and Process.hierarchical and shows what the manager agent costs in model calls. The report comes back as a Pydantic model where every claim is tagged fact or inference and carries source IDs. A task guardrail rejects uncited facts, and an eval after the run checks every number in the report against the source it cites.

Two earlier posts cover ground this one skips. The multi-agent web scraper with CrewAI explains output_pydantic, guardrail retries and a BaseLLM stub from first principles. The agent frameworks comparison covers when CrewAI is the right pick at all.

The design#

The research data is a local fixture of five short source notes about a fictional market (office coffee subscriptions in Bangalore). The companies and numbers in it are invented for this post. Nothing is scraped. In a real project those notes would come from your own search or retrieval step, which is where citations start; see AI agent web search with citations for that half.

                     sources.json (S1..S5)
                            |
   SEQUENTIAL               |              HIERARCHICAL
                            v
  research ---> competitors ---> report     Crew Manager (manager_llm)
  (researcher)  (analyst)        (writer)     |  runs every task itself
                                  |           |  "Delegate work to coworker"
                       output_pydantic        v
                       + guardrail       researcher / analyst / writer
                                  |           |
                                  v           v
                         MarketReport (claims with kind + source_ids)
                                  |
                                  v
                eval: numbers in each claim vs. the cited source text

The guardrail and the eval do different jobs. The guardrail runs inside the crew, so it has to be cheap and deterministic: valid JSON, every fact has a source ID, every ID exists. The eval runs after the crew finishes and checks content: does the number in the sentence appear in the source it points to. Moving the content check into the guardrail is possible, but then a wrong number triggers a retry loop, and a small model asked to "fix" a number often picks a different wrong one. Failing the report and showing a person the bad line is the safer default.

Setup#

CrewAI's PyPI metadata on 23 November 2026 lists version 1.15.44 with Requires-Python >=3.10, <3.14. If your default python3 is 3.14 or newer, pip refuses to install it. uv fetches a matching interpreter for you:

uv venv -p 3.12 .venv
uv pip install -p .venv/bin/python crewai==1.15.44
.venv/bin/python -c "import crewai; print(crewai.__version__)"   # 1.15.44

The fixture is five JSON objects. Two of them are competitors, three are survey or trend notes:

[
 {"id": "S1", "kind": "survey", "text": "A survey of 412 office managers in Bangalore found that 61% of offices with 50 to 200 staff pay for coffee or tea for employees. Of those, 38% said they would switch suppliers for a lower monthly price."},
 {"id": "S2", "kind": "competitor", "name": "BeanDesk", "text": "BeanDesk rents bean-to-cup machines to offices at Rs 9,500 per month including 20 kg of beans. It serves about 300 offices, mostly in Whitefield and Outer Ring Road."},
 {"id": "S3", "kind": "competitor", "name": "CupRoute", "text": "CupRoute installs tea and coffee dispensers and charges per cup, starting at Rs 12 per cup with a 2,000-cup monthly minimum."},
 {"id": "S4", "kind": "trend", "text": "Hybrid work means many offices are full only on Tuesday to Thursday. Office managers in the survey reported average occupancy of 55% across a five-day week."},
 {"id": "S5", "kind": "trend", "text": "Filter coffee kits with a local roaster brand were the most requested change, named by 27% of surveyed office managers."}
]

The report schema and the guardrail#

The schema is where the anti-hallucination work starts. A Claim has a kind that is either fact or inference, and a list of source_ids. That one field changes what the writer has to do: it can still offer an opinion, but it has to label it as one, and it cannot state a number as fact without pointing at a note.

import json
import os
from typing import Literal

os.environ.setdefault("CREWAI_DISABLE_TELEMETRY", "true")
os.environ.setdefault("CREWAI_TRACING_ENABLED", "false")

from crewai import Agent, Crew, Process, Task
from pydantic import BaseModel, Field

SOURCES = json.load(open(os.path.join(os.path.dirname(__file__), "sources.json")))
SOURCE_IDS = {s["id"] for s in SOURCES}


class Claim(BaseModel):
    text: str = Field(description="One sentence")
    kind: Literal["fact", "inference"]
    source_ids: list[str] = Field(default_factory=list,
                                  description="IDs like S1; required for facts")


class Competitor(BaseModel):
    name: str
    pricing: str
    source_id: str


class MarketReport(BaseModel):
    market: str
    claims: list[Claim]
    competitors: list[Competitor]
    recommendation: str


def report_guardrail(output):
    """Cheap structural checks. Content checks happen in the eval afterwards."""
    try:
        report = MarketReport.model_validate_json(output.raw)
    except ValueError as exc:
        return False, f"Output is not valid MarketReport JSON: {exc}"
    for c in report.claims:
        if c.kind == "fact" and not c.source_ids:
            return False, f"UNCITED fact: '{c.text}'. Cite a source ID or mark it inference."
        unknown = set(c.source_ids) - SOURCE_IDS
        if unknown:
            return False, f"Unknown source IDs {sorted(unknown)}. Valid: {sorted(SOURCE_IDS)}"
    if len(report.competitors) < 2:
        return False, "List at least two competitors."
    return True, output

The guardrail parses output.raw rather than reading output.pydantic, for the reason the scraper post found: in 1.15.44 the guardrail sees the output before the Pydantic conversion. CrewAI sends the error string back to the agent as its retry instruction (the Tasks docs describe the retry loop and guardrail_max_retries). "UNCITED fact: '...'. Cite a source ID or mark it inference" tells the model the two acceptable fixes. "Invalid output" tells it nothing.

Agents and tasks#

Three agents, each with delegation off. The tasks take the fixture through {sources} interpolation, and the report task gets the other two as context:

def build_agents(llm):
    common = dict(llm=llm, allow_delegation=False, verbose=False)
    researcher = Agent(
        role="Market researcher",
        goal="Pull customer needs and market facts out of the source notes",
        backstory="You quote numbers exactly as written and tag each with its source ID.",
        **common)
    analyst = Agent(
        role="Competitor analyst",
        goal="Describe each competitor's offer and price from the source notes",
        backstory="You never guess a price. If a note has no price, you say so.",
        **common)
    writer = Agent(
        role="Report writer",
        goal="Turn findings into a short report a founder can act on",
        backstory="Every factual sentence carries a source ID. Opinions are marked inference.",
        **common)
    return researcher, analyst, writer


def build_tasks(researcher, analyst, writer, assign=True):
    def who(agent):
        return agent if assign else None

    research = Task(
        description=("Market: {market}.\nSource notes as JSON:\n<sources>{sources}</sources>\n"
                     "List the customer needs and market facts, one line each, "
                     "ending with the source ID in brackets."),
        expected_output="Bullet list of findings, each ending with [S#]",
        agent=who(researcher))
    competitors = Task(
        description=("Source notes as JSON:\n<sources>{sources}</sources>\n"
                     "For each competitor, give its offer and price with the source ID."),
        expected_output="Bullet list: competitor, offer, price, [S#]",
        agent=who(analyst))
    report = Task(
        description=("Write the market report for {market} from the findings and the "
                     "competitor list. Facts must cite source IDs from the notes. "
                     "Anything you conclude yourself is kind=inference."),
        expected_output="A MarketReport JSON object",
        agent=who(writer),
        context=[research, competitors],
        output_pydantic=MarketReport,
        guardrail=report_guardrail,
        guardrail_max_retries=2)
    return [research, competitors, report]


def build_crew(llm, process="sequential", manager_llm=None):
    agents = build_agents(llm)
    if process == "sequential":
        return Crew(agents=list(agents), tasks=build_tasks(*agents),
                    process=Process.sequential, verbose=False)
    # Hierarchical: tasks have no fixed agent, the manager picks a coworker.
    return Crew(agents=list(agents), tasks=build_tasks(*agents, assign=False),
                process=Process.hierarchical, manager_llm=manager_llm or llm,
                verbose=False)


INPUTS = {"market": "office coffee subscriptions in Bangalore",
          "sources": json.dumps(SOURCES)}

The only code difference between the two processes is process=, manager_llm= and whether tasks have an agent. The behaviour difference is larger.

What hierarchical mode does inside#

The Processes docs and the hierarchical process guide describe a manager that plans, delegates and validates. Reading crew.py in 1.15.44 gives the precise version:

  1. The crew refuses to build without manager_llm or manager_agent. With manager_llm, CrewAI creates an agent with role "Crew Manager" and a stock backstory. For your own role and prompt, pass a custom manager agent instead; it must not have tools of its own and must not also appear in agents.
  2. Every task executes as the manager. _get_agent_to_use returns self.manager_agent for every task in hierarchical mode, which is why tasks_output[i].agent reads "Crew Manager" in the output below.
  3. The manager gets two tools, "Delegate work to coworker" and "Ask question to coworker". If a task has an agent set, the tools only list that one agent. If it has none, they list the whole crew and the manager picks.
  4. A delegation creates a fresh Task for the coworker with your manager's wording as the description and a stock expected output ("Your best answer to your coworker asking you this, accounting for the context shared."). Your output_pydantic and guardrail are not copied onto it. They apply to the manager's final answer for the original task.

Point 4 is the risk for this crew. The coworker never sees the MarketReport schema unless the manager's delegation message happens to include it, and the guardrail feedback on a retry reaches the writer only if the manager passes it on. A manager that paraphrases the task and leaves out the schema produces a report the guardrail rejects, and the retry goes back through the same manager.

The stub model#

To show the call pattern without a key, the run uses a BaseLLM subclass that answers by role. The scraper post walks through how a custom LLM plugs in, so only the new part is shown here: the manager. It emits the ReAct text CrewAI parses, delegates to a coworker chosen from the task text, and once an observation comes back, returns it as the final answer.

    def _manager(self, messages, prompt):
        replied = not isinstance(messages, str) and any(
            m.get("role") == "assistant" for m in messages)
        if replied:
            # A coworker answered; pass its answer up as the task result.
            last = [m for m in messages if m.get("role") == "assistant"][-1]
            obs = str(last["content"]).split("Observation:", 1)[-1].strip()
            return "Thought: my coworker finished\nFinal Answer: " + obs
        task = prompt.rsplit("Current Task:", 1)[1].split("This is the expected")[0]
        if "<sources>" not in task:
            who = "Report writer"
        elif "competitor" in task.split("</sources>")[-1]:
            who = "Competitor analyst"
        else:
            who = "Market researcher"
        ctx = prompt.split("This is the context you're working with:", 1)[-1]
        ctx = ctx.split("Begin!")[0] if "This is the context" in prompt else ""
        args = json.dumps({"task": task.strip(), "context": ctx.strip(), "coworker": who})
        return ("Thought: delegate this\nAction: Delegate work to coworker\n"
                f"Action Input: {args}")

The first version of this stub had two bugs. It checked for the string "Observation:" in the prompt to detect a tool result, but CrewAI's ReAct instructions contain that word, so the manager "finished" on its first call and returned the instruction text as the report. And CrewAI appends the tool result to the assistant message, not to a new user message; the last user message is a nudge that says "Analyze the tool result". The working version looks for an assistant turn and reads the observation from it.

The writer stub plants two mistakes on purpose. On its first try one fact has no source ID. And one claim says 48% of paying offices would switch supplier, cited to S1, which says 38%. The first mistake is the kind the guardrail exists for. The second is cited, well-formed and wrong, the kind a guardrail passes.

Running both processes#

run_stub.py builds the crew, counts model calls by role and runs the eval:

import sys
import time

from eval_report import evaluate, print_eval
from market_crew import INPUTS, build_crew
from stub_llm import StubLLM

process = sys.argv[1] if len(sys.argv) > 1 else "sequential"
llm = StubLLM(model="stub")
crew = build_crew(llm, process)
t = time.time()
result = crew.kickoff(inputs=INPUTS)
print(f"process={process}  model calls={len(llm.log)}  wall={time.time() - t:.1f}s")
print("calls by role:", {r: llm.log.count(r) for r in dict.fromkeys(llm.log)})
for i, out in enumerate(result.tasks_output):
    print(f"task {i + 1} ran as: {out.agent}")
print()
print_eval(evaluate(result.pydantic))

Sequential, with CrewAI's token-estimate warnings removed:

process=sequential  model calls=4  wall=0.4s
calls by role: {'Market researcher': 1, 'Competitor analyst': 1, 'Report writer': 2}
task 1 ran as: Market researcher
task 2 ran as: Competitor analyst
task 3 ran as: Report writer

ok   fact      S1     61% of Bangalore offices with 50 to 200 staff pay for staff coffee or 
FAIL fact      S1     48% of paying offices would switch supplier for a lower price.  numbers not in cited source: ['48']
ok   fact      S4     Average office occupancy is 55% across a five-day week.
ok   fact      S5     27% of office managers asked for filter coffee from a local roaster.
ok   inference S3,S4  Per-cup pricing suits offices that are full only three days a week.
ok   price     S2     BeanDesk: Rs 9,500 per month with 20 kg beans
ok   price     S3     CupRoute: from Rs 12 per cup, 2,000-cup minimum
1 unsupported of 7 checked

The writer ran twice. Its first report had the uncited filter coffee claim, the guardrail rejected it with the UNCITED message, and the retry added S5. The 48% claim went through the guardrail because it has a valid ID, and the eval caught it.

Hierarchical, same stub, same tasks:

process=hierarchical  model calls=12  wall=0.3s
calls by role: {'Crew Manager': 8, 'Market researcher': 1, 'Competitor analyst': 1, 'Report writer': 2}
task 1 ran as: Crew Manager
task 2 ran as: Crew Manager
task 3 ran as: Crew Manager

ok   fact      S1     61% of Bangalore offices with 50 to 200 staff pay for staff coffee or 
FAIL fact      S1     48% of paying offices would switch supplier for a lower price.  numbers not in cited source: ['48']
...
1 unsupported of 7 checked

The report is identical, and the call count tripled: 12 instead of 4. Each task costs the manager two calls (delegate, then accept), so three tasks are six calls, and the guardrail retry on the report sends the manager through the loop again for two more. That is the best case, with a manager that delegates correctly the first time and never asks a follow-up question. Each manager call also carries the full task text, the context and the tool instructions, so the prompt tokens grow faster than the call count.

With a fixed three-step pipeline, the manager adds cost and a place for things to go wrong, and gives nothing back. Hierarchical mode pays off when the task list is not a fixed pipeline: a manager that can send a vague request to whichever specialist fits, or ask the analyst a follow-up before accepting an answer. For a fixed order, use sequential and put the checking in code.

The eval for unsupported claims#

The eval is plain Python and runs on the MarketReport the crew returns:

import re

from market_crew import SOURCES, MarketReport

TEXT = {s["id"]: s["text"] for s in SOURCES}
NUM = re.compile(r"\d[\d,]*(?:\.\d+)?")


def numbers(s):
    return {n.replace(",", "") for n in NUM.findall(s)} - {""}


def check_claim(text, source_ids):
    """A number in a claim must appear in one of the sources it cites."""
    cited = " ".join(TEXT.get(i, "") for i in source_ids)
    missing = numbers(text) - numbers(cited)
    return sorted(missing)


def evaluate(report: MarketReport):
    rows = []
    for c in report.claims:
        missing = check_claim(c.text, c.source_ids) if c.kind == "fact" else []
        loose = sorted(numbers(c.text)) if c.kind == "inference" else []
        status = "FAIL" if missing else ("WARN" if loose else "ok")
        rows.append((status, c.kind, ",".join(c.source_ids) or "-", c.text, missing or loose))
    for comp in report.competitors:
        missing = check_claim(comp.pricing, [comp.source_id])
        rows.append(("FAIL" if missing else "ok", "price", comp.source_id,
                     f"{comp.name}: {comp.pricing}", missing))
    return rows

print_eval formats the rows and returns the FAIL count, so a CI job can exit non-zero on any unsupported number. Inferences that contain numbers get a WARN, because "a 20% price cut would win half the market" labelled as inference is still a number someone will quote.

This check is narrow on purpose. Numbers are where market reports do damage, and checking them needs no model. It misses a claim with no numbers that the source does not support ("BeanDesk is losing customers"), and it passes a number that appears in the source in a different role, such as citing S1's "200" as a customer count. The next layer is an LLM judge that sees one claim and its cited notes and answers supported or not; the LLM-as-a-judge post builds one, and detecting LLM hallucinations covers the other methods. Keep the regex check in front of the judge anyway. It is free, it never disagrees with itself, and it catches the most expensive kind of error.

The guardrail and eval have their own tests in test_crew.py, with no crew involved:

fact = {"text": "61% pay for coffee.", "kind": "fact"}
assert report_guardrail(report([{**fact, "source_ids": ["S1"]}]))[0] is True
ok, msg = report_guardrail(report([{**fact, "source_ids": []}]))
assert not ok and msg.startswith("UNCITED")
ok, msg = report_guardrail(report([{**fact, "source_ids": ["S9"]}]))
assert not ok and "Unknown source IDs ['S9']" in msg
ok, msg = report_guardrail(SimpleNamespace(raw="Here is your report: {...}"))
assert not ok and "not valid MarketReport JSON" in msg

assert check_claim("38% would switch for a lower price.", ["S1"]) == []
assert check_claim("48% would switch for a lower price.", ["S1"]) == ["48"]
assert check_claim("BeanDesk charges Rs 9,500 a month.", ["S3"]) == ["9500"]  # wrong source
print("7 checks passed")

report() is a small helper that wraps claims in a valid MarketReport JSON string. The last assert is the one people forget: a correct number cited to the wrong source is still an unsupported claim, because a reader who checks S3 will not find it.

With a real local model#

run_ollama.py is run_stub.py with the stub swapped for a real model, served by a local Ollama:

from crewai import LLM

llm = LLM(model="ollama/qwen3:4b-instruct", base_url="http://localhost:11434",
          temperature=0.1)
crew = build_crew(llm, process)
result = crew.kickoff(inputs=INPUTS)
u = result.token_usage

Run ollama pull qwen3:4b-instruct first. The sequential run on a laptop that was serving other jobs at the same time:

process=sequential  requests=9  prompt_tokens=6048  completion_tokens=2622  wall=185s
task 1 ran as: Market researcher
task 2 ran as: Competitor analyst
task 3 ran as: Report writer

ok   fact      S1     61% of offices with 50 to 200 staff in Bangalore pay for coffee or tea
ok   fact      S1     38% of offices that pay for coffee or tea would switch suppliers for a
ok   fact      S2     BeanDesk rents bean-to-cup machines to offices including 20 kg of bean
ok   fact      S3     CupRoute installs tea and coffee dispensers and charges per cup, start
ok   fact      S4     Due to hybrid work, offices in Bangalore have an average occupancy of 
ok   inference -      Filter coffee kits with a local roaster brand are a top requested chan
ok   price     S2     BeanDesk: Rs 9,500 per month
ok   price     S3     CupRoute: Starting at Rs 12 per cup with a 2,000-cup monthly minimum
0 unsupported of 8 checked

Every number checks out, and the 4B model labelled its one leap ("indicating a preference for locally sourced, artisanal coffee products") as inference. The crew made 9 requests for 3 tasks, as reported by result.token_usage; the script does not log what the extra six were, so read that as "more than one call per task" and not as a breakdown.

The saved report_sequential.json shows what the eval does not look at. The model wrote a paragraph into the market field, which was meant to be a name, and it contains "there is a clear preference for local, artisanal coffee products", a stronger version of the claim it had just labelled inference. The recommendation calls Whitefield and Outer Ring Road "high-density areas"; S2 only says BeanDesk's customers are mostly there. Neither sentence is a Claim, so neither is checked. Two fixes: give free-text fields a max_length and a description that says "name only", and run the claim checker (or the LLM judge) over every free-text field, not only the claims list.

The hierarchical run with the same model as worker and manager:

process=hierarchical  requests=32  prompt_tokens=33748  completion_tokens=11292  wall=349s
task 1 ran as: Crew Manager
task 2 ran as: Crew Manager
task 3 ran as: Crew Manager

ok   fact      S1     61% of offices with 50 to 200 staff in Bangalore pay for coffee or tea
ok   fact      S1     38% of offices with 50 to 200 staff indicated they would switch suppli
ok   fact      S2     BeanDesk rents bean-to-cup machines at Rs 9,500 per month, including 2
ok   fact      S3     CupRoute installs tea and coffee dispensers and charges per cup, start
ok   fact      S4     Due to hybrid work patterns, offices are full only on Tuesday to Thurs
ok   fact      S5     Filter coffee kits with a local roaster brand are the most requested c
ok   price     S2     BeanDesk: Rs 9,500 per month, including 20 kg of beans
ok   price     S3     CupRoute: Rs 12 per cup (minimum 2,000 cups per month)
0 unsupported of 8 checked

Side by side, from the two runs:

Sequential Hierarchical
Requests 9 32
Prompt tokens 6,048 33,748
Completion tokens 2,622 11,292
Wall time 185 s 349 s
Numbers flagged by the eval 0 0

Hierarchical used about 5.6 times the prompt tokens for a report of the same shape. Local tokens cost only time; on a paid API the same ratio applies to the bill. The manager did delegate and the schema survived this time, so point 4 above did not bite on this run. One run of each is not a benchmark, and the wall times include a busy machine.

The hierarchical report also has an error the eval missed. "38% of offices with 50 to 200 staff indicated they would switch suppliers" passed the eval, and it is wrong. S1 says 38% of the offices that already pay, which is about 23% of all offices (0.61 x 0.38). The number is in the source, the citation is right, and the meaning changed. A regex check cannot see that; a judge that reads the claim next to S1 can. Run both layers.

Failure modes#

  • Raw text around the JSON. A model can write "Here is the report:" before the object. The guardrail turns that into a retry with a parse error message. If it happens on every run, lower the temperature and put a one-line example object in expected_output.
  • Manager answers the task itself. In hierarchical mode a manager can skip delegation and write the report from its own knowledge, with no tie to the fixture at all. The eval flags its numbers, but only if it bothered to cite IDs. Count delegations per task (the stub's role log does this) and fail the run when a task had none.
  • Schema lost in delegation. Covered above: the coworker's delegated task carries no output_pydantic. Repeat the schema in the task description, or use sequential mode for the typed task.
  • Retry loops that do not converge. guardrail_max_retries=2 means at most three writer attempts, and CrewAI raises an exception after the last failure. Catch it and save the last raw output for a person to read, instead of losing the whole run.
  • Context window. CrewAI warned on this run that it does not know qwen3's window and assumes 8,192 tokens. The context Ollama actually loads depends on its own settings and can be smaller than that; ollama ps shows it (both 4,096 and 32,768 appeared on this machine during the session, from different loads). Five short notes fit easily. Fifty do not, and the manager's prompts are the largest because they carry everything. Set context_window_size on the LLM and the Ollama num_ctx to the same value.

Sources#

Found this useful? You can buy me a coffee or support with any amount. It pays for hosting and keeps new articles coming.