Defining an Agent
An agent is a role, a goal and a backstory. We gave llama3 the same question with three personas: a plain assistant wrote 212 words, a teacher wrote a library comparison with no jargon, an expert brought in B-trees. The persona changes the style - but none of them kept to a word limit, wherever we put it.
What you will be able to do
- Write an agent’s role, goal and backstory so they change the output in the way you want
- Explain how CrewAI uses them (the system prompt)
- Measure the effect of a persona on real answers
- Know which rules a persona can and cannot enforce
- Know the most useful Agent settings and their defaults
- Run one agent on its own with agent.kickoff()
The idea, in plain English
In CrewAI, an agent is described like a person you hire: a job title (role), what they try to achieve (goal), and a little background (backstory). Lesson 6.1 showed that CrewAI turns these three into the system prompt.
So the question is practical: how much does the persona really change the answer? We tested it on llama3 - same question, three personas - and then tried to make the agent follow a simple rule: "at most 80 words".
CrewAI 1.15.27, llama3 on Ollama, temperature 0, telemetry off (Lesson 6.2).
Worked example: "Explain what a database index is" answered by three personas, then a word limit placed in four different places - all with llama3.
Plain assistant
A correct, textbook answer with bullet points and a summary. 212 words.
"Explain what a database index is." Real llama3 answers.
Words you will see in this lesson
The parts of an agent.
PersonaThe character an agent plays: its role, goal and backstory together.roleThe job title: "Friendly teacher for complete beginners".goalWhat the agent tries to achieve: "Explain technical ideas so that a 14-year-old understands them".backstoryBackground and habits: "You never use a technical word without explaining it."System promptThe first message to the model, describing who it is. CrewAI builds it from the persona.JargonTechnical words a beginner does not know: B-tree, full table scan.An everyday example: hiring someone to explain
You ask three people "what is a database index?":
- A helpful stranger gives a correct, textbook answer.
- A school teacher says "it is like the catalogue in a library".
- A senior engineer talks about B-trees and full table scans.
- All three are right. Who you ask decides HOW it is explained. But if you tell any of them "in 80 words", they may still talk longer - and so does a model.
Example 1 - three personas, one task
The same task for each agent. Only role, goal and backstory change. The script counts the words and looks for a few jargon words:
- plain: the smallest possible persona.
- teacher: a clear audience (a 14-year-old), clear habits (explain every technical word, use one comparison) and a limit (80 words).
- expert: a different audience (experienced engineers) and style (exact, technical terms).
import re
from crewai import LLM, Agent, Crew, Task
llm = LLM(model="ollama/llama3", base_url="http://localhost:11434", temperature=0)
PERSONAS = {
"plain": dict(
role="Assistant",
goal="Answer questions",
backstory="You are helpful.",
),
"teacher": dict(
role="Friendly teacher for complete beginners",
goal="Explain technical ideas so that a 14-year-old understands them",
backstory=("You teach school students who have never programmed. You never use a technical word "
"without explaining it. You always use one everyday comparison. You answer in at most 80 words."),
),
"expert": dict(
role="Senior database engineer",
goal="Give precise technical answers to other experienced engineers",
backstory="You review database designs every day. You are exact and concise, and you use the correct technical terms.",
),
}
JARGON = ["b-tree", "b+", "o(log", "o(n)", "query planner", "cardinality", "selectivity", "full table scan", "log n"]
for name, persona in PERSONAS.items():
agent = Agent(**persona, llm=llm)
task = Task(description="Explain what a database index is.",
expected_output="A short explanation.", agent=agent)
text = Crew(agents=[agent], tasks=[task]).kickoff().raw
words = len(text.split())
jargon = [j for j in JARGON if j in text.lower()]
print(f"=== {name}: {words} words | jargon: {jargon or 'none'}")
print(text)
print()=== plain: 212 words | jargon: none
A database index is a data structure that improves the speed of data retrieval by providing a quick way to locate specific data in a database. It is a pre-computed data structure that contains the location of specific data in a database, allowing the database to quickly locate and retrieve the desired data.
An index is created on a column or set of columns in a table, and it contains the following information:
* The values in the indexed column(s)
* The location of the corresponding rows in the table
When a query is executed, the database can quickly scan the index to find the desired data, rather than having to scan the entire table. This can significantly improve the performance of queries that involve filtering, sorting, or grouping data.
For example, if you have a table of customer information and you frequently query the table to find all customers who live in a specific city, you could create an index on the city column. This would allow the database to quickly locate the desired data without having to scan the entire table.
In summary, a database index is a pre-computed data structure that improves the speed of data retrieval by providing a quick way to locate specific data in a database.
=== teacher: 117 words | jargon: none
Imagine you have a huge library with millions of books. You want to find a specific book, but it takes forever because the books are not organized. A database index is like a special cataloging system that helps you find the book quickly.
In a database, an index is a special list that keeps track of where specific information is stored. It's like a map that says, "Hey, if you want to find all the books about science, go to shelf 3, section 2." This way, when you need to find specific information, the database can look at the index and quickly find what you're looking for, just like you would find your book in the library!
=== expert: 299 words | jargon: ['b-tree', 'full table scan']
A database index is a data structure that improves the speed and efficiency of data retrieval operations on a database. It is a pre-computed data structure that contains the key-value pairs of a table, sorted in a specific order, typically based on the table's primary key or a unique identifier. The primary purpose of an index is to enable the database to quickly locate specific data records without having to scan the entire table.
An index is essentially a shortcut that allows the database to quickly find the location of a specific data record without having to perform a full table scan. This is achieved by storing the key-value pairs in a separate data structure, such as a B-tree or a hash table, that can be quickly searched and retrieved.
There are several types of indexes, including:
... (three index types and their trade-offs)
In summary, a database index is a pre-computed data structure that improves the speed and efficiency of data retrieval operations by providing a shortcut for quickly locating specific data records.Reading Example 1
- The persona changed the STYLE completely: textbook, story, or expert detail. The teacher really avoided jargon and used a comparison - exactly what its backstory asked.
- The persona did NOT keep the length rule. The teacher was told "at most 80 words" and wrote 117. The expert was told "concise" and wrote the longest answer, 299 words.
- Specific habits worked ("use one everyday comparison"). Vague words did not ("concise").
- The plain assistant was not wrong - just generic. Without a persona you get the model’s default style.
Example 2 - where should a rule go?
Maybe the limit was in the wrong place. We tried four places, on four topics (a database index, an API, a variable, a loop):
- In the backstory (the agent’s habit).
- In the task description (the job).
- In expected_output (what the result should look like - Lesson 6.4).
- In all three at once.
from crewai import LLM, Agent, Crew, Task
llm = LLM(model="ollama/llama3", base_url="http://localhost:11434", temperature=0)
BASE = "You teach school students who have never programmed. You never use a technical word without explaining it. You always use one everyday comparison."
TOPICS = ["a database index", "an API", "a variable", "a loop"]
setups = {
"limit in backstory": (BASE + " You answer in at most 80 words.", "Explain {t}.", "A short explanation."),
"limit in description": (BASE, "Explain {t} in at most 80 words.", "A short explanation."),
"limit in expected_output": (BASE, "Explain {t}.", "At most 80 words. One paragraph."),
"limit in all three": (BASE + " You answer in at most 80 words.", "Explain {t} in at most 80 words.", "At most 80 words. One paragraph."),
}
for name, (backstory, desc, expected) in setups.items():
agent = Agent(role="Friendly teacher for complete beginners",
goal="Explain technical ideas so that a 14-year-old understands them",
backstory=backstory, llm=llm)
counts = []
for t in TOPICS:
task = Task(description=desc.format(t=t), expected_output=expected, agent=agent)
counts.append(len(Crew(agents=[agent], tasks=[task]).kickoff().raw.split()))
ok = sum(c <= 80 for c in counts)
print(f"{name:26} words: {counts} -> {ok} of {len(TOPICS)} within 80")limit in backstory words: [126, 158, 112, 225] -> 0 of 4 within 80
limit in description words: [88, 196, 111, 150] -> 0 of 4 within 80
limit in expected_output words: [81, 131, 90, 127] -> 0 of 4 within 80
limit in all three words: [78, 99, 111, 100] -> 1 of 4 within 80Reading Example 2
- No single place worked: 0 of 4 every time.
- expected_output came closest (81, 90 words) - the rule was right next to the task.
- Saying it three times helped a little: 1 of 4.
- Conclusion: a persona and a prompt SHAPE the answer; they do not ENFORCE a rule. For a rule that must hold, check it in code - Lesson 6.4 shows a guardrail that got 4 of 4.
Tip: Put style in the persona (who the agent is, how it explains). Put the job in the task (what to do now). Put hard rules in code.
Writing a good persona
What worked in our tests, and what did not:
roleSpecific job + audience: "Friendly teacher for complete beginners", not "Assistant".goalA result you can picture: "so that a 14-year-old understands them".backstoryConcrete habits: "You always use one everyday comparison." Avoid vague words like "concise" or "expert".KnowledgeA persona gives none. "Senior database engineer" knows only what the model knows (Lesson 6.1).RulesNot reliable in a persona. Check them in code.The most useful Agent settings
Agent has many settings. These are the ones you need now (defaults from CrewAI 1.15.27):
role, goal, backstoryRequired. The persona.llmOptional - but without it the default is gpt-4.1-mini, which needs an OpenAI key (Lesson 6.2).verbose=FalseTrue prints each step in boxes.tools=[]Tools the agent may use (Lesson 6.7).allow_delegation=FalseTrue lets the agent hand work to other agents (Lesson 6.6).max_iter=25The most think/act rounds the agent may take on one task.max_execution_time=NoneA time limit in seconds; none by default.memory=NoneRemembering across tasks and runs (Lesson 6.8).Example 3 - one agent, no crew
To try a persona quickly, run the agent on its own:
- agent.kickoff("question") - no Task and no Crew needed.
- It returns a LiteAgentOutput; .raw is the text.
- It printed "LiteAgent Started" and "LiteAgent Completed" boxes even with verbose=False.
- Useful for testing a persona before you put it in a crew.
from crewai import LLM, Agent
llm = LLM(model="ollama/llama3", base_url="http://localhost:11434", temperature=0)
teacher = Agent(
role="Friendly teacher for complete beginners",
goal="Explain technical ideas so that a 14-year-old understands them",
backstory="You never use a technical word without explaining it. You always use one everyday comparison.",
llm=llm,
)
result = teacher.kickoff("What is a variable in programming? Two sentences.") # no Task, no Crew
print(type(result).__name__)
print(result.raw)╭──────────────────────────── 🤖 LiteAgent Started ────────────────────────────╮
│ LiteAgent Started │
│ Role: Friendly teacher for complete beginners │
│ Status: In Progress │
╰──────────────────────────────────────────────────────────────────────────────╯
...
LiteAgentOutput
So, you know how you have a special box at home where you keep your favorite toys, and you can put different toys in it depending on the day? A variable in programming is like that special box, but instead of toys, it's a container that can hold different values or "toys" (like numbers or words) at different times.
╭─────────────────────────── ✅ LiteAgent Completed ───────────────────────────╮
...The recipe
- 1. role: a specific job title and audience.
- 2. goal: a result you can picture.
- 3. backstory: two or three concrete habits.
- 4. llm=your local model - always.
- 5. Test the persona alone with agent.kickoff() on a few questions.
- 6. Do not trust it with hard rules - check those in code (Lesson 6.4).
Agents at a glance
CreateThree required fields.
Agent(role="...", goal="...", backstory="...", llm=llm)
Run aloneNo task, no crew.
agent.kickoff("question").rawSee the stepsPrint boxes.
Agent(..., verbose=True)
Limit roundsDefault 25.
Agent(..., max_iter=5)
Limit timeSeconds.
Agent(..., max_execution_time=60)
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Write a "patient grandmother who explains computers" persona and ask it what Wi-Fi is.”
“Replace "You are exact and concise" with "You answer in 3 bullet points." Does the expert follow it?”
“Run personas.py with gemma3. Do the personas change the style in the same way?”
“Change the teacher’s goal from a 14-year-old to a university student. What changes?”
What usually goes wrong
"Assistant / Answer questions / You are helpful" gives the model’s default style.
✗ role="Assistant"✓ role="Friendly teacher for complete beginners""Concise" produced 299 words. Use concrete habits instead.
Our 80-word limit was ignored 4 of 4 times. Check rules in code.
A role does not add facts. Give sources or tools.
Key points
- An agent is role + goal + backstory (+ llm); CrewAI turns them into the system prompt.
- A persona changes style strongly: textbook (212 words), library story with no jargon, expert detail with B-trees.
- Concrete habits ("use one everyday comparison") worked; vague words ("concise" -> 299 words) did not.
- A word limit was ignored wherever we put it (best: 1 of 4) - enforce rules in code.
- agent.kickoff("...") runs one agent without a task or crew - good for testing a persona.
Quick check before you move on
Quiz
- 1.
The "exact and concise" expert wrote 299 words. Why?
- 2.
Where did the word limit work best, and how well?
- 3.
What does a persona NOT give an agent?
- 4.
What happens if you leave out llm=?
Interview questions
How do role, goal and backstory affect a CrewAI agent?
They are compiled into the system prompt, so they shape tone, depth, vocabulary and approach. Concrete behavioural instructions work best; they do not add knowledge or guarantee constraints.
How do you make an agent follow a hard constraint like a length limit?
State it clearly in the task’s expected output, but enforce it in code - a guardrail or validation that rejects and retries, or post-processes the output.
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...