11.6 C
New York
Sunday, October 20, 2024

Structuring Inputs & Outputs in Multi Agent techniques Utilizing CrewAI


Options of Pydantic Description
Knowledge validation Verifies that enter knowledge conforms to anticipated sorts (e.g., int, str, record) and might apply customized guidelines.
Computerized kind conversion Converts appropriate knowledge sorts routinely, equivalent 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 non-compulsory 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)
attempt:
   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 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 acquired 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 take a look at different options of Pydantic, equivalent to non-compulsory, date, and default worth. 

from pydantic import BaseModel
from typing import Non-compulsory
from datetime import date
class EventModel(BaseModel):
   event_name: Non-compulsory[str] = None  # It is Non-compulsory to supply a price
   event_loc: str = "India" # Default worth
   event_date: date
# Computerized 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’ve handed solely the event_date, but it’s not throwing any error as a result of we set event_name to Non-compulsory 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 Programs

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 person for suggestions for the output. Let’s outline an agent and job 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",
 purpose="You've gotten sturdy foundational data on physics "
       "You give the most effective reply to your college students",
 backstory=(
   "You're employed as a school professor"
   "You educate physics and make clear doubts {doubts}"
   "You reply the query solely whether it is associated to physics"
   "You just be sure you present the most effective solutions!"
 ),
 allow_delegation=False,
 verbose=True)
doubt_clarification_task = Job(
   description=(
       "Deal with the physics doubts raised by the scholar {doubts}. "
       "You do not reply the query if the query will not be associated to physics"
       "Present clear, detailed explanations, examples, and any mandatory formulation to assist the scholar perceive the ideas."
   ),
   expected_output=(
       "A transparent response to the scholar'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 scholar What's
thermodynamics. You do not reply the query if the query will not be associated
to physicsProvide clear, detailed explanations, examples, and any mandatory
formulation to assist the scholar 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 supplies a framework for
understanding how vitality is transferred and remodeled in techniques, whether or not
they're mechanical engines, fridges, or organic organisms.

The examine of thermodynamics is predicated on 4 elementary 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 techniques 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**: Typically said 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 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 whole entropy of an
remoted system can by no means lower over time. It means that vitality
transformations will not be 100% environment friendly and that techniques 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 unimaginable to succeed in 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 equivalent to
engineering (designing engines, fridges), chemistry (response
spontaneity), and environmental science (understanding local weather techniques). 

In abstract, thermodynamics is crucial for analyzing how vitality is utilized
and transferred, offering insights into enhancing effectivity and
understanding pure processes in varied bodily techniques.

 ## Ultimate 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 remodeled in
techniques, whether or not they're mechanical engines, fridges, or organic
organisms.

The examine of thermodynamics is predicated on 4 elementary 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 techniques 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**: Typically said 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 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 whole entropy of an
remoted system can by no means lower over time. It means that vitality
transformations will not be 100% environment friendly and that techniques 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 unimaginable to succeed in 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 equivalent to
engineering (designing engines, fridges), chemistry (response
spontaneity), and environmental science (understanding local weather techniques). 

In abstract, thermodynamics is crucial for analyzing how vitality is utilized
and transferred, offering insights into enhancing effectivity and
understanding pure processes in varied bodily techniques.

=====

## Please present suggestions on the Ultimate Outcome 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
elementary legal guidelines that describe how vitality is transferred and transformed in
bodily techniques. 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 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 Programs

Let’s make brokers who may help me fill out particulars like title, e mail, telephone 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 count on in order that the next brokers get structured knowledge and context.

Be aware: In a case like mine, not structuring the outputs with anticipated fields would possibly result in a lack of info, and the next brokers would possibly 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 count on within the output. As defined within the Pydantic fashions’ part, you need to use Non-compulsory or set a price 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
   telephone: int
class allDetails(BaseModel):
   title: str
   e mail: Listing[str]
   telephone: int
   job: str

Let’s outline the primary agent and job that fills out the person’s title and e mail. Use the “output_pydantic” parameter in Job(). I handed the nameEmail class as I gained’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="Knowledge Entry Specialist",
   purpose="Your job is to fill out the person's title and e mail by yourself.",
   backstory=(
       "You focus 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 yr within the e mail"
   ),
   allow_delegation=False,
   verbose=True
)
name_email_task = Job(
   description="Fill out the title and e mail of the person.",
   expected_output="Identify and e mail.",
   agent=name_email_agent,
   output_pydantic=nameEmail,
   human_input=False
)

Let’s use the opposite solution to construction the output through the use of the “output_json” parameter in Job() which provides the output in json format. 

# Job 2: Agent for filling telephone quantity utilizing output_json
phone_number_agent = Agent(
   position="Contact Info Supervisor",
   purpose="Your job is to fill out a random 10 digit telephone quantity by yourself.",
   backstory=(
       "You're an skilled in managing contact particulars, particularly telephone numbers."
   ),
   allow_delegation=False,
   verbose=True
)
phone_number_task = Job(
   description="Fill out the person's telephone quantity.",
   expected_output="A JSON format with the person's telephone 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 title, e mail, telephone 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",
   purpose="Your job is to randomly determine a job for the person",
   backstory=(
       "You deal with assigning job roles randomly."
   ),
   allow_delegation=False,
   verbose=True
)

job_description_task = Job(

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

   expected_output="Show title, e mail, telephone 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

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

# Agent: Knowledge Entry Specialist

## Ultimate Reply: 

Identify: Elowen Thorne  

Electronic mail: [email protected]

# Agent: Contact Info Supervisor

## Job: Fill out the person's telephone quantity.

# Agent: Contact Info Supervisor

## Ultimate Reply: 

{

  "title": "Elowen Thorne",

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

  "phone_number": "1234567890"

}

# Agent: Job Decider

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

# Agent: Job Decider

## Ultimate Reply: 

Identify: Elowen Thorne  

Electronic mail: [email protected]  

Cellphone No: 1234567890  

Job Position: Knowledge Analyst

That is the output file that was created :

Output

You can even take a look at every job’s output:

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

I acquired the anticipated output, and as a result of structuring the intermediate outputs, the main points remained fixed as every job progressed. 

Additionally, to grasp 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 techniques. Structured outputs assist keep consistency and stop errors equivalent to knowledge loss and hallucinations, guaranteeing that brokers can collaborate effectively. Implementing these methods permits builders to create extra sturdy agentic techniques able to dealing with complicated duties with higher precision and reliability.

Ceaselessly Requested Questions

Q1. What are agent-based techniques?

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

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

Ans. CrewAI is a framework that helps agentic techniques, 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 solution 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 fall. What are Pydantic fashions, and the way are they utilized in agentic techniques?

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 techniques.

Q5. How do you construction outputs in agentic techniques 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 Knowledge Science Trainee proper now. I’m very a lot all for Deep Studying and Generative AI.

We use cookies important for this web site to operate properly. Please click on to assist us enhance its usefulness with extra cookies. Study 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

Latest Articles