Lesson 5 of 5 · CrewAI
Project: Content Research Crew
Build a CrewAI crew that researches, writes and edits a blog article: a researcher with a search tool, a writer with checked citations and a structured editor.
- 6 min read
- Intermediate
- Reviewed
- Design a crew of three agents with distinct jobs
- Give the researcher a search tool that returns sources
- Check the writer's citations with a guardrail that sends bad drafts back
- Return a structured, saved final article
- Know how to extend the crew for production
What you'll build
A content crew for Velamuvi Bikes' blog that writes “How to choose your first city e-bike” from the shop's buying-guide notes. Every claim must carry a source, and only sources that really exist are allowed.
| Agent | Job | Tools and checks |
|---|---|---|
| Researcher | Find the key facts, each with its [source-id] | A search tool over the buying-guide notes |
| Writer | Turn the facts into a friendly article of about 100 words | Guardrail: every citation must exist |
| Editor | Tighten the text, add a title, list the sources | Structured output (Article), guardrail: at most 150 words, saved to a file |
The pipeline in plain Python
First, the shape of the run with stand-ins for the agents. The writer's first draft cites a source that doesn't exist, and the guardrail sends it back:
import re
# The content crew's pipeline in plain Python: research -> write (with a citation guardrail) -> edit.
LIBRARY = {
"range-guide": "Most city e-bikes travel 40 to 80 km per charge.",
"fit-guide": "Choose the frame size from your height and test-ride if you can.",
"budget-guide": "Good city e-bikes start around 1,500 euros.",
}
def researcher(topic): # stand-in: search notes, keep facts with sources
return [f"{text} [{sid}]" for sid, text in LIBRARY.items()]
drafts = iter([
"Range matters [range-guide]. Prices vary [price-survey].", # cites a made-up source
"Most city e-bikes do 40 to 80 km per charge [range-guide]. Pick your frame by height "
"[fit-guide], and expect to pay from about 1,500 euros [budget-guide].",
])
def writer(facts, feedback=None):
if feedback:
print(f" writer gets feedback: {feedback}")
return next(drafts)
def citations_exist(text):
unknown = sorted(set(re.findall(r"\[([\w-]+)\]", text)) - set(LIBRARY))
return (False, f"Unknown sources {unknown}") if unknown else (True, text)
def editor(text): # stand-in: add a title, list the sources
return {"title": "How to choose your first city e-bike", "body": text,
"sources": sorted(set(re.findall(r"\[([\w-]+)\]", text)))}
facts = researcher("a first city e-bike")
print(f"research: {len(facts)} facts")
feedback = None
for attempt in range(1, 4):
draft = writer(facts, feedback)
ok, feedback = citations_exist(draft)
print(f"write attempt {attempt}: {'accepted' if ok else 'rejected'}")
if ok:
break
article = editor(draft)
print(article["title"], "|", len(article["body"].split()), "words |", article["sources"])The CrewAI version
import re
from pydantic import BaseModel
from crewai import LLM, Agent, Crew, Process, Task, TaskOutput
from crewai.tools import tool
# ---------- A small library of notes the researcher can search (sample content) ----------
LIBRARY = {
"range-guide": "Most city e-bikes travel 40 to 80 km per charge; hills, cold weather and heavy loads reduce range.",
"fit-guide": "Choose the frame size from your height: test-ride if you can, and check you can put a foot down at stops.",
"motor-guide": "Hub motors are simpler and cheaper; mid-drive motors climb hills better and feel more natural.",
"budget-guide": "Good city e-bikes start around 1,500 euros; budget about 100 euros a year for servicing.",
"law-guide": "In the EU, e-bikes are limited to 25 km/h of motor assistance and 250 W of continuous power.",
}
@tool("Search buying guides")
def search_library(query: str) -> str:
"""Search the shop's buying-guide notes. Returns up to 2 notes, each with its [source-id]."""
q = set(re.findall(r"[a-z]+", query.lower()))
ranked = sorted(LIBRARY, key=lambda k: -len(q & set(re.findall(r"[a-z]+", LIBRARY[k].lower()))))
return "\n".join(f"[{k}] {LIBRARY[k]}" for k in ranked[:2])
def citations_exist(output: TaskOutput) -> tuple[bool, str]:
unknown = sorted(set(re.findall(r"\[([\w-]+)\]", output.raw)) - set(LIBRARY))
return (False, f"Unknown sources {unknown}. Cite only sources from the research.") if unknown else (True, output.raw)
class Article(BaseModel):
title: str
body: str
sources: list[str]
def under_150_words(output: TaskOutput) -> tuple[bool, str]:
words = len(output.pydantic.body.split()) if output.pydantic else len(output.raw.split())
return (True, output.raw) if words <= 150 else (False, f"{words} words; cut to 150.")
# ---------- The crew ----------
llm = LLM(model="anthropic/MODEL_NAME")
researcher = Agent(role="Researcher", goal="Find accurate facts in the buying guides, with sources",
backstory="You never state a fact without its [source-id].", tools=[search_library], llm=llm)
writer = Agent(role="Writer", goal="Write clear, friendly articles for first-time e-bike buyers",
backstory="You write the Velamuvi Bikes blog.", llm=llm)
editor = Agent(role="Editor", goal="Make articles accurate, short and easy to read",
backstory="You check every claim against its source before publishing.", llm=llm)
research = Task(description="Research the most important things to consider when choosing {topic}. "
"Use the search tool for range, fit, motors and budget.",
expected_output="5 to 8 facts, each followed by its [source-id].", agent=researcher)
write = Task(description="Write a blog article about choosing {topic}, using only the research.",
expected_output="An article of about 100 words that keeps the [source-id] citations.",
agent=writer, context=[research], guardrail=citations_exist)
edit = Task(description="Edit the article: fix unclear sentences, keep every citation, add a title.",
expected_output="The final article with a title, a body and the list of sources used.",
agent=editor, context=[write], output_pydantic=Article, guardrail=under_150_words,
output_file="first-e-bike.json")
crew = Crew(agents=[researcher, writer, editor], tasks=[research, write, edit], process=Process.sequential)
result = crew.kickoff(inputs={"topic": "a first city e-bike"})
article = result.pydantic
print(article.title)
print(f"{len(article.body.split())} words, sources: {article.sources}")How to choose your first city e-bike 74 words, sources: ['range-guide', 'fit-guide', 'motor-guide', 'budget-guide']
How it works
- Research with sources. The researcher's only tool searches the notes and returns each match with its
[source-id]. Its backstory (“You never state a fact without its [source-id]”) and its task's expected output both insist on sources. In the test run, it searched twice, once for range and fit and once for motors and budget, then listed its facts. - Writing with a guardrail. The writer sees only the research, through
context=[research]. Its first draft cited[price-survey], which isn't in the library;citations_existrejected it with that exact problem, and the second draft passed. - Editing into structure. The editor receives the approved draft, returns an
Articlewith a title, body and source list, is held to 150 words by a second guardrail, and its result is saved tofirst-e-bike.jsonbyoutput_file. - Inputs.
{topic}in the task descriptions makes the crew reusable: change the input to write about cargo bikes or folding bikes.
Common mistakes
Write the writer task's guardrail: every article must cite sources, and only sources the researcher could have found.
import re
LIBRARY = {"range-guide", "fit-guide", "budget-guide"}
def citations_exist(text):
# Find the [source-id] citations with re.findall(r"\[([\w-]+)\]", text).
# If the text cites no sources at all, return (False, "No sources cited").
# If any cited ID is not in LIBRARY, return (False, "Unknown: <sorted list>").
# Otherwise return (True, text).
pass
for t in ["Range is 40-80 km [range-guide].", "E-bikes are great!", "Fit first [fit-guide] [shop-blog]."]:
print(citations_exist(t))
Why does the writer's task have a guardrail that checks citations?
Summary
- A researcher with a search tool, a writer and an editor each do one job.
- Facts travel with
[source-id]citations from search to final article. - A guardrail on the writing task rejects unknown sources; another keeps the edited article short.
- The editor returns a structured
Article, saved withoutput_file;{topic}makes the crew reusable.
Course complete
You can now build crews in CrewAI: define agents with roles, goals and backstories, write tasks with context, structured output and guardrails, give agents tools with caching and limits, choose sequential or hierarchical processes, control larger workflows with Flows, and combine it all into a research crew whose every claim carries a checked source.
Finished reading? Tick it off to track your progress.