Structuring Inputs & Outputs in Multi Agent programs Utilizing CrewAI

Options of Pydantic Description
Information validation Verifies that enter knowledge conforms to anticipated varieties (e.g., int, str, record) and may apply customized guidelines.
Automated sort conversion Converts suitable knowledge varieties mechanically, resembling turning “2023-10-17” right into a datetime.date.
Information 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, title as “str” and e-mail as “e-mail” 

from pydantic import BaseModel
class UserModel(BaseModel):
   id: int
   title: str
   e-mail: str
# Legitimate enter
valid_user = UserModel(id=1, title="Vidhya", e-mail="[email protected]")
print(valid_user)
id=1 title="Vidhya" e-mail="[email protected]"
# Invalid enter (raises a validation error)
strive:
   invalid_user = UserModel(id="one", title="Vidhya", e-mail="[email protected]")
besides ValueError as e:
   print(f"Validation Error: {e}")
Validation Error: 1 validation error for UserModel
id
  Enter ought to be a sound 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 acquired a validation error after we tried passing a string in id and Pydantic additionally returns the hyperlink to documentation that helps us perceive the error.

Now, let’s take a look at different options of Pydantic, resembling elective, date, and default worth. 

from pydantic import BaseModel
from typing import Elective
from datetime import date
class EventModel(BaseModel):
   event_name: Elective[str] = None  # It is Elective 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 have now handed solely the event_date, but it’s not throwing any error as a result of we set event_name to Elective 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 be sure you set up CrewAI.

!pip set up crewai

Structuring Inputs in Agentic Techniques

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

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

from crewai import Agent, Job, Crew
import os
os.environ['OPENAI_API_KEY']=''
llm_config={'mannequin':'gpt-4o-mini-2024-07-18'}
teacher_agent = Agent(
 position="Physics Professor",
 aim="You've gotten robust foundational information on physics "
       "You give the very best reply to your college students",
 backstory=(
   "You're employed as a university professor"
   "You train physics and make clear doubts {doubts}"
   "You reply the query solely whether it is associated to physics"
   "You just remember to present the very best solutions!"
 ),
 allow_delegation=False,
 verbose=True)
doubt_clarification_task = Job(
   description=(
       "Deal with 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 crucial 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

## Job: Deal with 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 crucial
formulation to assist the coed perceive the ideas.

# Agent: Physics Professor

## Remaining Reply: 

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

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

1. **Zeroth Legislation of Thermodynamics**: This regulation establishes the idea of
temperature. It states that if two programs 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 also 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**: Usually said because the regulation of vitality
conservation, this regulation asserts that vitality can't be created or destroyed,
solely reworked. Mathematically, it may be expressed as:

   [

   Delta U = Q - W

   ]

   the place ( Delta U ) is the change in inside vitality of the system, ( Q
) is the warmth added to the system, and ( W ) is the work carried out 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 programs naturally progress
towards a state of dysfunction. A standard instance is the concept 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 suggests that it's not possible to achieve absolute zero
in a finite variety of steps, an idea that underscores the basic
limits of thermodynamic processes.

In sensible purposes, thermodynamics is utilized in quite a few fields resembling
engineering (designing engines, fridges), chemistry (response
spontaneity), and environmental science (understanding local weather programs). 

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

 ## Remaining Outcome: Thermodynamics is the department of physics that offers with the
relationships between warmth, work, temperature, and vitality. It supplies a
framework for understanding how vitality is transferred and reworked in
programs, whether or not they're mechanical engines, fridges, or organic
organisms.

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

1. **Zeroth Legislation of Thermodynamics**: This regulation establishes the idea of
temperature. It states that if two programs 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 also 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**: Usually said because the regulation of vitality
conservation, this regulation asserts that vitality can't be created or destroyed,
solely reworked. Mathematically, it may be expressed as:

   [

   Delta U = Q - W

   ]

   the place ( Delta U ) is the change in inside vitality of the system, ( Q
) is the warmth added to the system, and ( W ) is the work carried out 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 programs naturally progress
towards a state of dysfunction. A standard instance is the concept 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 suggests that it's not possible to achieve absolute zero
in a finite variety of steps, an idea that underscores the basic
limits of thermodynamic processes.

In sensible purposes, thermodynamics is utilized in quite a few fields resembling
engineering (designing engines, fridges), chemistry (response
spontaneity), and environmental science (understanding local weather programs). 

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

=====

## Please present suggestions on the Remaining Outcome and the Agent's actions:

Give the reply in 3 traces

# Agent: Physics Professor

## Remaining Reply: 

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

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

Structuring Outputs in Agentic Techniques

Let’s make brokers who might help me fill out particulars like title, e-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.

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

from crewai import Agent, Job, 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 utilize Elective or set a worth by default if wanted.

from pydantic import BaseModel
from typing import Listing
# Outline the courses utilizing Pydantic
class nameEmail(BaseModel):
   title: Listing[str]
   e-mail: Listing[str]
class phoneNo(BaseModel):
   title: str
   e-mail: str
   cellphone: int
class allDetails(BaseModel):
   title: str
   e-mail: Listing[str]
   cellphone: int
   job: str

Let’s outline the primary agent and activity that fills out the consumer’s title and e-mail. Use the “output_pydantic” parameter in Job(). I handed the nameEmail class as I received’t be utilizing title and e-mail as output right here. 

# Job 1: Agent for filling title and e-mail utilizing output_pydantic
name_email_agent = Agent(
   position="Information Entry Specialist",
   aim="Your activity is to fill out the consumer's title and e-mail by yourself.",
   backstory=(
       "You concentrate on filling out private info like title and e-mail."
       "You fill the title and e-mail by yourself"
       "You employ uncommon names and use start 12 months within the e-mail"
   ),
   allow_delegation=False,
   verbose=True
)
name_email_task = Job(
   description="Fill out the title and e-mail of the consumer.",
   expected_output="Identify and e-mail.",
   agent=name_email_agent,
   output_pydantic=nameEmail,
   human_input=False
)

Let’s use the opposite strategy to construction the output by utilizing the “output_json” parameter in Job() which provides the output in json format. 

# Job 2: Agent for filling cellphone quantity utilizing output_json
phone_number_agent = Agent(
   position="Contact Data Supervisor",
   aim="Your activity is to fill out a random 10 digit cellphone quantity by yourself.",
   backstory=(
       "You're an knowledgeable in managing contact particulars, particularly cellphone numbers."
   ),
   allow_delegation=False,
   verbose=True
)
phone_number_task = Job(
   description="Fill out the consumer's cellphone quantity.",
   expected_output="A JSON format with the consumer'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 consumer. The ultimate output will comprise all of the title, e-mail, cellphone quantity, and job position info as pedantic and saved in output.txt utilizing the “output_file” parameter. 

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

job_description_task = Job(

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

   expected_output="Show title, e-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: Information Entry Specialist

## Job: Fill out the title and e-mail of the consumer.

# Agent: Information Entry Specialist

## Remaining Reply: 

Identify: Elowen Thorne  

Electronic mail: [email protected]

# Agent: Contact Data Supervisor

## Job: Fill out the consumer's cellphone quantity.

# Agent: Contact Data Supervisor

## Remaining Reply: 

{

  "title": "Elowen Thorne",

  "e-mail": "[email protected]",

  "phone_number": "1234567890"

}

# Agent: Job Decider

## Job: Fill out the consumer's job position.

# Agent: Job Decider

## Remaining Reply: 

Identify: Elowen Thorne  

Electronic mail: [email protected]  

Cellphone No: 1234567890  

Job Position: Information Analyst

That is the output file that was created :

Output

You may as well take a look at every activity’s output:

job_description_task.output
TaskOutput(description="Fill out the consumer's job position.", title=None,
expected_output="Show title, e-mail, cellphone no and job position.", abstract="Fill
out the consumer's job position....", uncooked='Identify: Elowen Thorne  nEmail:
[email protected]  nPhone No: 1234567890  nJob Position: Information
Analyst', pydantic=allDetails(title="Elowen Thorne", e-mail=
['[email protected]'], cellphone=1234567890, job='Information Analyst'),
json_dict=None, agent="Job Decider", output_format=<OutputFormat.PYDANTIC:
'pydantic'>)

I acquired the anticipated output, and attributable to structuring the intermediate outputs, the main points 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 programs. Structured outputs assist keep consistency and stop errors resembling knowledge loss and hallucinations, making certain that brokers can collaborate effectively. Implementing these methods permits builders to create extra sturdy agentic programs able to dealing with complicated duties with larger precision and reliability.

Continuously Requested Questions

Q1. What are agent-based programs?

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

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

Ans. CrewAI is a framework that helps agentic programs, permitting brokers to work collectively to resolve 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 strategy 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 programs?

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

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

Ans. Outputs are structured by defining the anticipated fields (like title, e-mail, and so forth.) 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 Know-how. I am working as a Information Science Trainee proper now. I’m very a lot excited about Deep Studying and Generative AI.

We use cookies important for this website to operate nicely. 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