HomeArtificial IntelligenceA Coding Information to Construct a Scalable Multi-Agent System with Google ADK

A Coding Information to Construct a Scalable Multi-Agent System with Google ADK


On this tutorial, we discover the superior capabilities of Google’s Agent Improvement Equipment (ADK) by constructing a multi-agent system geared up with specialised roles and instruments. We information you thru creating brokers tailor-made for duties corresponding to internet analysis, mathematical computation, information evaluation, and content material creation. By integrating Google Search, asynchronous execution, and modular structure, we reveal how one can orchestrate a strong, production-ready agent workflow utilizing the Gemini mannequin. Our purpose is that can assist you perceive how ADK could be leveraged to construct scalable, clever techniques appropriate for enterprise purposes. 🧵 Take a look at the Full Codes right here

!pip set up google-adk


import os
import asyncio
import json
from typing import Record, Dict, Any
from dataclasses import dataclass
from google.adk.brokers import Agent, LlmAgent
from google.adk.instruments import google_search


def get_api_key():
   """Get API key from person enter or surroundings variable"""
   api_key = os.getenv("GOOGLE_API_KEY")
   if not api_key:
       from getpass import getpass
       api_key = getpass("Enter your Google API Key: ")
       if not api_key:
           increase ValueError("API secret is required to run this tutorial")
       os.environ["GOOGLE_API_KEY"] = api_key
   return api_key

We start by putting in the google-adk package deal and importing the required libraries to construct our agent system. To authenticate our entry, we retrieve the Google API key both from the surroundings or securely immediate for it utilizing the getpass module. This ensures our brokers can work together with Google’s instruments and providers seamlessly. 🧵 Take a look at the Full Codes right here

@dataclass
class TaskResult:
   """Information construction for process outcomes"""
   agent_name: str
   process: str
   end result: str
   metadata: Dict[str, Any] = None


class AdvancedADKTutorial:
   """Major tutorial class demonstrating ADK capabilities"""
  
   def __init__(self):
       self.mannequin = "gemini-1.5-flash"
       self.brokers = {}
       self.outcomes = []
      
   def create_specialized_agents(self):
       """Create a multi-agent system with specialised roles"""
      
       self.brokers['researcher'] = Agent(
           title="researcher",
           mannequin=self.mannequin,
           instruction="""You're a analysis specialist. Use Google Search to seek out
           correct, up-to-date info. Present concise, factual summaries with sources.
           All the time cite your sources and concentrate on the newest and dependable info.""",
           description="Specialist in internet analysis and data gathering",
           instruments=[google_search]
       )
      
       self.brokers['calculator'] = Agent(
           title="calculator",
           mannequin=self.mannequin,
           instruction="""You're a arithmetic knowledgeable. Resolve calculations step-by-step.
           Present your work clearly and double-check outcomes. Deal with arithmetic, algebra,
           geometry, statistics, and monetary calculations. All the time clarify your reasoning.""",
           description="Knowledgeable in mathematical calculations and downside fixing"
       )
      
       self.brokers['analyst'] = Agent(
           title="analyst",
           mannequin=self.mannequin,
           instruction="""You're a information evaluation knowledgeable. When given numerical information:
           1. Calculate fundamental statistics (imply, median, min, max, vary, std dev)
           2. Determine patterns, developments, and outliers
           3. Present enterprise insights and interpretations
           4. Present all calculations step-by-step
           5. Recommend actionable suggestions based mostly on the info""",
           description="Specialist in information evaluation and statistical insights"
       )
      
       self.brokers['writer'] = Agent(
           title="author",
           mannequin=self.mannequin,
           instruction="""You're a skilled writing assistant. Assist with:
           - Creating clear, participating, and well-structured content material
           - Enterprise stories and government summaries
           - Technical documentation and explanations
           - Content material modifying and enchancment
           All the time use skilled tone and correct formatting.""",
           description="Knowledgeable in content material creation and doc writing"
       )
      
       print("âś“ Created specialised agent system:")
       print(f"  • Researcher: Net search and data gathering")
       print(f"  • Calculator: Mathematical computations and evaluation")
       print(f"  • Analyst: Information evaluation and statistical insights")
       print(f"  • Author: Skilled content material creation")
  
   async def run_agent_with_input(self, agent, user_input):
       """Helper methodology to run agent with correct error dealing with"""
       attempt:
           if hasattr(agent, 'generate_content'):
               end result = await agent.generate_content(user_input)
               return end result.textual content if hasattr(end result, 'textual content') else str(end result)
           elif hasattr(agent, '__call__'):
               end result = await agent(user_input)
               return end result.textual content if hasattr(end result, 'textual content') else str(end result)
           else:
               end result = str(agent) + f" processed: {user_input[:50]}..."
               return end result
       besides Exception as e:
           return f"Agent execution error: {str(e)}"
  
   async def demonstrate_single_agent_research(self):
       """Show single agent analysis capabilities"""
       print("n=== Single Agent Analysis Demo ===")
      
       question = "What are the most recent developments in quantum computing breakthroughs in 2024?"
       print(f"Analysis Question: {question}")
      
       attempt:
           response_text = await self.run_agent_with_input(
               agent=self.brokers['researcher'],
               user_input=question
           )
           abstract = response_text[:300] + "..." if len(response_text) > 300 else response_text
          
           task_result = TaskResult(
               agent_name="researcher",
               process="Quantum Computing Analysis",
               end result=abstract
           )
           self.outcomes.append(task_result)
          
           print(f"âś“ Analysis Full: {abstract}")
           return response_text
          
       besides Exception as e:
           error_msg = f"Analysis failed: {str(e)}"
           print(f"❌ {error_msg}")
           return error_msg
  
   async def demonstrate_calculator_agent(self):
       """Show mathematical calculation capabilities"""
       print("n=== Calculator Agent Demo ===")
      
       calc_problem = """Calculate the compound annual progress fee (CAGR) for an funding
       that grows from $50,000 to $125,000 over 8 years. Use the system:
       CAGR = (Ending Worth / Starting Worth)^(1/variety of years) - 1
       Categorical the end result as a share."""
      
       print("Math Downside: CAGR Calculation")
      
       attempt:
           response_text = await self.run_agent_with_input(
               agent=self.brokers['calculator'],
               user_input=calc_problem
           )
           abstract = response_text[:250] + "..." if len(response_text) > 250 else response_text
          
           task_result = TaskResult(
               agent_name="calculator",
               process="CAGR Calculation",
               end result=abstract
           )
           self.outcomes.append(task_result)
          
           print(f"âś“ Calculation Full: {abstract}")
           return response_text
          
       besides Exception as e:
           error_msg = f"Calculation failed: {str(e)}"
           print(f"❌ {error_msg}")
           return error_msg
  
   async def demonstrate_data_analysis(self):
       """Show information evaluation capabilities"""
       print("n=== Information Evaluation Agent Demo ===")
      
       data_task = """Analyze this quarterly gross sales information for a tech startup (in 1000's USD):
       Q1 2023: $125K, Q2 2023: $143K, Q3 2023: $167K, This autumn 2023: $152K
       Q1 2024: $187K, Q2 2024: $214K, Q3 2024: $239K, This autumn 2024: $263K
      
       Calculate progress developments, establish patterns, and supply enterprise insights."""
      
       print("Information Evaluation: Quarterly Gross sales Traits")
      
       attempt:
           response_text = await self.run_agent_with_input(
               agent=self.brokers['analyst'],
               user_input=data_task
           )
           abstract = response_text[:250] + "..." if len(response_text) > 250 else response_text
          
           task_result = TaskResult(
               agent_name="analyst",
               process="Gross sales Information Evaluation",
               end result=abstract
           )
           self.outcomes.append(task_result)
          
           print(f"âś“ Evaluation Full: {abstract}")
           return response_text
          
       besides Exception as e:
           error_msg = f"Evaluation failed: {str(e)}"
           print(f"❌ {error_msg}")
           return error_msg
  
   async def demonstrate_content_creation(self):
       """Show content material creation capabilities"""
       print("n=== Content material Creation Agent Demo ===")
      
       writing_task = """Create a short government abstract (2-3 paragraphs) for a board presentation
       that mixes the important thing findings from:
       1. Latest quantum computing developments
       2. Robust monetary progress developments displaying 58% year-over-year progress
       3. Suggestions for strategic planning
      
       Use skilled enterprise language appropriate for C-level executives."""
      
       print("Content material Creation: Government Abstract")
      
       attempt:
           response_text = await self.run_agent_with_input(
               agent=self.brokers['writer'],
               user_input=writing_task
           )
           abstract = response_text[:250] + "..." if len(response_text) > 250 else response_text
          
           task_result = TaskResult(
               agent_name="author",
               process="Government Abstract",
               end result=abstract
           )
           self.outcomes.append(task_result)
          
           print(f"âś“ Content material Created: {abstract}")
           return response_text
          
       besides Exception as e:
           error_msg = f"Content material creation failed: {str(e)}"
           print(f"❌ {error_msg}")
           return error_msg
  
   def display_comprehensive_summary(self):
       """Show complete tutorial abstract and outcomes"""
       print("n" + "="*70)
       print("🚀 ADVANCED ADK TUTORIAL - COMPREHENSIVE SUMMARY")
       print("="*70)
      
       print(f"n📊 EXECUTION STATISTICS:")
       print(f"   • Complete brokers created: {len(self.brokers)}")
       print(f"   • Complete duties accomplished: {len(self.outcomes)}")
       print(f"   • Mannequin used: {self.mannequin} (Free Tier)")
       print(f"   • Runner sort: Direct Agent Execution")
      
       print(f"n🤖 AGENT CAPABILITIES DEMONSTRATED:")
       print("   • Superior internet analysis with Google Search integration")
       print("   • Complicated mathematical computations and monetary evaluation")
       print("   • Statistical information evaluation with enterprise insights")
       print("   • Skilled content material creation and documentation")
       print("   • Asynchronous agent execution and error dealing with")
      
       print(f"n🛠️ KEY ADK FEATURES COVERED:")
       print("   • Agent() class with specialised directions")
       print("   • Constructed-in instrument integration (google_search)")
       print("   • InMemoryRunner for agent execution")
       print("   • Async/await patterns for concurrent operations")
       print("   • Skilled error dealing with and logging")
       print("   • Modular, scalable agent structure")
      
       print(f"nđź“‹ TASK RESULTS SUMMARY:")
       for i, end in enumerate(self.outcomes, 1):
           print(f"   {i}. {end result.agent_name.title()}: {end result.process}")
           print(f"      Outcome: {end result.end result[:100]}...")
      
       print(f"n🎯 PRODUCTION READINESS:")
       print("   • Code follows ADK finest practices")
       print("   • Prepared for deployment on Cloud Run")
       print("   • Suitable with Vertex AI Agent Engine")
       print("   • Scalable multi-agent structure")
       print("   • Enterprise-grade error dealing with")
      
       print(f"nđź”— NEXT STEPS:")
       print("   • Discover sub-agent delegation with LlmAgent")
       print("   • Add customized instruments and integrations")
       print("   • Deploy to Google Cloud for manufacturing use")
       print("   • Implement persistent reminiscence and periods")
      
       print("="*70)
       print("✅ Tutorial accomplished efficiently! Glad Agent Constructing! 🎉")
       print("="*70)

We outline a TaskResult information construction to retailer outputs from every agent. Then, we construct a multi-agent system utilizing Google ADK, assigning specialised roles like researcher, calculator, analyst, and author. Via asynchronous strategies, we reveal every agent’s capabilities and compile a closing abstract of their efficiency and insights. 🧵 Take a look at the Full Codes right here

async def primary():
   """Major tutorial execution perform"""
   print("🚀 Google ADK Python - Superior Tutorial")
   print("=" * 50)
  
   attempt:
       api_key = get_api_key()
       print("âś… API key configured efficiently")
   besides Exception as e:
       print(f"❌ Error: {e}")
       return
  
   tutorial = AdvancedADKTutorial()
  
   tutorial.create_specialized_agents()
  
   print(f"n🎯 Working complete agent demonstrations...")
  
   await tutorial.demonstrate_single_agent_research()
   await tutorial.demonstrate_calculator_agent()
   await tutorial.demonstrate_data_analysis()
   await tutorial.demonstrate_content_creation()
  
   tutorial.display_comprehensive_summary()


def run_tutorial():
   """Run the tutorial in Jupyter/Colab surroundings"""
   import asyncio
  
   attempt:
       from IPython import get_ipython
       if get_ipython() isn't None:
           return asyncio.create_task(primary())
   besides ImportError:
       go
  
   return asyncio.run(primary())


if __name__ == "__main__":
   attempt:
       loop = asyncio.get_running_loop()
       print("Detected Pocket book surroundings. Please run: await primary()")
   besides RuntimeError:
       asyncio.run(primary())


await primary()

We finalize the tutorial by defining the principle() perform, which initializes the system, runs all agent demonstrations, and shows a abstract. We guarantee compatibility with each script and pocket book environments, permitting us to run every little thing seamlessly with await primary() in Colab.

In conclusion, we’ve got efficiently created and deployed a completely useful multi-agent system utilizing Google ADK. We’ve seen our brokers deal with a various vary of duties, from conducting real-time analysis and fixing complicated monetary equations to analyzing information developments and producing government summaries. We additionally spotlight how the ADK framework helps error dealing with, extensibility, and seamless integration with instruments. Via this hands-on expertise, we acquire confidence in utilizing ADK to develop strong agent-based options for real-world issues, and we’re excited to discover much more superior orchestration and deployment methods shifting ahead.


Take a look at the Full Codes right here. All credit score for this analysis goes to the researchers of this venture. Additionally, be happy to observe us on Twitter and don’t overlook to affix our 100k+ ML SubReddit and Subscribe to our Publication.

🧵 You might also like NVIDIA’s Open Sourced Cosmos DiffusionRenderer [Check it now]


Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is dedicated to harnessing the potential of Synthetic Intelligence for social good. His most up-to-date endeavor is the launch of an Synthetic Intelligence Media Platform, Marktechpost, which stands out for its in-depth protection of machine studying and deep studying information that’s each technically sound and simply comprehensible by a large viewers. The platform boasts of over 2 million month-to-month views, illustrating its recognition amongst audiences.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments