
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, knowledge evaluation, and content material creation. By integrating Google Search, asynchronous execution, and modular structure, we reveal the right way to orchestrate a robust, production-ready agent workflow utilizing the Gemini mannequin. Our aim is that will help you perceive how ADK may be leveraged to construct scalable, clever programs 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 consumer 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 key's required to run this tutorial")
os.environ["GOOGLE_API_KEY"] = api_key
return api_key
We start by putting in the google-adk bundle 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. 🧵 Take a look at the Full Codes right here
@dataclass
class TaskResult:
"""Information construction for process outcomes"""
agent_name: str
process: str
outcome: str
metadata: Dict[str, Any] = None
class AdvancedADKTutorial:
"""Predominant 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 search out
correct, up-to-date data. Present concise, factual summaries with sources.
At all times cite your sources and deal with the newest and dependable data.""",
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. Clear up 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="Professional 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, partaking, and well-structured content material
- Enterprise stories and government summaries
- Technical documentation and explanations
- Content material modifying and enchancment
At all times use skilled tone and correct formatting.""",
description="Professional in content material creation and doc writing"
)
print("✓ Created specialised agent system:")
print(f" • Researcher: Internet 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 technique to run agent with correct error dealing with"""
attempt:
if hasattr(agent, 'generate_content'):
outcome = await agent.generate_content(user_input)
return outcome.textual content if hasattr(outcome, 'textual content') else str(outcome)
elif hasattr(agent, '__call__'):
outcome = await agent(user_input)
return outcome.textual content if hasattr(outcome, 'textual content') else str(outcome)
else:
outcome = str(agent) + f" processed: {user_input[:50]}..."
return outcome
besides Exception as e:
return f"Agent execution error: {str(e)}"
async def demonstrate_single_agent_research(self):
"""Reveal single agent analysis capabilities"""
print("n=== Single Agent Analysis Demo ===")
question = "What are the newest 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",
outcome=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):
"""Reveal 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 outcome as a share."""
print("Math Drawback: 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",
outcome=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):
"""Reveal knowledge evaluation capabilities"""
print("n=== Information Evaluation Agent Demo ===")
data_task = """Analyze this quarterly gross sales knowledge for a tech startup (in 1000's USD):
Q1 2023: $125K, Q2 2023: $143K, Q3 2023: $167K, This fall 2023: $152K
Q1 2024: $187K, Q2 2024: $214K, Q3 2024: $239K, This fall 2024: $263K
Calculate progress traits, determine patterns, and supply enterprise insights."""
print("Information Evaluation: Quarterly Gross sales Developments")
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",
outcome=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):
"""Reveal 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. Current quantum computing developments
2. Robust monetary progress traits exhibiting 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",
outcome=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" • Whole brokers created: {len(self.brokers)}")
print(f" • Whole 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 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}. {outcome.agent_name.title()}: {outcome.process}")
print(f" Consequence: {outcome.outcome[: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 classes")
print("="*70)
print("✅ Tutorial accomplished efficiently! Blissful 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 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 predominant():
"""Predominant 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🎯 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
attempt:
from IPython import get_ipython
if get_ipython() is just not None:
return asyncio.create_task(predominant())
besides ImportError:
go
return asyncio.run(predominant())
if __name__ == "__main__":
attempt:
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 primary() 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 all the things seamlessly with await predominant() in Colab.
In conclusion, we’ve got efficiently created and deployed a completely practical 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 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 acquire 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.
Take a look at the Full Codes right here. All credit score for this analysis goes to the researchers of this undertaking. Additionally, be happy to comply with us on Twitter and don’t neglect to hitch 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.