feat: Introduce Sequential Agent tutorial for google ADK
This commit is contained in:
parent
b837c057da
commit
b5d047ee7c
6 changed files with 419 additions and 1 deletions
|
|
@ -0,0 +1,3 @@
|
|||
# If using Gemini via Google AI Studio
|
||||
GOOGLE_GENAI_USE_VERTEXAI=False
|
||||
GOOGLE_API_KEY="your-api-key"
|
||||
|
|
@ -0,0 +1,146 @@
|
|||
# 🎯 Tutorial 9.1: Sequential Agents - Business Implementation Plan Generator
|
||||
|
||||
## 🎯 What You'll Learn
|
||||
|
||||
- **Sequential Agent Composition**: How to orchestrate multiple specialized agents in sequence
|
||||
- **AgentTool Integration**: Wrapping agents as tools for enhanced capabilities
|
||||
- **Web Search Integration**: Real-time market intelligence through search agents
|
||||
- **Business Analysis Pipeline**: From market research to implementation planning
|
||||
- **Streamlit Web Interface**: User-friendly application for business planning
|
||||
|
||||
## 🧠 Core Concept: Sequential Agent with Search Capabilities
|
||||
|
||||
According to the [ADK workflow agents documentation](https://google.github.io/adk-docs/agents/workflow-agents/), **Sequential Agents** execute sub-agents one after another, in sequence. This tutorial demonstrates a **Business Implementation Plan Generator** that combines web search capabilities with sequential analysis:
|
||||
|
||||
```
|
||||
Business Topic → SequentialAgent → 4 Sub-agents (Sequential Execution)
|
||||
↓
|
||||
[Market Research + Web Search] → [SWOT Analysis] → [Strategy] → [Implementation]
|
||||
↓
|
||||
Complete Business Implementation Plan
|
||||
```
|
||||
|
||||
**Key Innovation**: The Market Research Agent uses a specialized Search Agent (wrapped as AgentTool) to access real-time web search capabilities for current market intelligence.
|
||||
|
||||
## 📁 Project Structure
|
||||
|
||||
```
|
||||
9_1_sequential_agent/
|
||||
├── agent.py # Business implementation plan generator with search capabilities
|
||||
├── app.py # Streamlit web interface for business planning
|
||||
├── requirements.txt # Python dependencies
|
||||
└── README.md # This documentation
|
||||
```
|
||||
|
||||
## 🚀 Getting Started
|
||||
|
||||
### 1. Install Dependencies
|
||||
```bash
|
||||
cd 9_1_sequential_agent
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
### 2. Set Up Environment
|
||||
Create a `.env` file with your Google API key:
|
||||
```bash
|
||||
echo "GOOGLE_API_KEY=your_ai_studio_key_here" > .env
|
||||
```
|
||||
|
||||
**Important**: Get your API key from [Google AI Studio](https://aistudio.google.com/)
|
||||
|
||||
### 3. Run the Streamlit App
|
||||
```bash
|
||||
streamlit run app.py
|
||||
```
|
||||
|
||||
This will launch the **Business Implementation Plan Generator Agent** web interface!
|
||||
|
||||
## 🧪 How It Works
|
||||
|
||||
### **Business Implementation Plan Generation Pipeline**
|
||||
|
||||
The agent processes business opportunities through a sophisticated 4-step sequential workflow:
|
||||
|
||||
1. **🔍 Market Analysis** - Uses web search for current market information and competitive research
|
||||
2. **📊 SWOT Analysis** - Strategic assessment of strengths, weaknesses, opportunities, and threats
|
||||
3. **🎯 Strategy Development** - Strategic objectives and action plans
|
||||
4. **📋 Implementation Planning** - Detailed execution roadmap and resource requirements
|
||||
|
||||
**Key Innovation**: The Market Analysis Agent has access to a specialized Search Agent (wrapped as AgentTool) that can perform real-time web searches using the `google_search` tool. This provides current market intelligence that feeds into the sequential analysis pipeline.
|
||||
|
||||
The `SequentialAgent` ensures each step builds upon the previous step's output, creating a comprehensive business implementation plan ready for execution.
|
||||
|
||||
**Result**: A complete business implementation plan with market research, strategic analysis, and execution roadmap.
|
||||
|
||||
## 🔧 ADK Concepts Demonstrated
|
||||
|
||||
### **1. SequentialAgent Pattern**
|
||||
The core workflow orchestrator that executes sub-agents in sequence, ensuring each step builds upon the previous step's output.
|
||||
|
||||
### **2. AgentTool Integration**
|
||||
Advanced pattern where one agent (Search Agent) is wrapped as a tool and used by another agent (Market Researcher) to enhance capabilities.
|
||||
|
||||
### **3. Web Search Capabilities**
|
||||
Real-time market intelligence through integrated search functionality, providing current data rather than relying on training data.
|
||||
|
||||
### **4. Sub-agent Specialization**
|
||||
Each sub-agent specializes in a specific business analysis phase, creating a modular and maintainable system.
|
||||
|
||||
### **5. Session Management**
|
||||
Maintains conversation state across the entire analysis pipeline, ensuring context flows between agents.
|
||||
|
||||
### **6. Runner Execution**
|
||||
Processes the complete business implementation workflow with proper error handling and response management.
|
||||
|
||||
## 🧪 Sample Topics to Try
|
||||
|
||||
- **Electric vehicle charging stations** in urban areas
|
||||
- **AI-powered healthcare diagnostics** and patient care
|
||||
- **Sustainable food delivery** services and packaging
|
||||
- **Remote work collaboration** tools and platforms
|
||||
- **Renewable energy storage** solutions
|
||||
|
||||
## 📊 Expected Output
|
||||
|
||||
The sequential agent will provide:
|
||||
1. **Market Research**: Competitive analysis and market trends
|
||||
2. **SWOT Analysis**: Strategic assessment with actionable insights
|
||||
3. **Strategy Plan**: Clear objectives and implementation steps
|
||||
4. **Implementation Roadmap**: Practical execution guidance
|
||||
|
||||
## 🎯 Learning Objectives
|
||||
|
||||
- ✅ Understand how `SequentialAgent` orchestrates sub-agents
|
||||
- ✅ Learn to execute sequential agents with Runner and Session management
|
||||
- ✅ See how sub-agents can build upon each other's output
|
||||
- ✅ Experience a working, executable sequential workflow
|
||||
- ✅ Understand AgentTool integration for enhanced capabilities
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
- Try different business topics to see the sequential workflow in action
|
||||
- Experiment with reordering the sub-agents
|
||||
- Add more specialized agents to the pipeline
|
||||
- Explore other ADK workflow patterns (Parallel, Branching)
|
||||
|
||||
## 🔧 Troubleshooting
|
||||
|
||||
**Common Issues:**
|
||||
- **API Key Error**: Ensure `GOOGLE_API_KEY` is set in `.env`
|
||||
- **Import Errors**: Make sure you're in the correct directory
|
||||
- **Search Tool Errors**: Verify your API key has access to search capabilities
|
||||
|
||||
**Pro Tips:**
|
||||
- Start with simple topics to understand the flow
|
||||
- Use the Streamlit app for easy testing and visualization
|
||||
- The sequential pattern is great for predictable, step-by-step processes
|
||||
- Web search integration provides real-time market intelligence
|
||||
|
||||
## 📚 Key Takeaways
|
||||
|
||||
- **SequentialAgent** is perfect for workflows that must happen in order
|
||||
- **AgentTool integration** allows agents to enhance each other's capabilities
|
||||
- **Web search capabilities** provide current market intelligence
|
||||
- **Sub-agents** can be simple `LlmAgent` instances or complex tool-enabled agents
|
||||
- **Clean, readable code** makes it easy to understand and modify
|
||||
- **Streamlit interface** provides user-friendly access to complex agent workflows
|
||||
|
|
@ -0,0 +1,146 @@
|
|||
import os
|
||||
import asyncio
|
||||
from dotenv import load_dotenv
|
||||
from google.adk.agents import LlmAgent, SequentialAgent
|
||||
from google.adk.tools import google_search
|
||||
from google.adk.tools.agent_tool import AgentTool
|
||||
from google.adk.sessions import InMemorySessionService
|
||||
from google.adk.runners import Runner
|
||||
from google.genai import types
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
# --- Search Agent (Wrapped as AgentTool) ---
|
||||
search_agent = LlmAgent(
|
||||
name="search_agent",
|
||||
model="gemini-2.0-flash",
|
||||
description="Conducts web search for current market information and competitive analysis",
|
||||
instruction=(
|
||||
"You are a web search specialist. When given a business topic:\n"
|
||||
"1. Use web search to find current market information\n"
|
||||
"2. Identify key competitors and their market position\n"
|
||||
"3. Gather recent industry trends and market data\n"
|
||||
"4. Find market size estimates and growth projections\n"
|
||||
"5. Provide comprehensive, up-to-date market analysis\n\n"
|
||||
"Always use web search to get the most current information available."
|
||||
),
|
||||
tools=[google_search]
|
||||
)
|
||||
|
||||
# --- Simple Sub-agents ---
|
||||
market_researcher = LlmAgent(
|
||||
name="market_researcher",
|
||||
model="gemini-2.5-flash",
|
||||
description="Conducts market research and competitive analysis using search capabilities",
|
||||
instruction=(
|
||||
"You are a market research specialist. Given a business topic:\n"
|
||||
"1. Use the search_agent to gather current market information\n"
|
||||
"2. Identify key competitors and their market position\n"
|
||||
"3. Analyze current market trends and opportunities\n"
|
||||
"4. Provide industry insights and market size estimates\n"
|
||||
"5. Synthesize search results into comprehensive market analysis\n\n"
|
||||
"Provide a comprehensive analysis in clear, structured format based on current web research."
|
||||
),
|
||||
tools=[AgentTool(search_agent)]
|
||||
)
|
||||
|
||||
swot_analyzer = LlmAgent(
|
||||
name="swot_analyzer",
|
||||
model="gemini-2.5-flash",
|
||||
description="Performs SWOT analysis based on market research",
|
||||
instruction=(
|
||||
"You are a strategic analyst. Given market research findings:\n"
|
||||
"1. Identify internal strengths and competitive advantages\n"
|
||||
"2. Assess internal weaknesses and limitations\n"
|
||||
"3. Identify external opportunities in the market\n"
|
||||
"4. Evaluate external threats and challenges\n\n"
|
||||
"Provide a clear SWOT analysis with actionable insights."
|
||||
)
|
||||
)
|
||||
|
||||
strategy_formulator = LlmAgent(
|
||||
name="strategy_formulator",
|
||||
model="gemini-2.5-flash",
|
||||
description="Develops strategic objectives and action plans",
|
||||
instruction=(
|
||||
"You are a strategic planner. Given SWOT analysis results:\n"
|
||||
"1. Define 3-5 key strategic objectives\n"
|
||||
"2. Create specific action items for each objective\n"
|
||||
"3. Recommend realistic timeline for implementation\n"
|
||||
"4. Define success metrics and KPIs to track\n\n"
|
||||
"Provide a clear strategic plan with actionable steps."
|
||||
)
|
||||
)
|
||||
|
||||
implementation_planner = LlmAgent(
|
||||
name="implementation_planner",
|
||||
model="gemini-2.5-flash",
|
||||
description="Creates detailed implementation roadmap",
|
||||
instruction=(
|
||||
"You are an implementation specialist. Given the strategy plan:\n"
|
||||
"1. Identify required resources (human, financial, technical)\n"
|
||||
"2. Define key milestones and checkpoints\n"
|
||||
"3. Develop risk mitigation strategies\n"
|
||||
"4. Provide final recommendations with confidence level\n\n"
|
||||
"Create a practical implementation roadmap."
|
||||
)
|
||||
)
|
||||
|
||||
# --- Sequential Agent (Pure Sequential Pattern) ---
|
||||
business_intelligence_team = SequentialAgent(
|
||||
name="business_intelligence_team",
|
||||
description="Sequentially processes business intelligence through research, analysis, strategy, and planning",
|
||||
sub_agents=[
|
||||
market_researcher, # Step 1: Market research (with search capabilities)
|
||||
swot_analyzer, # Step 2: SWOT analysis
|
||||
strategy_formulator, # Step 3: Strategy development
|
||||
implementation_planner # Step 4: Implementation planning
|
||||
]
|
||||
)
|
||||
|
||||
# --- Runner Setup for Execution ---
|
||||
session_service = InMemorySessionService()
|
||||
runner = Runner(
|
||||
agent=business_intelligence_team,
|
||||
app_name="business_intelligence",
|
||||
session_service=session_service
|
||||
)
|
||||
|
||||
# --- Simple Execution Function ---
|
||||
async def analyze_business_intelligence(user_id: str, business_topic: str) -> str:
|
||||
"""Process business intelligence through the sequential pipeline"""
|
||||
session_id = f"bi_session_{user_id}"
|
||||
|
||||
# Create or get session
|
||||
session = await session_service.get_session(
|
||||
app_name="business_intelligence",
|
||||
user_id=user_id,
|
||||
session_id=session_id
|
||||
)
|
||||
if not session:
|
||||
session = await session_service.create_session(
|
||||
app_name="business_intelligence",
|
||||
user_id=user_id,
|
||||
session_id=session_id,
|
||||
state={"business_topic": business_topic, "conversation_history": []}
|
||||
)
|
||||
|
||||
# Create user content
|
||||
user_content = types.Content(
|
||||
role='user',
|
||||
parts=[types.Part(text=f"Please analyze this business topic: {business_topic}")]
|
||||
)
|
||||
|
||||
# Run the sequential pipeline
|
||||
response_text = ""
|
||||
async for event in runner.run_async(
|
||||
user_id=user_id,
|
||||
session_id=session_id,
|
||||
new_message=user_content
|
||||
):
|
||||
if event.is_final_response():
|
||||
if event.content and event.content.parts:
|
||||
response_text = event.content.parts[0].text
|
||||
|
||||
return response_text
|
||||
|
|
@ -0,0 +1,112 @@
|
|||
import streamlit as st
|
||||
import asyncio
|
||||
from agent import business_intelligence_team, analyze_business_intelligence
|
||||
|
||||
# Page configuration
|
||||
st.set_page_config(
|
||||
page_title="Sequential Agent Demo",
|
||||
page_icon=":arrow_right:",
|
||||
layout="wide"
|
||||
)
|
||||
|
||||
# Title and description
|
||||
st.title("🚀 Business Implementation Plan Generator Agent")
|
||||
st.markdown("""
|
||||
This **Business Implementation Plan Generator Agent** analyzes business opportunities through a comprehensive 4-step process:
|
||||
|
||||
1. **🔍 Market Analysis** - Researches market, competitors, and trends using web search
|
||||
2. **📊 SWOT Analysis** - Identifies strengths, weaknesses, opportunities, and threats
|
||||
3. **🎯 Strategy Development** - Creates strategic objectives and action plans
|
||||
4. **📋 Implementation Planning** - Generates detailed business implementation roadmap
|
||||
|
||||
**Result**: A complete business implementation plan ready for execution.
|
||||
""")
|
||||
|
||||
# This is a placeholder user_id for demo purposes.
|
||||
# In a real app, you might use authentication or session state to set this.
|
||||
user_id = "demo_user"
|
||||
|
||||
# Sample business topics
|
||||
sample_topics = [
|
||||
"Electric vehicle charging stations in urban areas",
|
||||
"AI-powered healthcare diagnostics",
|
||||
"Sustainable food delivery services",
|
||||
"Remote work collaboration tools",
|
||||
"Renewable energy storage solutions"
|
||||
]
|
||||
|
||||
# Main content
|
||||
st.header("Generate Your Business Implementation Plan")
|
||||
|
||||
# Topic input
|
||||
business_topic = st.text_area(
|
||||
"Enter a business opportunity to analyze:",
|
||||
value=sample_topics[0],
|
||||
height=100,
|
||||
placeholder="Describe a business opportunity, industry, or market you'd like to analyze for implementation planning..."
|
||||
)
|
||||
|
||||
# Sample topics
|
||||
st.subheader("Or choose from sample business opportunities:")
|
||||
cols = st.columns(len(sample_topics))
|
||||
for i, topic in enumerate(sample_topics):
|
||||
if cols[i].button(topic, key=f"topic_{i}"):
|
||||
business_topic = topic
|
||||
st.rerun()
|
||||
|
||||
# Analysis button
|
||||
if st.button("🚀 Generate Business Implementation Plan", type="primary"):
|
||||
if business_topic.strip():
|
||||
st.info("🚀 Starting business analysis... This will research the market, perform SWOT analysis, develop strategy, and create an implementation plan.")
|
||||
|
||||
# Display the workflow
|
||||
st.subheader("Business Analysis Workflow")
|
||||
col1, col2, col3, col4 = st.columns(4)
|
||||
|
||||
with col1:
|
||||
st.markdown("**1. Market Analysis**")
|
||||
st.markdown("🔍 Web search + competitive research")
|
||||
|
||||
with col2:
|
||||
st.markdown("**2. SWOT Analysis**")
|
||||
st.markdown("📊 Strengths, Weaknesses, Opportunities, Threats")
|
||||
|
||||
with col3:
|
||||
st.markdown("**3. Strategy Development**")
|
||||
st.markdown("🎯 Strategic objectives and action plans")
|
||||
|
||||
with col4:
|
||||
st.markdown("**4. Implementation Planning**")
|
||||
st.markdown("📋 Detailed roadmap and execution plan")
|
||||
|
||||
# Run the actual analysis
|
||||
with st.spinner("Generating comprehensive business implementation plan..."):
|
||||
try:
|
||||
result = asyncio.run(analyze_business_intelligence(user_id, business_topic))
|
||||
|
||||
st.success("✅ Business Implementation Plan Generated!")
|
||||
st.subheader("Your Business Implementation Plan")
|
||||
st.markdown(result)
|
||||
|
||||
except Exception as e:
|
||||
st.error(f"❌ Error during analysis: {str(e)}")
|
||||
st.info("Make sure you have set up your GOOGLE_API_KEY in the .env file")
|
||||
|
||||
else:
|
||||
st.error("Please enter a business opportunity to analyze.")
|
||||
|
||||
# How it works (in sidebar)
|
||||
with st.sidebar:
|
||||
st.header("How It Works")
|
||||
st.markdown("""
|
||||
The **Business Implementation Plan Generator Agent** uses a sophisticated sequential workflow to create comprehensive business plans:
|
||||
|
||||
1. **🔍 Market Analysis Agent**: Uses web search to research current market conditions, competitors, and trends
|
||||
2. **📊 SWOT Analysis Agent**: Analyzes the market research to identify strategic insights
|
||||
3. **🎯 Strategy Development Agent**: Creates strategic objectives and action plans based on SWOT analysis
|
||||
4. **📋 Implementation Planning Agent**: Develops detailed execution roadmaps and resource requirements
|
||||
|
||||
**Key Innovation**: The Market Analysis Agent has access to a specialized Search Agent (wrapped as AgentTool) that can perform real-time web searches for current market intelligence.
|
||||
|
||||
Each agent builds upon the previous agent's output, creating a comprehensive business implementation plan ready for execution.
|
||||
""")
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
google-adk>=1.9.0
|
||||
streamlit>=1.28.0
|
||||
python-dotenv>=1.1.1
|
||||
pydantic>=2.0.0
|
||||
|
|
@ -54,7 +54,14 @@ This crash course covers the essential concepts of Google ADK through hands-on t
|
|||
- Error handling and logging
|
||||
- Usage analytics and monitoring
|
||||
|
||||
8. **More tutorials coming soon!**
|
||||
8. **[8_simple_multi_agent](./8_simple_multi_agent/README.md)** - Multi-agent orchestration
|
||||
- **[8.1 Multi-Agent Researcher](./8_simple_multi_agent/multi_agent_researcher/README.md)** - Research pipeline with specialized agents
|
||||
- Coordinator agent with sub-agents
|
||||
- Sequential workflow: Research → Summarize → Critique
|
||||
- Web search integration and comprehensive analysis
|
||||
|
||||
9. **[9_multi_agent_patterns](./9_multi_agent_patterns/README.md)** - Multi-Agent Patterns
|
||||
- **[9.1 Sequential Agent](./9_multi_agent_patterns/9_1_sequential_agent/README.md)** — Deterministic pipeline of sub-agents (e.g., Draft → Critique → Improve)
|
||||
|
||||
## 🛠️ Prerequisites
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue