15.3 C
Canberra
Sunday, October 26, 2025

Structuring Inputs & Outputs in Multi Agent methods Utilizing CrewAI


Options of Pydantic Description
Knowledge validation Verifies that enter knowledge conforms to anticipated varieties (e.g., int, str, record) and might apply customized guidelines.
Automated kind conversion Converts appropriate knowledge varieties robotically, corresponding to turning “2023-10-17” right into a datetime.date.
Knowledge serialization Fashions can serialize knowledge into codecs like JSON, simplifying interactions with APIs.
Default values Fields will be elective or have default values, offering flexibility in dealing with inputs.

Instance of Pydantic Fashions

Let’s make a UserModel that inherits from BaseModel from Pydantic and the instantiated class ought to have an “id” as int, identify as “str” and electronic mail as “electronic mail” 

from pydantic import BaseModel
class UserModel(BaseModel):
   id: int
   identify: str
   electronic mail: str
# Legitimate enter
valid_user = UserModel(id=1, identify="Vidhya", electronic mail="[email protected]")
print(valid_user)
id=1 identify="Vidhya" electronic mail="[email protected]"
# Invalid enter (raises a validation error)
strive:
   invalid_user = UserModel(id="one", identify="Vidhya", electronic mail="[email protected]")
besides ValueError as e:
   print(f"Validation Error: {e}")
Validation Error: 1 validation error for UserModel
id
  Enter must be a legitimate integer, unable to parse string as an integer
[type=int_parsing, input_value="one", input_type=str]
    For additional info go to https://errors.pydantic.dev/2.9/v/int_parsing

We obtained a validation error once we tried passing a string in id and Pydantic additionally returns the hyperlink to documentation that helps us perceive the error.

Now, let’s have a look at different options of Pydantic, corresponding to elective, date, and default worth. 

from pydantic import BaseModel
from typing import Optionally available
from datetime import date
class EventModel(BaseModel):
   event_name: Optionally available[str] = None  # It is Optionally available to offer a worth
   event_loc: str = "India" # Default worth
   event_date: date
# Automated conversion of a string to a `date` object
occasion = EventModel(event_date="2024-10-17")
print(occasion)
event_name=None event_loc="India" event_date=datetime.date(2024, 10, 17)

We now have handed solely the event_date, but it’s not throwing any error as a result of we set event_name to Optionally available and event_loc to “India” by default. Additionally, discover that the date is being typecast from string to datetime. 

Installations

We will probably be utilizing CrewAI all through this information, so ensure you set up CrewAI.

!pip set up crewai

Structuring Inputs in Agentic Methods

The inputs will be formatted whereas defining the Agent and Activity utilizing curly braces { } with a variable identify inside. Setting the human_input=True will immediate the person for suggestions for the output. Let’s outline an agent and activity to reply questions associated to physics:

Observe: I’ll be utilizing the  ‘gpt-4o-mini-2024-07-18’ from openai all through the information. 

from crewai import Agent, Activity, Crew
import os
os.environ['OPENAI_API_KEY']=''
llm_config={'mannequin':'gpt-4o-mini-2024-07-18'}
teacher_agent = Agent(
 function="Physics Professor",
 aim="You've got sturdy foundational information on physics "
       "You give the very best reply to your college students",
 backstory=(
   "You're employed as a school professor"
   "You train physics and make clear doubts {doubts}"
   "You reply the query solely whether it is associated to physics"
   "You just be sure you present the very best solutions!"
 ),
 allow_delegation=False,
 verbose=True)
doubt_clarification_task = Activity(
   description=(
       "Tackle the physics doubts raised by the coed {doubts}. "
       "You do not reply the query if the query is just not associated to physics"
       "Present clear, detailed explanations, examples, and any needed formulation to assist the coed perceive the ideas."
   ),
   expected_output=(
       "A transparent response to the coed's doubts, "
       "together with explanations and examples if wanted. "
   ),
   agent=teacher_agent,
   human_input=True
)
crew = Crew(
 brokers=[teacher_agent],
 duties=[doubt_clarification_task],
 verbose=True,
 reminiscence=False
)

The inputs will be handed to the “inputs “ parameter in crew.kickoff()

inputs = {
   "doubts": "What's thermodynamics",
}
consequence = crew.kickoff(inputs=inputs)

Output

# Agent: Physics Professor

## Activity: Tackle the physics doubts raised by the coed What's
thermodynamics. You do not reply the query if the query is just not associated
to physicsProvide clear, detailed explanations, examples, and any needed
formulation to assist the coed perceive the ideas.

# Agent: Physics Professor

## Ultimate Reply: 

Thermodynamics is the department of physics that offers with the relationships
between warmth, work, temperature, and vitality. It gives a framework for
understanding how vitality is transferred and remodeled in methods, whether or not
they're mechanical engines, fridges, or organic organisms.

The research of thermodynamics is predicated on 4 basic legal guidelines that describe
how vitality strikes and modifications type:

1. **Zeroth Legislation of Thermodynamics**: This regulation establishes the idea of
temperature. It states that if two methods are in thermal equilibrium with a
third system, then they're additionally in thermal equilibrium with one another. For
instance, if System A is in equilibrium with System C, and System B can be
in equilibrium with System C, then System A and System B are in equilibrium
with one another. This enables us to outline temperature as a measurable entity.

2. **First Legislation of Thermodynamics**: Typically acknowledged because the regulation of vitality
conservation, this regulation asserts that vitality can't be created or destroyed,
solely remodeled. Mathematically, it may be expressed as:

   [

   Delta U = Q - W

   ]

   the place ( Delta U ) is the change in inner vitality of the system, ( Q
) is the warmth added to the system, and ( W ) is the work completed by the
system. An instance of the primary regulation in follow is a steam engine, the place warmth
vitality is transformed into work.

3. **Second Legislation of Thermodynamics**: This regulation introduces the idea of
entropy, stating that in any vitality switch, the overall entropy of an
remoted system can by no means lower over time. It means that vitality
transformations should not 100% environment friendly and that methods naturally progress
towards a state of dysfunction. A typical instance is the concept that warmth flows
spontaneously from a warmer physique to a colder physique, not the reverse.

4. **Third Legislation of Thermodynamics**: This regulation states that because the temperature
of a system approaches absolute zero, the entropy of an ideal crystal
approaches zero. This means that it's unattainable to achieve absolute zero
in a finite variety of steps, an idea that underscores the elemental
limits of thermodynamic processes.

In sensible functions, thermodynamics is utilized in quite a few fields corresponding to
engineering (designing engines, fridges), chemistry (response
spontaneity), and environmental science (understanding local weather methods). 

In abstract, thermodynamics is important for analyzing how vitality is utilized
and transferred, offering insights into bettering effectivity and
understanding pure processes in numerous bodily methods.

 ## Ultimate End result: Thermodynamics is the department of physics that offers with the
relationships between warmth, work, temperature, and vitality. It gives a
framework for understanding how vitality is transferred and remodeled in
methods, whether or not they're mechanical engines, fridges, or organic
organisms.

The research of thermodynamics is predicated on 4 basic legal guidelines that describe
how vitality strikes and modifications type:

1. **Zeroth Legislation of Thermodynamics**: This regulation establishes the idea of
temperature. It states that if two methods are in thermal equilibrium with a
third system, then they're additionally in thermal equilibrium with one another. For
instance, if System A is in equilibrium with System C, and System B can be
in equilibrium with System C, then System A and System B are in equilibrium
with one another. This enables us to outline temperature as a measurable
entity.

2. **First Legislation of Thermodynamics**: Typically acknowledged because the regulation of vitality
conservation, this regulation asserts that vitality can't be created or destroyed,
solely remodeled. Mathematically, it may be expressed as:

   [

   Delta U = Q - W

   ]

   the place ( Delta U ) is the change in inner vitality of the system, ( Q
) is the warmth added to the system, and ( W ) is the work completed by the
system. An instance of the primary regulation in follow is a steam engine, the place
warmth vitality is transformed into work.

3. **Second Legislation of Thermodynamics**: This regulation introduces the idea of
entropy, stating that in any vitality switch, the overall entropy of an
remoted system can by no means lower over time. It means that vitality
transformations should not 100% environment friendly and that methods naturally progress
towards a state of dysfunction. A typical instance is the concept that warmth flows
spontaneously from a warmer physique to a colder physique, not the reverse.

4. **Third Legislation of Thermodynamics**: This regulation states that because the temperature
of a system approaches absolute zero, the entropy of an ideal crystal
approaches zero. This means that it's unattainable to achieve absolute zero
in a finite variety of steps, an idea that underscores the elemental
limits of thermodynamic processes.

In sensible functions, thermodynamics is utilized in quite a few fields corresponding to
engineering (designing engines, fridges), chemistry (response
spontaneity), and environmental science (understanding local weather methods). 

In abstract, thermodynamics is important for analyzing how vitality is utilized
and transferred, offering insights into bettering effectivity and
understanding pure processes in numerous bodily methods.

=====

## Please present suggestions on the Ultimate End result and the Agent's actions:

Give the reply in 3 traces

# Agent: Physics Professor

## Ultimate Reply: 

Thermodynamics is the department of physics that offers with the relationships
between warmth, work, temperature, and vitality. It's ruled by 4
basic legal guidelines that describe how vitality is transferred and transformed in
bodily methods. For instance, the primary regulation of thermodynamics states that
vitality can't be created or destroyed, solely remodeled, which is expressed
mathematically as ΔU = Q - W, the place ΔU is the change in inner vitality, Q
is the warmth added to the system, and W is the work completed by the system.

We handed a query within the enter, “What’s thermodynamics?” and with the assistance of a human enter, we obtained the specified reply. 

Structuring Outputs in Agentic Methods

Let’s make brokers who may help me fill out particulars like identify, electronic mail, cellphone quantity, and job one after the other. Structuring the outputs as Pydantic or json helps outline what output we’re anticipating and the format we anticipate in order that the following brokers get structured knowledge and context.

Observe: In a case like mine, not structuring the outputs with anticipated fields would possibly result in a lack of info, and the following brokers would possibly begin hallucinating. 

from crewai import Agent, Activity, Crew
import os
os.environ['OPENAI_API_KEY']=''
llm_config={'mannequin':'gpt-4o-mini-2024-07-18'}

Let’s outline the courses utilizing pedantic with the fields I anticipate within the output. As defined within the Pydantic fashions’ part, you should use Optionally available or set a worth by default if wanted.

from pydantic import BaseModel
from typing import Record
# Outline the courses utilizing Pydantic
class nameEmail(BaseModel):
   identify: Record[str]
   electronic mail: Record[str]
class phoneNo(BaseModel):
   identify: str
   electronic mail: str
   cellphone: int
class allDetails(BaseModel):
   identify: str
   electronic mail: Record[str]
   cellphone: int
   job: str

Let’s outline the primary agent and activity that fills out the person’s identify and electronic mail. Use the “output_pydantic” parameter in Activity(). I handed the nameEmail class as I received’t be utilizing identify and electronic mail as output right here. 

# Activity 1: Agent for filling identify and electronic mail utilizing output_pydantic
name_email_agent = Agent(
   function="Knowledge Entry Specialist",
   aim="Your activity is to fill out the person's identify and electronic mail by yourself.",
   backstory=(
       "You specialise in filling out private info like identify and electronic mail."
       "You fill the identify and electronic mail by yourself"
       "You utilize uncommon names and use start 12 months within the electronic mail"
   ),
   allow_delegation=False,
   verbose=True
)
name_email_task = Activity(
   description="Fill out the identify and electronic mail of the person.",
   expected_output="Title and electronic mail.",
   agent=name_email_agent,
   output_pydantic=nameEmail,
   human_input=False
)

Let’s use the opposite technique to construction the output through the use of the “output_json” parameter in Activity() which supplies the output in json format. 

# Activity 2: Agent for filling cellphone quantity utilizing output_json
phone_number_agent = Agent(
   function="Contact Data Supervisor",
   aim="Your activity is to fill out a random 10 digit cellphone quantity by yourself.",
   backstory=(
       "You might be an skilled in managing contact particulars, particularly cellphone numbers."
   ),
   allow_delegation=False,
   verbose=True
)
phone_number_task = Activity(
   description="Fill out the person's cellphone quantity.",
   expected_output="A JSON format with the person's cellphone quantity.",
   agent=phone_number_agent,
   output_json=phoneNo,
   human_input=False
)

Right here, the agent is designed to fill out the job particulars for the person. The ultimate output will comprise all of the identify, electronic mail, cellphone quantity, and job function info as pedantic and saved in output.txt utilizing the “output_file” parameter. 

# Activity 3: Agent for filling job description utilizing output_file
job_description_agent = Agent(
   function="Job Decider",
   aim="Your activity is to randomly resolve a job for the person",
   backstory=(
       "You deal with assigning job roles randomly."
   ),
   allow_delegation=False,
   verbose=True
)

job_description_task = Activity(

   description="Fill out the person's job description.",

   expected_output="Show identify, electronic mail, cellphone no and job description.",

   agent=job_description_agent,

   output_pydantic=allDetails,

   output_file="/content material/output.txt",

   human_input=False

)
# Outline the crew to run all duties
crew = Crew(
   brokers=[name_email_agent, phone_number_agent, job_description_agent],
   duties=[name_email_task, phone_number_task, job_description_task],
   verbose=True,
   reminiscence=False
)
consequence = crew.kickoff()
# Agent: Knowledge Entry Specialist

## Activity: Fill out the identify and electronic mail of the person.

# Agent: Knowledge Entry Specialist

## Ultimate Reply: 

Title: Elowen Thorne  

E-mail: [email protected]

# Agent: Contact Data Supervisor

## Activity: Fill out the person's cellphone quantity.

# Agent: Contact Data Supervisor

## Ultimate Reply: 

{

  "identify": "Elowen Thorne",

  "electronic mail": "[email protected]",

  "phone_number": "1234567890"

}

# Agent: Job Decider

## Activity: Fill out the person's job function.

# Agent: Job Decider

## Ultimate Reply: 

Title: Elowen Thorne  

E-mail: [email protected]  

Telephone No: 1234567890  

Job Function: Knowledge Analyst

That is the output file that was created :

Output

You can even have a look at every activity’s output:

job_description_task.output
TaskOutput(description="Fill out the person's job function.", identify=None,
expected_output="Show identify, electronic mail, cellphone no and job function.", abstract="Fill
out the person's job function....", uncooked='Title: Elowen Thorne  nEmail:
[email protected]  nPhone No: 1234567890  nJob Function: Knowledge
Analyst', pydantic=allDetails(identify="Elowen Thorne", electronic mail=
['[email protected]'], cellphone=1234567890, job='Knowledge Analyst'),
json_dict=None, agent="Job Decider", output_format= 'pydantic'>)

I obtained the anticipated output, and on account of structuring the intermediate outputs, the small print remained fixed as every activity progressed. 

Additionally, to know the Agent AI higher, discover: The Agentic AI Pioneer Program.

Conclusion

This text explored the significance of structuring inputs and outputs in multi-agent utilizing instruments like Pydantic fashions and CrewAI. By organizing knowledge successfully and validating inputs, we will considerably improve the efficiency and reliability of multi-agent methods. Structured outputs assist preserve consistency and stop errors corresponding to knowledge loss and hallucinations, making certain that brokers can collaborate effectively. Implementing these methods permits builders to create extra sturdy agentic methods able to dealing with complicated duties with larger precision and reliability.

Often Requested Questions

Q1. What are agent-based methods?

Ans. Agent-based methods contain a number of brokers working collectively to unravel issues, talk, and collaborate, offering extra sturdy options than single methods like LLMs.

Q2. What’s CrewAI, and the way does it combine with agentic methods?

Ans. CrewAI is a framework that helps agentic methods, permitting brokers to work collectively to unravel duties. On this article, we use CrewAI with pedantic fashions to construction outputs and guarantee correct knowledge administration between brokers.

Q3. How do you enter a picture in CrewAI?

Ans. One technique to enter a picture in CrewAI is by assigning the URL of the picture to a variable after which passing it to the inputs parameter in crew.kickoff(). 

This autumn. What are Pydantic fashions, and the way are they utilized in agentic methods?

Ans. Pydantic fashions are Python objects used for knowledge validation and serialization. They assist make sure that inputs and outputs between brokers are correctly structured, resulting in extra dependable outcomes in agent-based methods.

Q5. How do you construction outputs in agentic methods utilizing Pydantic fashions?

Ans. Outputs are structured by defining the anticipated fields (like identify, electronic mail, and so on.) utilizing Pydantic fashions, which ensures that the subsequent agent receives legitimate and well-formatted knowledge for processing.

I am a tech fanatic, graduated from Vellore Institute of Expertise. I am working as a Knowledge Science Trainee proper now. I’m very a lot fascinated with Deep Studying and Generative AI.

We use cookies important for this website to perform effectively. Please click on to assist us enhance its usefulness with further cookies. Find out about our use of cookies in our Privateness Coverage & Cookies Coverage.

Present particulars

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles