• bitcoinBitcoin(BTC)$83,097.00-1.62%
  • ethereumEthereum(ETH)$2,648.42-2.06%
  • tetherTether(USDT)$1.000.01%
  • binancecoinBNB(BNB)$764.57-1.11%
  • rippleXRP(XRP)$1.48-2.57%
  • usd-coinUSDC(USDC)$1.000.00%
  • solanaSolana(SOL)$118.95-1.81%
  • tronTRON(TRX)$0.333179-0.01%
  • zcashZcash(ZEC)$1,550.07-6.37%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.06-0.39%
  • HyperliquidHyperliquid(HYPE)$89.10-4.15%
  • dogecoinDogecoin(DOGE)$0.093189-3.33%
  • chainlinkChainlink(LINK)$13.82-2.60%
  • moneroMonero(XMR)$534.00-4.71%
  • whitebitWhiteBIT Coin(WBT)$82.89-1.67%
  • USDSUSDS(USDS)$1.000.01%
  • cardanoCardano(ADA)$0.245876-2.95%
  • RainRain(RAIN)$0.012527-1.39%
  • leo-tokenLEO Token(LEO)$9.080.67%
  • stellarStellar(XLM)$0.209147-3.07%
  • nearNEAR Protocol(NEAR)$5.16-5.39%
  • bitcoin-cashBitcoin Cash(BCH)$308.93-6.81%
  • uniswapUniswap(UNI)$9.24-6.41%
  • litecoinLitecoin(LTC)$70.66-1.95%
  • CantonCanton(CC)$0.1360830.23%
  • avalanche-2Avalanche(AVAX)$10.58-2.83%
  • suiSui(SUI)$1.212.13%
  • Ethena USDeEthena USDe(USDE)$1.000.02%
  • daiDai(DAI)$1.000.01%
  • the-open-networkGram (prev. Toncoin)(GRAM)$1.611.50%
  • USD1USD1(USD1)$1.000.01%
  • hedera-hashgraphHedera(HBAR)$0.0971163.55%
  • quant-networkQuant(QNT)$268.5253.25%
  • BitwayBitway(BTW)$1.3325.63%
  • BittensorBittensor(TAO)$305.85-5.96%
  • shiba-inuShiba Inu(SHIB)$0.000006-3.53%
  • Global DollarGlobal Dollar(USDG)$1.000.01%
  • crypto-com-chainCronos(CRO)$0.064498-3.74%
  • tether-goldTether Gold(XAUT)$4,188.37-2.10%
  • OndoOndo(ONDO)$0.587.86%
  • paypal-usdPayPal USD(PYUSD)$1.000.01%
  • MemeCoreMemeCore(M)$1.18-3.97%
  • EthenaEthena(ENA)$0.265181-2.76%
  • Ripple USDRipple USD(RLUSD)$1.000.02%
  • okbOKB(OKB)$117.30-3.13%
  • Circle USYCCircle USYC(USYC)$1.140.00%
  • Pump.funPump.fun(PUMP)$0.00514516.05%
  • aaveAave(AAVE)$149.72-4.33%
  • BlackRock USD Institutional Digital Liquidity FundBlackRock USD Institutional Digital Liquidity Fund(BUIDL)$1.000.00%
  • Ondo US Dollar YieldOndo US Dollar Yield(USDY)$1.15-0.08%
TradePoint.io
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop
No Result
View All Result
TradePoint.io
No Result
View All Result

A Coding Guide to Build a Hierarchical Supervisor Agent Framework with CrewAI and Google Gemini for Coordinated Multi-Agent Workflows

September 30, 2025
in AI & Technology
Reading Time: 4 mins read
A A
A Coding Guide to Build a Hierarchical Supervisor Agent Framework with CrewAI and Google Gemini for Coordinated Multi-Agent Workflows
ShareShareShareShareShare

YOU MAY ALSO LIKE

20 Agentic Use Cases of TypeSafe AI’s Jev

Google Research Introduces an AI Video Co-Director: 4 Agentic Frameworks for Coherent, Minutes-Long Video Generation

@dataclass
class TaskConfig:
   description: str
   expected_output: str
   priority: TaskPriority
   max_execution_time: int = 300 
   requires_human_input: bool = False


class SupervisorFramework:
   """
   Advanced Supervisor Agent Framework using CrewAI
   Manages multiple specialized agents with hierarchical coordination
   """
  
   def __init__(self, gemini_api_key: str, serper_api_key: str = None):
       """
       Initialize the supervisor framework
      
       Args:
           gemini_api_key: Google Gemini API key (free tier)
           serper_api_key: Serper API key for web search (optional, has free tier)
       """
       os.environ["GOOGLE_API_KEY"] = gemini_api_key
       if serper_api_key:
           os.environ["SERPER_API_KEY"] = serper_api_key
      
       self.llm = ChatGoogleGenerativeAI(
           model="gemini-1.5-flash",
           temperature=0.7,
           max_tokens=2048
       )
      
       self.tools = []
       if serper_api_key:
           self.tools.append(SerperDevTool())
      
       self.agents = {}
       self.supervisor = None
       self.crew = None
      
       print("🚀 SupervisorFramework initialized successfully!")
       print(f"📡 LLM Model: {self.llm.model}")
       print(f"🛠️  Available tools: {len(self.tools)}")


   def create_research_agent(self) -> Agent:
       """Create a specialized research agent"""
       return Agent(
           role="Senior Research Analyst",
           goal="Conduct comprehensive research and gather accurate information on any given topic",
           backstory="""You are an expert research analyst with years of experience in
           information gathering, fact-checking, and synthesizing complex data from multiple sources.
           You excel at finding reliable sources and presenting well-structured research findings.""",
           verbose=True,
           allow_delegation=False,
           llm=self.llm,
           tools=self.tools,
           max_iter=3,
           memory=True
       )


   def create_analyst_agent(self) -> Agent:
       """Create a specialized data analyst agent"""
       return Agent(
           role="Strategic Data Analyst",
           goal="Analyze data, identify patterns, and provide actionable insights",
           backstory="""You are a strategic data analyst with expertise in statistical analysis,
           pattern recognition, and business intelligence. You transform raw data and research
           into meaningful insights that drive decision-making.""",
           verbose=True,
           allow_delegation=False,
           llm=self.llm,
           max_iter=3,
           memory=True
       )


   def create_writer_agent(self) -> Agent:
       """Create a specialized content writer agent"""
       return Agent(
           role="Expert Technical Writer",
           goal="Create clear, engaging, and well-structured written content",
           backstory="""You are an expert technical writer with a talent for making complex
           information accessible and engaging. You specialize in creating documentation,
           reports, and content that effectively communicates insights to diverse audiences.""",
           verbose=True,
           allow_delegation=False,
           llm=self.llm,
           max_iter=3,
           memory=True
       )


   def create_reviewer_agent(self) -> Agent:
       """Create a quality assurance reviewer agent"""
       return Agent(
           role="Quality Assurance Reviewer",
           goal="Review, validate, and improve the quality of all deliverables",
           backstory="""You are a meticulous quality assurance expert with an eye for detail
           and a commitment to excellence. You ensure all work meets high standards of accuracy,
           completeness, and clarity before final delivery.""",
           verbose=True,
           allow_delegation=False,
           llm=self.llm,
           max_iter=2,
           memory=True
       )


   def create_supervisor_agent(self) -> Agent:
       """Create the main supervisor agent"""
       return Agent(
           role="Project Supervisor & Coordinator",
           goal="Coordinate team efforts, manage workflows, and ensure project success",
           backstory="""You are an experienced project supervisor with expertise in team
           coordination, workflow optimization, and quality management. You ensure that all
           team members work efficiently towards common goals and maintain high standards
           throughout the project lifecycle.""",
           verbose=True,
           allow_delegation=True,
           llm=self.llm,
           max_iter=2,
           memory=True
       )


   def setup_agents(self):
       """Initialize all agents in the framework"""
       print("🤖 Setting up specialized agents...")
      
       self.agents = {
           'researcher': self.create_research_agent(),
           'analyst': self.create_analyst_agent(),
           'writer': self.create_writer_agent(),
           'reviewer': self.create_reviewer_agent()
       }
      
       self.supervisor = self.create_supervisor_agent()
      
       print(f"✅ Created {len(self.agents)} specialized agents + 1 supervisor")
      
       for role, agent in self.agents.items():
           print(f"   └── {role.title()}: {agent.role}")


   def create_task_workflow(self, topic: str, task_configs: Dict[str, TaskConfig]) -> List[Task]:
       """
       Create a comprehensive task workflow
      
       Args:
           topic: Main topic/project focus
           task_configs: Dictionary of task configurations
          
       Returns:
           List of CrewAI Task objects
       """
       tasks = []
      
       if 'research' in task_configs:
           config = task_configs['research']
           research_task = Task(
               description=f"{config.description} Focus on: {topic}",
               expected_output=config.expected_output,
               agent=self.agents['researcher']
           )
           tasks.append(research_task)
      
       if 'analysis' in task_configs:
           config = task_configs['analysis']
           analysis_task = Task(
               description=f"{config.description} Analyze the research findings about: {topic}",
               expected_output=config.expected_output,
               agent=self.agents['analyst'],
               context=tasks 
           )
           tasks.append(analysis_task)
      
       if 'writing' in task_configs:
           config = task_configs['writing']
           writing_task = Task(
               description=f"{config.description} Create content about: {topic}",
               expected_output=config.expected_output,
               agent=self.agents['writer'],
               context=tasks
           )
           tasks.append(writing_task)
      
       if 'review' in task_configs:
           config = task_configs['review']
           review_task = Task(
               description=f"{config.description} Review all work related to: {topic}",
               expected_output=config.expected_output,
               agent=self.agents['reviewer'],
               context=tasks
           )
           tasks.append(review_task)
      
       supervisor_task = Task(
           description=f"""As the project supervisor, coordinate the entire workflow for: {topic}.
           Monitor progress, ensure quality standards, resolve any conflicts between agents,
           and provide final project oversight. Ensure all deliverables meet requirements.""",
           expected_output="""A comprehensive project summary including:
           - Executive summary of all completed work
           - Quality assessment of deliverables
           - Recommendations for improvements or next steps
           - Final project status report""",
           agent=self.supervisor,
           context=tasks
       )
       tasks.append(supervisor_task)
      
       return tasks


   def execute_project(self,
                      topic: str,
                      task_configs: Dict[str, TaskConfig],
                      process_type: Process = Process.hierarchical) -> Dict[str, Any]:
       """
       Execute a complete project using the supervisor framework
      
       Args:
           topic: Main project topic
           task_configs: Task configurations
           process_type: CrewAI process type (hierarchical recommended for supervisor)
          
       Returns:
           Dictionary containing execution results
       """
       print(f"🚀 Starting project execution: {topic}")
       print(f"📋 Process type: {process_type.value}")
      
       if not self.agents or not self.supervisor:
           self.setup_agents()
      
       tasks = self.create_task_workflow(topic, task_configs)
       print(f"📝 Created {len(tasks)} tasks in workflow")
      
       crew_agents = list(self.agents.values()) + [self.supervisor]
      
       self.crew = Crew(
           agents=crew_agents,
           tasks=tasks,
           process=process_type,
           manager_llm=self.llm, 
           verbose=True,
           memory=True
       )
      
       print("🎯 Executing project...")
       try:
           result = self.crew.kickoff()
          
           return {
               'status': 'success',
               'result': result,
               'topic': topic,
               'tasks_completed': len(tasks),
               'agents_involved': len(crew_agents)
           }
          
       except Exception as e:
           print(f"❌ Error during execution: {str(e)}")
           return {
               'status': 'error',
               'error': str(e),
               'topic': topic
           }


   def get_crew_usage_metrics(self) -> Dict[str, Any]:
       """Get usage metrics from the crew"""
       if not self.crew:
           return {'error': 'No crew execution found'}
      
       try:
           return {
               'total_tokens_used': getattr(self.crew, 'total_tokens_used', 'Not available'),
               'total_cost': getattr(self.crew, 'total_cost', 'Not available'),
               'execution_time': getattr(self.crew, 'execution_time', 'Not available')
           }
       except:
           return {'note': 'Metrics not available for this execution'}

Credit: Source link

ShareTweetSendSharePin

Related Posts

20 Agentic Use Cases of TypeSafe AI’s Jev
AI & Technology

20 Agentic Use Cases of TypeSafe AI’s Jev

September 28, 2026
Google Research Introduces an AI Video Co-Director: 4 Agentic Frameworks for Coherent, Minutes-Long Video Generation
AI & Technology

Google Research Introduces an AI Video Co-Director: 4 Agentic Frameworks for Coherent, Minutes-Long Video Generation

September 28, 2026
Which Is Better To Use?
AI & Technology

Which Is Better To Use?

September 28, 2026
Are 3D Printers Worth Buying In 2026?
AI & Technology

Are 3D Printers Worth Buying In 2026?

September 28, 2026
Next Post
DeepSeek V3.2-Exp Cuts Long-Context Costs with DeepSeek Sparse Attention (DSA) While Maintaining Benchmark Parity

DeepSeek V3.2-Exp Cuts Long-Context Costs with DeepSeek Sparse Attention (DSA) While Maintaining Benchmark Parity

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search

No Result
View All Result
Japan's Next Chapter

Japan's Next Chapter

September 24, 2026
Pennsylvania teen and his mother charged in stabbing death of college student

Pennsylvania teen and his mother charged in stabbing death of college student

September 26, 2026
5 Prompts For Every ChatGPT New Feature

5 Prompts For Every ChatGPT New Feature

September 25, 2026

About

Learn more

Our Services

Legal

Privacy Policy

Terms of Use

Bloggers

Learn more

Article Links

Contact

Advertise

Ask us anything

©2020- TradePoint.io - All rights reserved!

Tradepoint.io, being just a publishing and technology platform, is not a registered broker-dealer or investment adviser. So we do not provide investment advice. Rather, brokerage services are provided to clients of Tradepoint.io by independent SEC-registered broker-dealers and members of FINRA/SIPC. Every form of investing carries some risk and past performance is not a guarantee of future results. “Tradepoint.io“, “Instant Investing” and “My Trading Tools” are registered trademarks of Apperbuild, LLC.

This website is operated by Apperbuild, LLC. We have no link to any brokerage firm and we do not provide investment advice. Every information and resource we provide is solely for the education of our readers. © 2020 Apperbuild, LLC. All rights reserved.

No Result
View All Result
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop

© 2023 - TradePoint.io - All Rights Reserved!