On this tutorial, we discover a strong multi-agent system constructed across the PEER sample: Plan, Execute, Categorical, and Overview. We run the complete workflow in Google Colab/Pocket book, integrating brokers with specialised roles and leveraging Google’s Gemini 1.5 Flash mannequin by way of a free API key. As we stroll by way of the system, we observe how every agent collaborates to deal with complicated duties throughout totally different domains resembling finance, expertise, and artistic technique. This hands-on tutorial permits us to grasp the structure, workflow, and iterative refinement that underpin high-quality AI outputs.
!pip set up agentUniverse google-generativeai python-dotenv pydantic
import os
import asyncio
from typing import Dict, Listing, Any, Elective
from dataclasses import dataclass
from enum import Enum
import json
import time
import google.generativeai as genai
GEMINI_API_KEY = 'Use Your API Key Right here'
genai.configure(api_key=GEMINI_API_KEY)
We start by putting in the required libraries, together with agentUniverse and google-generativeai, to arrange our multi-agent system. After importing the mandatory modules, we configure the Gemini API utilizing our free API key to allow AI-powered content material era. Take a look at the Full Codes right here.
class AgentRole(Enum):
PLANNER = "planner"
EXECUTOR = "executor"
EXPRESSER = "expresser"
REVIEWER = "reviewer"
@dataclass
class Activity:
id: str
description: str
context: Dict[str, Any]
standing: str = "pending"
outcome: Elective[str] = None
suggestions: Elective[str] = None
class BaseAgent:
"""Base agent class with core performance"""
def __init__(self, identify: str, position: AgentRole, system_prompt: str):
self.identify = identify
self.position = position
self.system_prompt = system_prompt
self.reminiscence: Listing[Dict] = []
async def course of(self, activity: Activity) -> str:
immediate = f"{self.system_prompt}nnTask: {activity.description}nContext: {json.dumps(activity.context)}"
outcome = await self._simulate_llm_call(immediate, activity)
self.reminiscence.append({
"task_id": activity.id,
"enter": activity.description,
"output": outcome,
"timestamp": time.time()
})
return outcome
async def _simulate_llm_call(self, immediate: str, activity: Activity) -> str:
"""Name Google Gemini API for actual LLM processing"""
strive:
mannequin = genai.GenerativeModel('gemini-1.5-flash')
enhanced_prompt = self._create_role_prompt(immediate, activity)
response = await asyncio.to_thread(
lambda: mannequin.generate_content(enhanced_prompt)
)
return response.textual content.strip()
besides Exception as e:
print(f"⚠️ Gemini API error for {self.position.worth}: {str(e)}")
return self._get_fallback_response(activity)
def _create_role_prompt(self, base_prompt: str, activity: Activity) -> str:
"""Create enhanced role-specific prompts for Gemini"""
role_instructions = {
AgentRole.PLANNER: "You're a strategic planning knowledgeable. Create detailed, actionable plans. Break down complicated duties into clear steps with priorities and dependencies.",
AgentRole.EXECUTOR: "You're a expert executor. Analyze the duty totally and supply detailed implementation insights. Give attention to sensible options and potential challenges.",
AgentRole.EXPRESSER: "You're a skilled communicator. Current info clearly, professionally, and engagingly. Construction your response with headers, bullet factors, and clear conclusions.",
AgentRole.REVIEWER: "You're a high quality assurance knowledgeable. Consider completeness, accuracy, and readability. Present particular, actionable enchancment ideas."
}
context_info = f"Earlier context: {json.dumps(activity.context, indent=2)}" if activity.context else "No earlier context"
return f"""
{role_instructions[self.role]}
{base_prompt}
{context_info}
Activity to course of: {activity.description}
Present a complete, skilled response applicable to your position as {self.position.worth}.
"""
def _get_fallback_response(self, activity: Activity) -> str:
"""Fallback responses if Gemini API is unavailable"""
fallbacks = {
AgentRole.PLANNER: f"STRATEGIC PLAN for '{activity.description}': 1) Requirement evaluation 2) Useful resource evaluation 3) Implementation roadmap 4) Danger mitigation 5) Success metrics",
AgentRole.EXECUTOR: f"EXECUTION ANALYSIS for '{activity.description}': Complete evaluation accomplished. Key findings recognized, sensible options developed, implementation concerns famous.",
AgentRole.EXPRESSER: f"PROFESSIONAL SUMMARY for '{activity.description}': ## Evaluation Completenn**Key Insights:** Detailed evaluation performedn**Suggestions:** Strategic actions identifiedn**Subsequent Steps:** Implementation prepared",
AgentRole.REVIEWER: f"QUALITY REVIEW for '{activity.description}': **Evaluation:** Prime quality output achieved. **Strengths:** Complete evaluation, clear construction. **Solutions:** Contemplate extra quantitative metrics."
}
return fallbacks[self.role]
We outline 4 distinct agent roles, Planner, Executor, Expresser, and Reviewer, utilizing an Enum to signify their specialised features. Then, we create a Activity dataclass to handle activity metadata, together with standing, outcome, and suggestions. The BaseAgent class serves because the core blueprint for all brokers, enabling them to course of duties, name the Gemini API with role-specific prompts, retailer ends in reminiscence, and gracefully fall again to predefined responses if the API fails. Take a look at the Full Codes right here.
class PEERAgent:
"""PEER Sample Implementation - Plan, Execute, Categorical, Overview"""
def __init__(self):
self.planner = BaseAgent("Strategic Planner", AgentRole.PLANNER,
"You're a strategic planning agent. Break down complicated duties into actionable steps.")
self.executor = BaseAgent("Activity Executor", AgentRole.EXECUTOR,
"You might be an execution agent. Full duties effectively utilizing accessible instruments and data.")
self.expresser = BaseAgent("End result Expresser", AgentRole.EXPRESSER,
"You're a communication agent. Current outcomes clearly and professionally.")
self.reviewer = BaseAgent("High quality Reviewer", AgentRole.REVIEWER,
"You're a high quality assurance agent. Overview outputs and supply enchancment suggestions.")
self.iteration_count = 0
self.max_iterations = 3
async def collaborate(self, activity: Activity) -> Dict[str, Any]:
"""Execute PEER collaboration sample"""
outcomes = {"iterations": [], "final_result": None}
whereas self.iteration_count = 1:
outcomes["final_result"] = expression
break
self.iteration_count += 1
activity.context["previous_feedback"] = overview
return outcomes
We implement the PEER sample, Plan, Execute, Categorical, Overview, by way of the PEERAgent class, which coordinates 4 specialised brokers for collaborative task-solving. Every iteration runs by way of all 4 phases, refining the duty output based mostly on structured planning, execution, skilled expression, and high quality overview. We enable as much as three iterations, concluding early if the overview signifies high-quality completion, making the workflow each adaptive and environment friendly. Take a look at the Full Codes right here.
class MultiAgentOrchestrator:
"""Orchestrates a number of specialised brokers"""
def __init__(self):
self.brokers = {}
self.peer_system = PEERAgent()
self.task_queue = []
def register_agent(self, agent: BaseAgent):
"""Register a specialised agent"""
self.brokers[agent.name] = agent
async def process_complex_task(self, description: str, area: str = "normal") -> Dict[str, Any]:
"""Course of complicated activity utilizing PEER sample and area brokers"""
activity = Activity(
id=f"task_{int(time.time())}",
description=description,
context={"area": area, "complexity": "excessive"}
)
print(f"🚀 Beginning Advanced Activity Processing: {description}")
print("=" * 60)
peer_results = await self.peer_system.collaborate(activity)
if area in ["financial", "technical", "creative"]:
domain_agent = self._get_domain_agent(area)
if domain_agent:
print(f"🔧 Area-Particular Processing ({area})")
domain_result = await domain_agent.course of(activity)
peer_results["domain_enhancement"] = domain_result
return {
"task_id": activity.id,
"original_request": description,
"peer_results": peer_results,
"standing": "accomplished",
"processing_time": f"{len(peer_results['iterations'])} iterations"
}
def _get_domain_agent(self, area: str) -> Elective[BaseAgent]:
"""Get domain-specific agent with enhanced Gemini prompts"""
domain_agents = {
"monetary": BaseAgent("Monetary Analyst", AgentRole.EXECUTOR,
"You're a senior monetary analyst with experience in market evaluation, threat evaluation, and funding methods. Present detailed monetary insights with quantitative evaluation."),
"technical": BaseAgent("Technical Professional", AgentRole.EXECUTOR,
"You're a lead software program architect with experience in system design, scalability, and finest practices. Present detailed technical options with implementation concerns."),
"inventive": BaseAgent("Artistic Director", AgentRole.EXPRESSER,
"You might be an award-winning inventive director with experience in model technique, content material creation, and revolutionary campaigns. Generate compelling and strategic inventive options.")
}
return domain_agents.get(area)
class KnowledgeBase:
"""Easy data administration system"""
def __init__(self):
self.data = {
"financial_analysis": ["Risk assessment", "Portfolio optimization", "Market analysis"],
"technical_development": ["System architecture", "Code optimization", "Security protocols"],
"creative_content": ["Brand storytelling", "Visual design", "Content strategy"]
}
def get_domain_knowledge(self, area: str) -> Listing[str]:
return self.data.get(area, ["General knowledge"])
async def run_advanced_demo():
orchestrator = MultiAgentOrchestrator()
knowledge_base = KnowledgeBase()
print("n📊 DEMO 1: Monetary Evaluation with PEER Sample")
print("-" * 40)
financial_task = "Analyze the potential impression of rising rates of interest on tech shares portfolio"
result1 = await orchestrator.process_complex_task(financial_task, "monetary")
print(f"n✅ Activity Accomplished: {result1['processing_time']}")
print(f"Remaining End result: {result1['peer_results']['final_result']}")
print("n💻 DEMO 2: Technical Downside Fixing")
print("-" * 40)
technical_task = "Design a scalable microservices structure for a heavy-traffic e-commerce platform"
result2 = await orchestrator.process_complex_task(technical_task, "technical")
print(f"n✅ Activity Accomplished: {result2['processing_time']}")
print(f"Remaining End result: {result2['peer_results']['final_result']}")
print("n🎨 DEMO 3: Artistic Content material with Multi-Agent Collaboration")
print("-" * 40)
creative_task = "Create a complete model technique for a sustainable trend startup"
result3 = await orchestrator.process_complex_task(creative_task, "inventive")
print(f"n✅ Activity Accomplished: {result3['processing_time']}")
print(f"Remaining End result: {result3['peer_results']['final_result']}")
print("n🧠 AGENT MEMORY & LEARNING")
print("-" * 40)
print(f"Planner processed {len(orchestrator.peer_system.planner.reminiscence)} duties")
print(f"Executor processed {len(orchestrator.peer_system.executor.reminiscence)} duties")
print(f"Expresser processed {len(orchestrator.peer_system.expresser.reminiscence)} duties")
print(f"Reviewer processed {len(orchestrator.peer_system.reviewer.reminiscence)} duties")
return {
"demo_results": [result1, result2, result3],
"agent_stats": {
"total_tasks": 3,
"success_rate": "100%",
"avg_iterations": sum(len(r['peer_results']['iterations']) for r in [result1, result2, result3]) / 3
}
}
def explain_peer_pattern():
"""Clarify the PEER sample intimately"""
rationalization = """
🔍 PEER Sample Defined:
P - PLAN: Strategic decomposition of complicated duties
E - EXECUTE: Systematic implementation utilizing instruments and data
E - EXPRESS: Clear, structured communication of outcomes
R - REVIEW: High quality assurance and iterative enchancment
This sample allows:
✅ Higher activity decomposition
✅ Systematic execution
✅ Skilled output formatting
✅ Steady high quality enchancment
"""
print(rationalization)
def show_architecture():
"""Show the multi-agent structure"""
structure = """
🏗️ agentUniverse Structure:
📋 Activity Enter
↓
🎯 PEER System
├── Planner Agent
├── Executor Agent
├── Expresser Agent
└── Reviewer Agent
↓
🔧 Area Specialists
├── Monetary Analyst
├── Technical Professional
└── Artistic Director
↓
📚 Data Base
↓
📊 Outcomes & Analytics
"""
print(structure)
We carry every little thing collectively by way of the MultiAgentOrchestrator, which coordinates the PEER system and, when wanted, invokes domain-specific brokers just like the Monetary Analyst or Technical Professional. This orchestrator handles every complicated activity by first leveraging the PEER sample after which enhancing outcomes with specialised data. We additionally outline a easy KnowledgeBase to assist domain-aware reasoning. Within the run_advanced_demo() operate, we take a look at the complete pipeline with three duties, monetary, technical, and artistic, whereas capturing agent efficiency and iteration metrics to showcase the facility and flexibility of our multi-agent setup. Take a look at the Full Codes right here.
if __name__ == "__main__":
print("💡 Get your FREE API key at: https://makersuite.google.com/app/apikey")
print("🔑 Ensure to interchange 'your-gemini-api-key-here' together with your precise key!")
if GEMINI_API_KEY == 'your-gemini-api-key-here':
print("⚠️ WARNING: Please set your Gemini API key first!")
print(" 1. Go to https://makersuite.google.com/app/apikey")
print(" 2. Create a free API key")
print(" 3. Change 'your-gemini-api-key-here' together with your key")
print(" 4. Re-run the tutorial")
else:
print("✅ API key configured! Beginning tutorial...")
explain_peer_pattern()
show_architecture()
print("n⏳ Working Superior Demo with Gemini AI (This will likely take a second)...")
strive:
import nest_asyncio
nest_asyncio.apply()
demo_results = asyncio.run(run_advanced_demo())
print("n🎉 TUTORIAL COMPLETED SUCCESSFULLY!")
print("=" * 50)
print(f"📈 Efficiency Abstract:")
print(f" • Duties Processed: {demo_results['agent_stats']['total_tasks']}")
print(f" • Success Price: {demo_results['agent_stats']['success_rate']}")
print(f" • Avg Iterations: {demo_results['agent_stats']['avg_iterations']:.1f}")
print(f" • Powered by: Google Gemini (FREE)")
print("n💡 Key Takeaways:")
print(" • PEER sample allows systematic problem-solving")
print(" • Multi-agent collaboration improves output high quality")
print(" • Area experience integration enhances specialization")
print(" • Iterative refinement ensures high-quality outcomes")
print(" • Gemini offers highly effective, free AI capabilities")
besides ImportError:
print("📝 Observe: Set up nest_asyncio for full async assist in Colab")
print("Run: !pip set up nest_asyncio")
besides Exception as e:
print(f"⚠️ Error operating demo: {str(e)}")
print("This could be resulting from API key configuration or community points.")
print("n🔗 Subsequent Steps:")
print(" • Customise brokers to your particular area")
print(" • Experiment with totally different Gemini fashions (gemini-pro, gemini-1.5-flash)")
print(" • Construct production-ready multi-agent functions")
We conclude the tutorial by initializing the system, verifying the Gemini API key, and executing the complete PEER-based multi-agent workflow. We clarify the structure and sample earlier than operating the demo, and upon profitable completion, we show a efficiency abstract and key takeaways.
In conclusion, we efficiently display how a multi-agent system can systematically resolve complicated issues with the assistance of domain-specific reasoning, structured communication, and iterative high quality checks. We acquire insights into the collaborative energy of the PEER framework and witness how Gemini enhances every agent’s output. By way of this expertise, we understand the potential of modular AI methods in creating scalable, dependable, and clever functions prepared for real-world deployment.
Take a look at the Full Codes right here. Be happy to take a look at our GitHub Web page for Tutorials, Codes and Notebooks. Additionally, be happy to observe us on Twitter and don’t neglect to hitch our 100k+ ML SubReddit and Subscribe to our E-newsletter.
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.