Validates input data against expected formats (e.g., integer, string, list) and potentially enforces tailored rules. | |
Translates various data formats seamlessly, such as converting the date string “2023-10-17” into a datetime.date object. | |
While fashions may not seem directly related to serializing knowledge, they can indeed facilitate the process of converting complex data into more manageable formats, such as JSON, thereby streamlining interactions with APIs. | |
While fields may be optional or provide default values, this flexibility enables a more accommodating approach to handling input. |
class UserModel(BaseModel):
id: int
identify: str
email: Email
from pydantic import BaseModel
class UserModel(BaseModel):
id: int
identify: str
email: str
valid_user = UserModel(id=1, identify="Vidhya", email="")
print(valid_user)
id=1 identify="Vidhya" e-mail=""
# Invalid enter raises a validation error
attempt:
try:
invalid_user = UserModel(id="one", identify="Vidhya", email="")
except ValueError as e:
print(f"Validation Error: {e}")
The required 'username' field cannot be null or empty. Please fill in a valid username.
id
Enter a valid integer.
[type=int_parsing, input_value="one", input_type=str]
The error handling in Pydantic's integer parsing is a crucial aspect of any application that relies heavily on robust data validation and processing. https://errors.pydantic.dev/2.9/v/int_parsing
When attempting to pass a string as the ‘id’ value, we encountered a validation error. Pydantic not only detected this issue but also provided a helpful link to its documentation, enabling us to better understand the error and take corrective action.
The versatility of Pydantic’s optional values is quite remarkable; there are three main variants: non-obligatory, date, and default.
from pydantic import BaseModel
from typing import Optional
from datetime import date
class EventModel(BaseModel):
event_name: Optional[str] = None # It is optional to supply a value
event_loc: str = "India" # Default value
event_date: date
occasion = EventModel(event_date=date(2024, 10, 17))
print(occasion)
event_name=None event_loc="India" event_date=datetime.date(2024, 10, 17)
Since we’ve solely passed the `event_date`, without triggering any errors, we’ve intentionally set `event_name` to optional and `event_loc` to “India” by default. The function should be modified to avoid errors when converting dates.
Installations
We will utilize CrewAI throughout this process, ensuring a seamless experience.
!pip set up crewai
Structuring Inputs in Agentic Programs
The text processing system efficiently handles inputs formatted with curly braces { } defining Agents and Jobs using variables. Setting the `human_input=True` parameter immediately prompts the user for input and enables interactive mode. The Agent for Responding to Physics-Related Questions (ARPRQ) will facilitate efficient and accurate interactions with users seeking information about physics.
It shall engage in conversations by identifying the user’s query, retrieving relevant information from a vast knowledge base, and providing concise yet informative responses that cater to the user’s level of understanding.
from crewai import Agent, Job, Crew
import os
os.environ['OPENAI_API_KEY'] = ''
llm_config = {'model': 'gpt-4o-mini', 'date': '2024-07-18'}
teacher_agent = Agent(function="Physics Professor", purpose="Providing effective explanations to students on physics concepts.", backstory=("Serving as a school professor, I teach physics and clarify students' doubts."), allow_delegation=False, verbose=True)
doubt_clarification_task = Job(description=f"Clarify physics-related doubts raised by students {os.linesep}Doubts: ?") "You provide a concise and accurate explanation that directly addresses the student's query." "
),
agent=teacher_agent,
human_input=True
)
crew = Crew(
brokers=[teacher_agent],
duties=[doubt_clarification_task],
verbose=True,
reminiscence=False
)
The “inputs” parameter in crew.kickoff() should accept handed inputs.
import asyncio
from typing import Dict
def crew_kickoff(inputs: Dict) -> None:
if not inputs.get("doubts"):
print("No doubts provided.")
elif inputs["doubts"] == "What's thermodynamics":
print("Thermodynamics is the study of energy and its interactions with matter.
# Agent: Physics ProfessorWhat are the key physical principles underlying the scholar's query?
thermodynamics. I'm ready to help! Please provide the text you'd like me to improve in a different style as a professional editor.
to provide clear, concise and in-depth explanations, illustrations and any necessary supporting details.
Formulations designed to facilitate the scholar's comprehension of concepts.# Agent: Physics Professor
## Remaining Reply:
Thermodynamics is a fundamental department of physics that deals with the relationships between heat, work, and energy.
Amongst the realms of warmth, diligent effort, precise measurement of heat, and pulsating energy. It supplies a framework for
Understanding how vitality is transformed and reworked within programs remains a crucial aspect of software development, whether one is working with established languages or exploring innovative new paradigms.
There are systems that operate on different principles: they're either mechanical engines, refrigeration units, or living organisms.The fundamental principles guiding thermodynamic research are encapsulated in four essential laws.
Vitality's strike capability allows for swift and precise attacks.1. The Zeroth Law of Thermodynamics states that if two systems are in thermal equilibrium with a third system, then they are also in thermal equilibrium with each other.
temperature. They share the same temperature.
Thirdly, these systems are also thermally equilibrated amongst themselves. For
Since System A is in equilibrium with System C, and System B can also be in equilibrium with both Systems A and C, it follows that System B must also be in equilibrium with itself.
When Systems A and B are in equilibrium with System C, they must also be in equilibrium with each other.
with one another. By defining temperature as a quantifiable parameter, we establish a foundation for understanding its significance.2. The First Law of Thermodynamics: Typically recognized as the Law of Energy.
Conservation of energy, as asserted by this legislation, postulates that energy cannot be created or destroyed, merely transformed from one form to another.
solely reworked. Mathematically, this phenomenon can be succinctly expressed as:[
ΔU = Q - W
]
the place where thermodynamic processes occur is denoted as ΔU, representing the change in internal energy of the system; Q,
The internal energy of a closed system. The internal energy is the sum of the kinetic energy of the molecules making up the system, their potential energies, and any other forms of energy that might be present. When heat is added to a system, the internal energy increases. The change in internal energy (ΔU) is related to the work done on the system by the equation: ΔU = Q - W, where Q is the amount of heat added to the system and W is the work accomplished by the
system. A fundamental illustration of secondary legislation is a steam engine, where heat
vitality is transformed into work.3. The Second Law of Thermodynamics: This principle stipulates that as energy is transferred or transformed from one form to another, some of the available energy will inevitably degrade into thermal energy, thus increasing the overall entropy of the system.
Entropy remains unchanged, as a vital switch involves no net transfer of energy.
Remote systems cannot possibly deteriorate with age. It means that vitality
Transformations may not be 100% environmentally sustainable; yet, as technology progresses?
towards a state of dysfunction. The concept of warmth flows in a standard instance?
Spontaneously transforming from a warm-bodied creature to one adapted for a colder environment, rather than vice versa.4. The third law of thermodynamics states that as the temperature of a system approaches absolute zero, its entropy also approaches a minimum value, provided that the system remains in thermal equilibrium with its surroundings.
As a system approaches absolute zero, the entropy of an ideal crystal lattice is expected to vanish.
approaches zero. It is impossible to achieve a temperature of absolute zero.
In a finite sequence of steps, a concept that embodies the fundamental principles.
limits of thermodynamic processes.Across various disciplines, thermodynamics plays a crucial role in several areas, including
What sparks curiosity in you is the intersection of engineering and chemistry?
Spontaneity, encompassing adaptability to unexpected situations, and environmental science, including comprehension of local meteorological initiatives.Thermodynamics plays a pivotal role in understanding the efficient utilization of energy.
and effectively transferred, providing valuable insights to enhance operational efficiency.
Understanding the nuances of pure processes within diverse bodily systems.Thermodynamics is the branch of physics that deals with the
The interconnectedness of warmth, work, temperature, and vitality? It supplies a
A framework for comprehending how vitality is transmitted and refined within?
Programs, regardless of whether they are mechanical engines, refrigeration systems, or biological organisms
organisms.The investigation of thermodynamics is founded upon four fundamental principles that outline
Vitality strikes with profound force, its modifications resonating deeply within.1. Zeroth Law of Thermodynamics: This law states that if two systems are in thermal equilibrium with a third system, then they are also in thermal equilibrium with each other.
temperature. If two programs are in thermal equilibrium with any third program, then they must also be in thermal equilibrium with each other.
The two systems are initially at different temperatures, but as heat transfer occurs between them, they eventually reach a state of thermal equilibrium where their temperatures become equalised. For
Systems A and C being in equilibrium implies that their respective states are uniform and unchanging; similarly, the stability of System B's state ensures no internal fluctuations. The notion that System B can also be in equilibrium with System C suggests a harmonious coexistence between these systems, where any perturbations are absorbed and restored to their initial conditions?
In equilibrium with System C, systems A and B are in equilibrium.
with one another. This allows for the definition of temperature as a quantifiable.
entity.2. The First Law of Thermodynamics: Typically referred to as the Law of Energy
Conservation of energy, as this legislation posits, maintains that the total amount of vitality remains constant and cannot be either created or destroyed.
solely reworked. Mathematically, this phenomenon can be succinctly captured by:[
ΔU = Q - W
]
The place where the thermodynamic process occurs, denoted by ΔU, represents the change in internal energy of the system. This value is equivalent to the heat added, or Q,
The internal energy of a closed system is increased by the heat added to the system, and the work accomplished by the external forces acting on the system.
system. In a notable example of primary legislation, a steam engine stands out as
Passion and energy are converted into productive endeavors.3. The second law of thermodynamics: This principle stipulates that
Entropy's fundamental principle dictates that in any thermodynamic transition, the total entropy of a closed system always increases, never decreasing.
Remote systems cannot decline in quality over time. It means that vitality
Transformations may not be entirely environmentally sustainable; conversely, programs tend to evolve.
towards a state of dysfunction. Warmth flows are a fundamental concept in thermodynamics, describing the movement of thermal energy from one location to another.
As the temperature shifts spontaneously from a warmer physique to a colder physique,4. The third law of thermodynamics asserts that as the temperature of a system approaches absolute zero, its entropy approaches a minimum value.
As a thermodynamic system approaches absolute zero, the entropy of an ideal crystal lattice exhibits a unique characteristic.
approaches zero. It is impossible to achieve success at an absolute zero.
In a few, decisive moves, an insight crystallizes the fundamental principles.
limits of thermodynamic processes.Thermodynamic principles are widely applied across various disciplines, including
Engineering and chemistry are two distinct disciplines that share a common thread in their focus on the fundamental principles of natural phenomena. In designing engines and refrigeration systems, engineers apply mathematical models to optimize performance, efficiency, and sustainability. Similarly, chemists use the periodic table and chemical reactions to develop new materials, medicines, and technologies.
Spontaneity, in conjunction with a strong foundation in environmental science (including comprehension of local weather patterns).Thermodynamics plays a pivotal role in understanding the efficient utilization of energy.
enhancing productivity through streamlined processes and strategic allocation of resources.
Unraveling the intricacies of pure biological processes across diverse physiological pathways.=====
The remaining end result was subpar due to a lack of transparency in the agent's actions.
Please provide the text you'd like me to improve, and I'll respond with the revised text in a different style.
# Agent: Physics Professor
## Remaining Reply:
Thermodynamics is a branch of physics that deals with the interrelationships between heat, work, and energy.
Amongst radiant warmth, industrious work, ambient temperature, and pulsing vitality. It's ruled by 4
Basic legal frameworks that outline the mechanisms for the transfer and transformation of vitality.
bodily programs. The fundamental principles of thermodynamics, as outlined by its primary legislation, assert that
Energy cannot be created or destroyed, merely transformed, as the saying goes.
ΔU = Q - W
The first law of thermodynamics states that the total energy of an isolated system remains constant, as any increase in internal energy or kinetic energy is balanced by a corresponding decrease in potential energy?
What’s Thermodynamics?
Structuring Outputs in Agentic Programs
Let’s create a brokerage platform where you can easily add personal details such as name, email address, phone number, and occupation in sequence. Defining outputs in a standardized format, such as Pydantic or JSON, facilitates clear communication with subsequent brokers by providing structured information and context.
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 pedagogically sound approaches across the various fields I envision in our academic programs. As defined within the Pydantic framework’s specifications, consider utilizing optional or setting a value by default when needed.
from pydantic import BaseModel, conlist
# Outline the courses utilizing Pydantic
class NameEmail(BaseModel):
identities: conlist(str)
emails: conlist[str]
class PhoneNo(BaseModel):
identity: str
email: str
phone_number: int
class AllDetails(BaseModel):
identity: str
emails: conlist[str]
phone_number: int
job: str
The primary agents responsible for filling out a person’s identity and email are typically employers, educational institutions, or government agencies, with activities such as data collection, registration, and verification processes. You can use the `output_pydantic` parameter in `Job()` to simplify your output processing and conversion into Pydantic models. This feature is particularly useful when you’re working with complex data structures that require significant processing or validation before being returned. I won’t utilize identity and email as output here.
# Job 1: Agent for filling identity and email using output_pyntactic
name_email_agent = Agent(function="Information Entry Specialist",
purpose="Fill out individual's identity and email independently.",
backstory=f"You specialize in entering private data like name and email. You generate unique names and use the first year of the century in the email ({now.year}) for each entry. This task requires no external information.",
allow_delegation=False, verbose=True)
name_email_task = Job(description="Enter individual's name and email details.",
expected_output="Name and Email",
agent=name_email_agent,
output_pydantic=NameEmail, human_input=False)
Let’s construct the output using the opposite option for constructing the output by way of providing the output in JSON format via the “output_json” parameter in the Job().
# Job 2: Agent for filling telephone quantity utilizing output_json
phone_number_agent = Agent(
function="Contact Data Supervisor",
purpose="Fill a random 10-digit phone number.",
backstory="As an expert in managing contact details, you'll generate a phone number.",
allow_delegation=False,
verbose=True
)
phone_number_task = Job(description="Generate a person's phone number.", expected_output="JSON", agent=phone_number_agent, output_json=phoneNo, human_input=False)
The agent is intended to populate job details for the individual. The ultimate output will comprise all identified data, including email, phone number, and job function, stored in a file named “output.txt” using the “output_file” parameter?
crew = Crew(brokers=[name_email_agent, phone_number_agent, job_description_agent], duties=[name_email_task, phone_number_task, job_description_task], verbose=True)
result = crew.start()
# Agent: Information Entry SpecialistName: John Smith Email: [john.smith@email.com](mailto:john.smith@email.com)
# Agent: Information Entry Specialist
## Remaining Reply:
Title: Elowen Thorne
Electronic mail:
# Agent: Contact Data Supervisor
Please provide the person's name and relevant details to complete the task accurately. Phone number: ___________________________
# Agent: Contact Data Supervisor
## Remaining Reply:
{
"identify": "Elowen Thorne",
"e-mail": "",
"phone_number": "1234567890"
}
# Agent: Job Decider
Marketing Manager?
# Agent: Job Decider
## Remaining Reply:
Title: Elowen Thorne
Electronic mail:
Cellphone No: 1234567890
Job Function: Information Analyst
One can easily examine each task’s result.
job_description_task.output
TaskOutput(description="The individual fills a specific role within an organization, responsible for executing assigned tasks and responsibilities. Their primary occupation is", identify=None,)
Show identify, email, telephone number, and job function.
Identifying the individual's role and responsibilities.
Phone Number: 1-234-567-890, Job Function: Information Technology
Analyst', pydantic=allDetails(identify="Elowen Thorne", e-mail=
[''], telephone=1234567890, job='Information Analyst'),
json_dict=None, agent="Job Decider", output_format=<OutputFormat.PYDANTIC:
'pydantic'>)
I successfully obtained the expected outcome, and by organizing the interim results, the key findings remained steady throughout each step.
.
Conclusion
The text examines the crucial role of organizing inputs and outputs in multi-agent systems, leveraging tools such as and. By effectively structuring knowledge and verifying data inputs, we can significantly enhance the performance and dependability of complex multi-agent systems. Structured outputs ensure consistency and prevent errors like data loss, thereby guaranteeing that brokers can collaborate efficiently. By employing these methods, developers can craft robust, autonomous systems capable of tackling complex tasks with enhanced accuracy and dependability.
Steadily Requested Questions
Ans. Agent-based programs comprise multiple brokers operating in tandem to address challenges, converse, and cooperate, thereby providing more robust solutions compared to individual systems like LLMs.
Ans. CrewAI is a pioneering framework that enables autonomous agents to collaborate seamlessly, allowing brokers to work harmoniously in resolving complex tasks. Our article leverages CrewAI’s cutting-edge technology in a meticulous manner, crafting outputs that ensure the accurate management of knowledge between agents.
Ans. To insert an image into CrewAI, you can create a variable that holds the URL of the desired picture and then pass this variable as part of the inputs argument when calling the crew.kickoff() function.
Ans. Pydantic models are Python objects that provide knowledge validation and serialization capabilities. They ensure that inputs and outputs between brokers are accurately formatted, thereby guaranteeing more reliable outcomes in agent-based applications.
Ans. Structured outputs utilize Pydantic models to define anticipated fields such as identify, email, and more, ensuring the subsequent agent receives accurate and well-formatted data for seamless processing.