2.6 C
United States of America
Thursday, December 26, 2024

What are Agentic Flows in CrewAI?


Need to simplify the creation and administration of AI workflows? CrewAI flows provide structured patterns for orchestrating AI agent interactions. They permit builders to successfully mix coding duties and Crews, providing a robust framework for growing AI automation. With Agentic Flows in CrewAI, you may design structured, event-driven workflows that streamline activity coordination, handle state, and management execution inside your AI functions.

What are Agentic Flows in CrewAI?

What are Crews?

Crews from crewAI allow the orchestration of AI brokers for activity automation. It facilitates seamless collaboration between brokers to unravel advanced issues. So why “flows” you ask? CrewAI flows are structured patterns for orchestrating AI agent interactions. They outline how brokers collaborate and talk to attain duties. These Flows encompass a sequence of duties the place the output of 1 activity can set off the following, and the system offers versatile mechanisms for state administration and conditional execution management. 

What are Flows?

Crew Flows
Supply: Creator

Flows are event-driven, which means that they react to particular triggers or circumstances. You’ll be able to design workflows that dynamically regulate based mostly on the execution outcomes from completely different duties, enabling seamless execution of advanced AI processes. 

Workflow Management

In CrewAI Flows, builders can construction the move of duties and management how data passes between them. Duties might be chained collectively, making a logical move of operations. This construction allows builders to outline a sequence of operations the place sure duties are executed conditionally based mostly on the output of earlier duties.

State Administration

We are able to use Structured State Administration, which makes use of a predefined schema, usually by Pydantic’s BaseModel, to make sure that the information handed between duties follows a selected construction. It offers the advantages of kind security, validation, and simpler administration of advanced knowledge states.

Enter Flexibility

Flows can settle for inputs to initialize or replace their state at any level within the execution. Relying on the workflow’s necessities, these inputs might be supplied originally, throughout, or after execution. 

Occasion-Pushed Structure

CrewAI Flows permit workflows to regulate based mostly on the outcomes from completely different duties dynamically. Duties can hear for outputs from earlier steps, enabling a reactive system the place new duties might be triggered based mostly on the outputs of earlier ones. The decorators @hear() and @router() allow this degree of flexibility, permitting builders to hyperlink duties conditionally and dynamically based mostly on their outcomes. Do not forget that the @begin() decorator is used to mark the start line of a Circulate.

Decorators and Conditional Logic Description
@hear() Creates listener strategies triggered by particular occasions or activity outputs.
@router() Permits conditional routing inside the move, permitting completely different execution paths based mostly on the outputs of prior steps. Helpful for managing success or failure outcomes.
or_ Triggers a listener when any of the required strategies emit an output. Ultimate for continuing after any activity completion.
and_ Ensures a listener is triggered solely when all specified strategies emit outputs. Helpful for ready till a number of circumstances or duties are accomplished earlier than continuing.

Job Routing

Flows additionally allow using routing to regulate how execution proceeds based mostly on particular circumstances. The @router() decorator facilitates this by permitting strategies to decide on their execution path based mostly on the outcomes of prior duties. For instance, a technique may test the output of a earlier activity and determine whether or not to proceed alongside one route or one other, relying on whether or not sure circumstances are met.

Additionally learn: Constructing Collaborative AI Brokers With CrewAI

Flows in Motion

Let’s construct an agentic system utilizing flows from CrewAI that recommends motion pictures based mostly on style. This shall be a easy agentic system that may assist us perceive what’s working behind it. 

Installations

!pip set up crewai -U
!pip set up crewai-tools

Warning management

import warnings
warnings.filterwarnings('ignore')

Load setting variables

Go to Serper and get your Serper api-key for Google search. We’ll be utilizing the 4o-mini mannequin from OpenAI.

import os
os.environ["OPENAI_API_KEY"] = ‘’
os.environ['OPENAI_MODEL_NAME'] = 'gpt-4o-mini-2024-07-18'
os.environ["SERPER_API_KEY"]=''

Import needed modules

from crewai import Agent, Job, Crew
from crewai.move.move import hear, begin, and_, or_, router
from crewai_tools import SerperDevTool
from crewai import Circulate
from pydantic import BaseModel

Outline agent

To maintain issues easy, we’ll outline a single agent that every one the duties will use. This agent can have a google search instrument that every one the duties can use. 

movie_agent = Agent(
    position="Suggest in style film particular to the style",
    aim="Present a listing of flicks based mostly on consumer preferences",
    backstory="You're a cinephile, "
              "you suggest good motion pictures to your folks, "
              "the flicks ought to be of the identical style",
    instruments=[SerperDevTool()],
    verbose=True
)

Outline duties

action_task = Job(
    identify="ActionTask",
    description="Recommends a preferred motion film",
    expected_output="A listing of 10 in style motion pictures",
    agent=movie_agent
)
comedy_task = Job(
    identify="ComedyTask",
    description="Recommends a preferred comedy film",
    expected_output="A listing of 10 in style motion pictures",
    agent=movie_agent
)
drama_task = Job(
    identify="DramaTask",
    description="Recommends a preferred drama film",
    expected_output="A listing of 10 in style motion pictures",
    agent=movie_agent
)
sci_fi_task = Job(
    identify="SciFiTask",
    description="Recommends a sci-fi film",
    expected_output="A listing of 10 in style motion pictures",
    agent=movie_agent
)

Outline crews for every style

action_crew = Crew(
    brokers=[movie_agent],
    duties=[action_task],
    verbose=True,
)
comedy_crew = Crew(
    brokers=[movie_agent],
    duties=[comedy_task],
    verbose=True
)
drama_crew = Crew(
    brokers=[movie_agent],
    duties=[drama_task],
    verbose=True
)
sci_fi_crew = Crew(
    brokers=[movie_agent],
    duties=[sci_fi_task],
    verbose=True
)

Outline genres and GenreState

GENRES = ["action", "comedy", "drama", "sci-fi"]
class GenreState(BaseModel):
    style: str = ""

Outline MovieRecommendationFlow

We outline a category inheriting from the Circulate class and we are able to optionally use state performance so as to add or modify state attributes, right here we’ve got already outlined GenreState with style attribute of kind string. (Discover that our pydantic mannequin “GenreState” is handed in sq. brackets)

class MovieRecommendationFlow(Circulate[GenreState]):
    @begin()
    def input_genre(self):
        style = enter("Enter a style: ")
        print(f"Style enter obtained: {style}")
        self.state.style = style
        return style
    @router(input_genre)
    def route_to_crew(self):
        style = self.state.style
        if style not in GENRES:
            elevate ValueError(f"Invalid style: {style}")
        if style == "motion":
            return "motion"
        elif style == "comedy":
            return "comedy"
        elif style == "drama":
            return "drama"
        elif style == "sci-fi":
            return "sci-fi"
    @hear("motion")
    def action_movies(self, style):
        suggestions = action_crew.kickoff()
        return suggestions
    @hear("comedy")
    def comedy_movies(self, style):
        suggestions = comedy_crew.kickoff()
        return suggestions
    @hear("drama")
    def drama_movies(self, style):
        suggestions = drama_crew.kickoff()
        return suggestions
    @hear("sci-fi")
    def sci_fi_movies(self, style):
        suggestions = sci_fi_crew.kickoff()
        return suggestions
    @hear(or_("action_movies", "comedy_movies", "drama_movies", "sci_fi_movies"))
    def finalize_recommendation(self, suggestions):
        print("Closing film suggestions:")
        return suggestions

We must always specify the move of execution by @hear decorator by passing the earlier technique and the output of the earlier technique might be handed as an argument within the subsequent technique. (Be aware: The move ought to begin with the @begin decorator)

The router is getting used right here to determine which technique ought to execute based mostly on the output of the tactic contained in the @router decorator. 

The  or_ specifies that the tactic ought to execute as quickly as any of the strategies within the or_( ) technique returns an output.

(Be aware: use and_( ) if you need the tactic to attend till all outputs are obtained).

Plot the move

move = MovieRecommendationFlow()
move.plot()

Show the move diagram

from IPython.core.show import show, HTML
with open('/content material/crewai_flow.html', 'r') as f:
    html_content = f.learn()
show(HTML(html_content))
Output

This diagram ought to provide you with a greater understanding of what’s occurring. Primarily based on the “enter style,” solely one of many 4 duties is executed, and when one in all them returns an output, the “Finalize Advice” will get triggered. 

Kickoff the move

suggestions = await move.kickoff_async()
Output

I entered sci-fi as enter when requested.

Output

After your complete execution of the Circulate, that is the output I received for the sci-fi film suggestions I needed. 

Additionally learn: CrewAI Multi-Agent System for Writing Article from YouTube Movies

Conclusion

On this article, we’ve explored how CrewAI’s event-driven workflows simplify the creation and administration of AI activity orchestration. By leveraging structured flows, builders can design environment friendly, dynamic AI techniques that allow seamless coordination between duties and brokers. With highly effective instruments just like the @hear(), @router(), and state administration mechanisms, CrewAI permits for versatile and adaptive workflows. The hands-on instance of a film advice system highlights how Agentic Flows in CrewAI might be successfully used to tailor AI functions, with duties reacting to consumer inputs and dynamically adjusting to circumstances.

Additionally, if you’re in search of an AI Agent course on-line then, discover: Agentic AI Pioneer Program.

Ceaselessly Requested Query

Q1. How do I move inputs to a Circulate?

Ans. Use the kickoff() technique with an inputs parameter: move.kickoff(inputs={“counter”: 10}). Right here “counter” is usually a variable used inside activity or agent definitions.  

Q2. What’s the distinction between @begin() and @hear() decorators?

Ans. @begin() marks strategies as move beginning factors that run in parallel. @hear() marks strategies that execute when specified duties full.

Q3. How do I visualize my move?

Ans. Both use move.plot() or run crewai move plot command to generate an interactive HTML visualization.

This fall. Can I incorporate human suggestions right into a Circulate?

Ans. Sure, crewAI Flows help human-in-the-loop suggestions.

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 enthusiastic about Deep Studying and Generative AI.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles