8.1 C
United States of America
Sunday, November 24, 2024

Structuring Inputs & Outputs in Multi Agent programs Utilizing CrewAI


Options of Pydantic Description
Information validation Verifies that enter knowledge conforms to anticipated sorts (e.g., int, str, record) and may apply customized guidelines.
Computerized sort conversion Converts appropriate knowledge sorts robotically, 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 may be non-obligatory 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 must be a legitimate integer, unable to parse string as an integer
[type=int_parsing, input_value="one", input_type=str]
    For additional data go to https://errors.pydantic.dev/2.9/v/int_parsing

We bought 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 non-obligatory, 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 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 got 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 can be utilizing CrewAI all through this information, so ensure you set up CrewAI.

!pip set up crewai

Structuring Inputs in Agentic Techniques

The inputs may be formatted whereas defining the Agent and Activity 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 process to reply questions associated to physics:

Word: 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(
 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 university professor"
   "You educate physics and make clear doubts {doubts}"
   "You reply the query solely whether it is associated to physics"
   "You just remember to present the most effective solutions!"
 ),
 allow_delegation=False,
 verbose=True)
doubt_clarification_task = Activity(
   description=(
       "Tackle the physics doubts raised by the scholar {doubts}. "
       "You do not reply the query if the query isn't associated to physics"
       "Present clear, detailed explanations, examples, and any vital 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 may 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 scholar What's
thermodynamics. You do not reply the query if the query isn't associated
to physicsProvide clear, detailed explanations, examples, and any vital
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 programs, whether or not
they're mechanical engines, fridges, or organic organisms.

The examine of thermodynamics relies on 4 basic legal guidelines that describe
how vitality strikes and adjustments kind:

1. **Zeroth Regulation 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 be
in equilibrium with System C, then System A and System B are in equilibrium
with one another. This permits us to outline temperature as a measurable entity.

2. **First Regulation of Thermodynamics**: Usually 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 accomplished 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 Regulation 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 Regulation 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 unattainable to achieve absolute zero
in a finite variety of steps, an idea that underscores the basic
limits of thermodynamic processes.

In sensible functions, 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.

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

The examine of thermodynamics relies on 4 basic legal guidelines that describe
how vitality strikes and adjustments kind:

1. **Zeroth Regulation 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 be
in equilibrium with System C, then System A and System B are in equilibrium
with one another. This permits us to outline temperature as a measurable
entity.

2. **First Regulation of Thermodynamics**: Usually 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 accomplished 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 Regulation 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 Regulation 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 unattainable to achieve absolute zero
in a finite variety of steps, an idea that underscores the basic
limits of thermodynamic processes.

In sensible functions, 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 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
basic 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 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 accomplished by the system.

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

Structuring Outputs in Agentic Techniques

Let’s make brokers who can assist 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 anticipate in order that the following brokers get structured knowledge and context.

Word: In a case like mine, not structuring the outputs with anticipated fields may result in a lack of data, and the following brokers may 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 Elective or set a price by default if wanted.

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

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

# Activity 1: Agent for filling title and e mail utilizing output_pydantic
name_email_agent = Agent(
   position="Information Entry Specialist",
   purpose="Your process is to fill out the person's title and e mail by yourself.",
   backstory=(
       "You concentrate on filling out private data like title and e mail."
       "You fill the title and e mail by yourself"
       "You employ uncommon names and use delivery yr within the e mail"
   ),
   allow_delegation=False,
   verbose=True
)
name_email_task = Activity(
   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 strategy to construction the output by utilizing the “output_json” parameter in Activity() which supplies the output in json format. 

# Activity 2: Agent for filling telephone quantity utilizing output_json
phone_number_agent = Agent(
   position="Contact Data Supervisor",
   purpose="Your process is to fill out a random 10 digit telephone quantity by yourself.",
   backstory=(
       "You're an professional in managing contact particulars, particularly telephone numbers."
   ),
   allow_delegation=False,
   verbose=True
)
phone_number_task = Activity(
   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 data 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(
   position="Job Decider",
   purpose="Your process 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 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: Information Entry Specialist

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

# Agent: Information Entry Specialist

## Ultimate Reply: 

Identify: Elowen Thorne  

E mail: [email protected]

# Agent: Contact Data Supervisor

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

# Agent: Contact Data Supervisor

## Ultimate Reply: 

{

  "title": "Elowen Thorne",

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

  "phone_number": "1234567890"

}

# Agent: Job Decider

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

# Agent: Job Decider

## Ultimate Reply: 

Identify: Elowen Thorne  

E mail: [email protected]  

Telephone No: 1234567890  

Job Function: Information Analyst

That is the output file that was created :

Output

It’s also possible to take a look at every process’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 Function: Information
Analyst', pydantic=allDetails(title="Elowen Thorne", e mail=
['[email protected]'], telephone=1234567890, job='Information Analyst'),
json_dict=None, agent="Job Decider", output_format=<OutputFormat.PYDANTIC:
'pydantic'>)

I bought the anticipated output, and on account of structuring the intermediate outputs, the small print remained fixed as every process 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 preserve 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 higher precision and reliability.

Incessantly 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 sure 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 following 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 Information Science Trainee proper now. I’m very a lot eager about 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 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

Latest Articles