On this tutorial, we discover the superior capabilities of Google’s Agent Growth 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 net analysis, mathematical computation, knowledge evaluation, and content material creation. By integrating Google Search, asynchronous execution, and modular structure, we display 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 programs appropriate for enterprise purposes. 🧵 Try 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 atmosphere 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's 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 atmosphere or securely immediate for it utilizing the getpass module. This ensures our brokers can work together with Google’s instruments and companies seamlessly. 🧵 Try the Full Codes right here
@dataclass
class TaskResult:
"""Information construction for job outcomes"""
agent_name: str
job: str
consequence: str
metadata: Dict[str, Any] = None
class AdvancedADKTutorial:
"""Most important 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.
At all times cite your sources and concentrate on the newest and dependable info.""",
description="Specialist in net analysis and knowledge 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. At all times clarify your reasoning.""",
description="Skilled in mathematical calculations and drawback fixing"
)
self.brokers['analyst'] = Agent(
title="analyst",
mannequin=self.mannequin,
instruction="""You're a knowledge evaluation knowledgeable. When given numerical knowledge:
1. Calculate primary statistics (imply, median, min, max, vary, std dev)
2. Determine patterns, traits, and outliers
3. Present enterprise insights and interpretations
4. Present all calculations step-by-step
5. Counsel actionable suggestions based mostly on the info""",
description="Specialist in knowledge 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 enhancing and enchancment
At all times use skilled tone and correct formatting.""",
description="Skilled in content material creation and doc writing"
)
print("✓ Created specialised agent system:")
print(f" • Researcher: Net search and knowledge 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"""
strive:
if hasattr(agent, 'generate_content'):
consequence = await agent.generate_content(user_input)
return consequence.textual content if hasattr(consequence, 'textual content') else str(consequence)
elif hasattr(agent, '__call__'):
consequence = await agent(user_input)
return consequence.textual content if hasattr(consequence, 'textual content') else str(consequence)
else:
consequence = str(agent) + f" processed: {user_input[:50]}..."
return consequence
besides Exception as e:
return f"Agent execution error: {str(e)}"
async def demonstrate_single_agent_research(self):
"""Display 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}")
strive:
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",
job="Quantum Computing Analysis",
consequence=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):
"""Display mathematical calculation capabilities"""
print("n=== Calculator Agent Demo ===")
calc_problem = """Calculate the compound annual development 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
Specific the consequence as a share."""
print("Math Downside: CAGR Calculation")
strive:
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",
job="CAGR Calculation",
consequence=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):
"""Display knowledge evaluation capabilities"""
print("n=== Information Evaluation Agent Demo ===")
data_task = """Analyze this quarterly gross sales knowledge for a tech startup (in hundreds 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 development traits, determine patterns, and supply enterprise insights."""
print("Information Evaluation: Quarterly Gross sales Traits")
strive:
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",
job="Gross sales Information Evaluation",
consequence=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):
"""Display content material creation capabilities"""
print("n=== Content material Creation Agent Demo ===")
writing_task = """Create a quick government abstract (2-3 paragraphs) for a board presentation
that mixes the important thing findings from:
1. Latest quantum computing developments
2. Robust monetary development traits exhibiting 58% year-over-year development
3. Suggestions for strategic planning
Use skilled enterprise language appropriate for C-level executives."""
print("Content material Creation: Government Abstract")
strive:
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",
job="Government Abstract",
consequence=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 net analysis with Google Search integration")
print(" • Complicated mathematical computations and monetary evaluation")
print(" • Statistical knowledge 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 software 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, lead to enumerate(self.outcomes, 1):
print(f" {i}. {consequence.agent_name.title()}: {consequence.job}")
print(f" End result: {consequence.consequence[:100]}...")
print(f"n🎯 PRODUCTION READINESS:")
print(" • Code follows ADK greatest 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! Comfortable Agent Constructing! 🎉")
print("="*70)
We outline a TaskResult knowledge 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. By way of asynchronous strategies, we display every agent’s capabilities and compile a ultimate abstract of their efficiency and insights. 🧵 Try the Full Codes right here
async def predominant():
"""Most important tutorial execution operate"""
print("🚀 Google ADK Python - Superior Tutorial")
print("=" * 50)
strive:
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🎯 Operating 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 atmosphere"""
import asyncio
strive:
from IPython import get_ipython
if get_ipython() isn't None:
return asyncio.create_task(predominant())
besides ImportError:
cross
return asyncio.run(predominant())
if __name__ == "__main__":
strive:
loop = asyncio.get_running_loop()
print("Detected Pocket book atmosphere. Please run: await predominant()")
besides RuntimeError:
asyncio.run(predominant())
await predominant()
We finalize the tutorial by defining the principle() operate, 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 part seamlessly with await predominant() in Colab.
In conclusion, we have now efficiently created and deployed a totally purposeful 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 advanced monetary equations to analyzing knowledge traits and producing government summaries. We additionally spotlight how the ADK framework helps error dealing with, extensibility, and seamless integration with instruments. By way of this hands-on expertise, we achieve confidence in utilizing ADK to develop sturdy agent-based options for real-world issues, and we’re excited to discover much more superior orchestration and deployment methods shifting ahead.
Try the Full Codes right here. All credit score for this analysis goes to the researchers of this mission. Additionally, be at liberty to observe us on Twitter and don’t neglect to hitch our 100k+ ML SubReddit and Subscribe to our E-newsletter.
🧵 You may additionally 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 reputation amongst audiences.
Elevate your perspective with NextTech Information, the place innovation meets perception.
Uncover the most recent breakthroughs, get unique updates, and join with a worldwide community of future-focused thinkers.
Unlock tomorrow’s traits right this moment: learn extra, subscribe to our publication, and turn out to be a part of the NextTech neighborhood at NextTech-news.com

