This tutorial will discover highly effective multi-agent programs constructed round peer patterns: planning, execution, specific and evaluate. Run all the workflow with Google Colab/Pocket book, combine skilled roles with brokers, and leverage Google’s Gemini 1.5 Flash mannequin by way of a free API key. As we stroll via the system, we observe how every agent works collectively to sort out complicated duties throughout totally different domains, akin to finance, know-how, and artistic methods. This hands-on tutorial offers you an understanding of the structure, workflow, and iterative enhancements that underpin high-quality AI output.
!pip set up agentUniverse google-generativeai python-dotenv pydantic
import os
import asyncio
from typing import Dict, Checklist, 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)
First, arrange a multi-agent system by putting in the required libraries, together with Agentuniverse and Google-Generativeai. After importing the required modules, configure the Gemini API utilizing the free API key to allow AI-powered content material era. Please verify Full code is here.
class AgentRole(Enum):
PLANNER = "planner"
EXECUTOR = "executor"
EXPRESSER = "expresser"
REVIEWER = "reviewer"
@dataclass
class Process:
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, function: AgentRole, system_prompt: str):
self.identify = identify
self.function = function
self.system_prompt = system_prompt
self.reminiscence: Checklist[Dict] = []
async def course of(self, job: Process) -> str:
immediate = f"{self.system_prompt}nnTask: {job.description}nContext: {json.dumps(job.context)}"
outcome = await self._simulate_llm_call(immediate, job)
self.reminiscence.append({
"task_id": job.id,
"enter": job.description,
"output": outcome,
"timestamp": time.time()
})
return outcome
async def _simulate_llm_call(self, immediate: str, job: Process) -> str:
"""Name Google Gemini API for actual LLM processing"""
attempt:
mannequin = genai.GenerativeModel('gemini-1.5-flash')
enhanced_prompt = self._create_role_prompt(immediate, job)
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.function.worth}: {str(e)}")
return self._get_fallback_response(job)
def _create_role_prompt(self, base_prompt: str, job: Process) -> 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 completely and supply detailed implementation insights. Concentrate on 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(job.context, indent=2)}" if job.context else "No earlier context"
return f"""
{role_instructions[self.role]}
{base_prompt}
{context_info}
Process to course of: {job.description}
Present a complete, skilled response applicable on your function as {self.function.worth}.
"""
def _get_fallback_response(self, job: Process) -> str:
"""Fallback responses if Gemini API is unavailable"""
fallbacks = {
AgentRole.PLANNER: f"STRATEGIC PLAN for '{job.description}': 1) Requirement evaluation 2) Useful resource evaluation 3) Implementation roadmap 4) Danger mitigation 5) Success metrics",
AgentRole.EXECUTOR: f"EXECUTION ANALYSIS for '{job.description}': Complete evaluation accomplished. Key findings recognized, sensible options developed, implementation issues famous.",
AgentRole.EXPRESSER: f"PROFESSIONAL SUMMARY for '{job.description}': ## Evaluation Completenn**Key Insights:** Detailed evaluation performedn**Suggestions:** Strategic actions identifiedn**Subsequent Steps:** Implementation prepared",
AgentRole.REVIEWER: f"QUALITY REVIEW for '{job.description}': **Evaluation:** Prime quality output achieved. **Strengths:** Complete evaluation, clear construction. **Strategies:** Take into account further quantitative metrics."
}
return fallbacks[self.role]
Use enumerations to signify particular options to outline 4 totally different agent roles: planner, executor, explorer, and reviewer. Subsequent, create a job Dataclass to handle job metadata, together with standing, outcomes, and suggestions. The Baseagent class acts as a core blueprint for all brokers, processes duties, calls the Gemini API at role-specific prompts, and gracefully returns to the response outlined within the occasion that the API fails. Please verify Full code is 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("Process Executor", AgentRole.EXECUTOR,
"You might be an execution agent. Full duties effectively utilizing obtainable instruments and data.")
self.expresser = BaseAgent("Outcome 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, job: Process) -> Dict[str, Any]:
"""Execute PEER collaboration sample"""
outcomes = {"iterations": [], "final_result": None}
whereas self.iteration_count < self.max_iterations:
iteration_result = {}
print(f"🎯 Planning Part (Iteration {self.iteration_count + 1})")
plan = await self.planner.course of(job)
iteration_result["plan"] = plan
job.context["current_plan"] = plan
print(f"⚡ Execution Part")
execution = await self.executor.course of(job)
iteration_result["execution"] = execution
job.context["execution_result"] = execution
print(f"📝 Expression Part")
expression = await self.expresser.course of(job)
iteration_result["expression"] = expression
job.outcome = expression
print(f"🔍 Overview Part")
evaluate = await self.reviewer.course of(job)
iteration_result["review"] = evaluate
job.suggestions = evaluate
outcomes["iterations"].append(iteration_result)
if "excessive" in evaluate.decrease() and self.iteration_count >= 1:
outcomes["final_result"] = expression
break
self.iteration_count += 1
job.context["previous_feedback"] = evaluate
return outcomes
Coordinate 4 skilled brokers to coordinate collaborative job soaving via Peera Sample, Planning, Execution, Categorical, Overview and Peeragent lessons. Every iteration runs all 4 phases and refines the duty output based mostly on structured plans, executions, skilled representations, and high quality critiques. If the evaluate signifies top quality completion, you’ll be able to permit as much as three iterations to make the workflow adaptive and environment friendly. Please verify Full code is 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 = "common") -> Dict[str, Any]:
"""Course of complicated job utilizing PEER sample and area brokers"""
job = Process(
id=f"task_{int(time.time())}",
description=description,
context={"area": area, "complexity": "excessive"}
)
print(f"🚀 Beginning Complicated Process Processing: {description}")
print("=" * 60)
peer_results = await self.peer_system.collaborate(job)
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(job)
peer_results["domain_enhancement"] = domain_result
return {
"task_id": job.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, danger 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 issues."),
"artistic": BaseAgent("Artistic Director", AgentRole.EXPRESSER,
"You might be an award-winning artistic director with experience in model technique, content material creation, and progressive campaigns. Generate compelling and strategic artistic 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) -> Checklist[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✅ Process Accomplished: {result1['processing_time']}")
print(f"Closing Outcome: {result1['peer_results']['final_result']}")
print("n💻 DEMO 2: Technical Drawback Fixing")
print("-" * 40)
technical_task = "Design a scalable microservices structure for a high traffic e-commerce platform"
result2 = await orchestrator.process_complex_task(technical_task, "technical")
print(f"n✅ Process Accomplished: {result2['processing_time']}")
print(f"Closing Outcome: {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, "artistic")
print(f"n✅ Process Accomplished: {result3['processing_time']}")
print(f"Closing Outcome: {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"""
clarification = """
🔍 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 permits:
✅ Higher job decomposition
✅ Systematic execution
✅ Skilled output formatting
✅ Steady high quality enchancment
"""
print(clarification)
def show_architecture():
"""Show the multi-agent structure"""
structure = """
🏗️ agentUniverse Structure:
📋 Process 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 convey all of it collectively via a multigen trichestrator who coordinates the peer system and invokes domain-specific brokers akin to monetary analysts and technical consultants when crucial. This orchestrator handles every complicated job by first leveraging peer patterns and enhancing the outcomes with particular data. It additionally defines a easy data base to help domain-aware inference. The run_advanced_demo() perform exams an entire pipeline with three duties, finance, technical and artistic, and captures agent efficiency and iterative metrics to showcase the ability and flexibility of a multi-agent setup. Please verify Full code is here.
if __name__ == "__main__":
print("💡 Get your FREE API key at: https://makersuite.google.com/app/apikey")
print("🔑 Be sure that to switch '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. Exchange '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⏳ Operating Superior Demo with Gemini AI (This may occasionally take a second)...")
attempt:
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 Charge: {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 permits 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 supplies highly effective, free AI capabilities")
besides ImportError:
print("📝 Be aware: Set up nest_asyncio for full async help in Colab")
print("Run: !pip set up nest_asyncio")
besides Exception as e:
print(f"⚠️ Error working demo: {str(e)}")
print("This is likely to be as a result of API key configuration or community points.")
print("n🔗 Subsequent Steps:")
print(" • Customise brokers on your particular area")
print(" • Experiment with totally different Gemini fashions (gemini-pro, gemini-1.5-flash)")
print(" • Construct production-ready multi-agent functions")
End the tutorial by initializing the system, verifying the Gemini API key, and working a peer-based multi-agent workflow. Describe the structure and patterns earlier than working the demo, and when accomplished efficiently, it supplies a efficiency overview and necessary factors.
In conclusion, we efficiently reveal how multi-agent programs can systematically resolve complicated issues with the assistance of domain-specific inference, structured communication, and iterative high quality checks. Achieve perception into the collaborative energy of the peer framework and witness how Gemini can improve the output of every agent. By way of this expertise, we acknowledge the potential of modular AI programs to create scalable, dependable, clever functions that may accommodate real-world deployments.
Please verify Full code is here. Please be at liberty to verify GitHub pages for tutorials, code and notebooks. Additionally, please be at liberty to comply with us Twitter And do not forget to affix us 100k+ ml subreddit And subscribe Our Newsletter.
Asif Razzaq is CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, ASIF is dedicated to leveraging the probabilities of synthetic intelligence for social advantages. His newest efforts are the launch of MarkTechPost, a man-made intelligence media platform. That is distinguished by its detailed protection of machine studying and deep studying information, and is simple to grasp by a technically sound and extensive viewers. The platform has over 2 million views every month, indicating its reputation amongst viewers.


