Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      The Value-Driven AI Roadmap

      September 9, 2025

      This week in AI updates: Mistral’s new Le Chat features, ChatGPT updates, and more (September 5, 2025)

      September 6, 2025

      Designing For TV: Principles, Patterns And Practical Guidance (Part 2)

      September 5, 2025

      Neo4j introduces new graph architecture that allows operational and analytics workloads to be run together

      September 5, 2025

      ‘Job Hugging’ Trend Emerges as Workers Confront AI Uncertainty

      September 8, 2025

      Distribution Release: MocaccinoOS 25.09

      September 8, 2025

      Composition in CSS

      September 8, 2025

      DataCrunch raises €55M to boost EU AI sovereignty with green cloud infrastructure

      September 8, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Finally, safe array methods in JavaScript

      September 9, 2025
      Recent

      Finally, safe array methods in JavaScript

      September 9, 2025

      Perficient Interviewed for Forrester Report on AI’s Transformative Role in DXPs

      September 9, 2025

      Perficient’s “What If? So What?” Podcast Wins Gold Stevie® Award for Technology Podcast

      September 9, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Distribution Release: MocaccinoOS 25.09

      September 8, 2025
      Recent

      Distribution Release: MocaccinoOS 25.09

      September 8, 2025

      Speed Isn’t Everything When Buying SSDs – Here’s What Really Matters!

      September 8, 2025

      14 Themes for Beautifying Your Ghostty Terminal

      September 8, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Machine Learning»How to Build an Asynchronous AI Agent Network Using Gemini for Research, Analysis, and Validation Tasks

    How to Build an Asynchronous AI Agent Network Using Gemini for Research, Analysis, and Validation Tasks

    June 8, 2025

    In this tutorial, we introduce the Gemini Agent Network Protocol, a powerful and flexible framework designed to enable intelligent collaboration among specialized AI agents. Leveraging Google’s Gemini models, the protocol facilitates dynamic communication between agents, each equipped with distinct roles: Analyzer, Researcher, Synthesizer, and Validator. Users will learn to set up and configure an asynchronous agent network, enabling automated task distribution, collaborative problem-solving, and enriched dialogue management. Ideal for scenarios such as in-depth research, complex data analysis, and information validation, this framework empowers users to harness collective AI intelligence efficiently.

    Copy CodeCopiedUse a different Browser
    import asyncio
    import json
    import random
    from dataclasses import dataclass, asdict
    from typing import Dict, List, Optional, Any
    from enum import Enum
    import google.generativeai as genai

    We leverage asyncio for concurrent execution, dataclasses for structured message management, and Google’s Generative AI (google.generativeai) to facilitate interactions among multiple AI-driven agents. It includes utilities for dynamic message handling and structured agent roles, enhancing scalability and flexibility in collaborative AI tasks.

    Copy CodeCopiedUse a different Browser
    API_KEY = None
    
    
    try:
        import google.colab
        IN_COLAB = True
    except ImportError:
        IN_COLAB = False

    We initialize the API_KEY and detect whether the code is running in a Colab environment. If the google.colab module is successfully imported, the IN_COLAB flag is set to True; otherwise, it defaults to False, allowing the script to adjust behavior accordingly.

    Copy CodeCopiedUse a different Browser
    class AgentType(Enum):
        ANALYZER = "analyzer"
        RESEARCHER = "researcher"
        SYNTHESIZER = "synthesizer"
        VALIDATOR = "validator"
    
    
    @dataclass
    class Message:
        sender: str
        receiver: str
        content: str
        msg_type: str
        metadata: Dict = None

    Check out the Notebook

    We define the core structures for agent interaction. The AgentType enum categorizes agents into four distinct roles, Analyzer, Researcher, Synthesizer, and Validator, each with a specific function in the collaborative network. The Message dataclass represents the format for inter-agent communication, encapsulating sender and receiver IDs, message content, type, and optional metadata.

    Copy CodeCopiedUse a different Browser
    class GeminiAgent:
        def __init__(self, agent_id: str, agent_type: AgentType, network: 'AgentNetwork'):
            self.id = agent_id
            self.type = agent_type
            self.network = network
            self.model = genai.GenerativeModel('gemini-2.0-flash')
            self.inbox = asyncio.Queue()
            self.context_memory = []
           
            self.system_prompts = {
                AgentType.ANALYZER: "You are a data analyzer. Break down complex problems into components and identify key patterns.",
                AgentType.RESEARCHER: "You are a researcher. Gather information and provide detailed context on topics.",
                AgentType.SYNTHESIZER: "You are a synthesizer. Combine information from multiple sources into coherent insights.",
                AgentType.VALIDATOR: "You are a validator. Check accuracy and consistency of information and conclusions."
            }
       
        async def process_message(self, message: Message):
            """Process incoming message and generate response"""
            if not API_KEY:
                return "<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/274c.png" alt="❌" class="wp-smiley" /> API key not configured. Please set API_KEY variable."
               
            prompt = f"""
            {self.system_prompts[self.type]}
           
            Context from previous interactions: {json.dumps(self.context_memory[-3:], indent=2)}
           
            Message from {message.sender}: {message.content}
           
            Provide a focused response (max 100 words) that adds value to the network discussion.
            """
           
            try:
                response = await asyncio.to_thread(
                    self.model.generate_content, prompt
                )
                return response.text.strip()
            except Exception as e:
                return f"Error processing: {str(e)}"
       
        async def send_message(self, receiver_id: str, content: str, msg_type: str = "task"):
            """Send message to another agent"""
            message = Message(self.id, receiver_id, content, msg_type)
            await self.network.route_message(message)
       
        async def broadcast(self, content: str, exclude_self: bool = True):
            """Broadcast message to all agents in network"""
            for agent_id in self.network.agents:
                if exclude_self and agent_id == self.id:
                    continue
                await self.send_message(agent_id, content, "broadcast")
       
        async def run(self):
            """Main agent loop"""
            while True:
                try:
                    message = await asyncio.wait_for(self.inbox.get(), timeout=1.0)
                   
                    response = await self.process_message(message)
                   
                    self.context_memory.append({
                        "from": message.sender,
                        "content": message.content,
                        "my_response": response
                    })
                   
                    if len(self.context_memory) > 10:
                        self.context_memory = self.context_memory[-10:]
                   
                    print(f"<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/1f916.png" alt="🤖" class="wp-smiley" /> {self.id} ({self.type.value}): {response}")
                   
                    if random.random() < 0.3:  
                        other_agents = [aid for aid in self.network.agents.keys() if aid != self.id]
                        if other_agents:
                            target = random.choice(other_agents)
                            await self.send_message(target, f"Building on that: {response[:50]}...")
                   
                except asyncio.TimeoutError:
                    continue
                except Exception as e:
                    print(f"<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/274c.png" alt="❌" class="wp-smiley" /> Error in {self.id}: {e}")

    Check out the Notebook

    The GeminiAgent class defines the behavior and capabilities of each agent in the network. Upon initialization, it assigns a unique ID, role type, and a reference to the agent network and loads the Gemini 2.0 Flash model. It uses role-specific system prompts to generate intelligent responses based on incoming messages, which are processed asynchronously through a queue. Each agent maintains a context memory to retain recent interactions and can either respond directly, send targeted messages, or broadcast insights to others. The run() method continuously processes messages, promotes collaboration by occasionally initiating responses to other agents, and manages message handling in a non-blocking loop.

    Copy CodeCopiedUse a different Browser
    class AgentNetwork:
        def __init__(self):
            self.agents: Dict[str, GeminiAgent] = {}
            self.message_log = []
            self.running = False
       
        def add_agent(self, agent_type: AgentType, agent_id: Optional[str] = None):
            """Add new agent to network"""
            if not agent_id:
                agent_id = f"{agent_type.value}_{len(self.agents)+1}"
           
            agent = GeminiAgent(agent_id, agent_type, self)
            self.agents[agent_id] = agent
            print(f"<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/2705.png" alt="✅" class="wp-smiley" /> Added {agent_id} to network")
            return agent_id
       
        async def route_message(self, message: Message):
            """Route message to target agent"""
            self.message_log.append(asdict(message))
           
            if message.receiver in self.agents:
                await self.agents[message.receiver].inbox.put(message)
            else:
                print(f"<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/26a0.png" alt="⚠" class="wp-smiley" />  Agent {message.receiver} not found")
       
        async def initiate_task(self, task: str):
            """Start a collaborative task"""
            print(f"<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/1f680.png" alt="🚀" class="wp-smiley" /> Starting task: {task}")
           
            analyzer_agents = [aid for aid, agent in self.agents.items()
                              if agent.type == AgentType.ANALYZER]
           
            if analyzer_agents:
                initial_message = Message("system", analyzer_agents[0], task, "task")
                await self.route_message(initial_message)
       
        async def run_network(self, duration: int = 30):
            """Run the agent network for specified duration"""
            self.running = True
            print(f"<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/1f310.png" alt="🌐" class="wp-smiley" /> Starting agent network for {duration} seconds...")
           
            agent_tasks = [agent.run() for agent in self.agents.values()]
           
            try:
                await asyncio.wait_for(asyncio.gather(*agent_tasks), timeout=duration)
            except asyncio.TimeoutError:
                print("<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/23f0.png" alt="⏰" class="wp-smiley" /> Network session completed")
            finally:
                self.running = False

    Check out the Notebook

    The AgentNetwork class manages the coordination and communication between all agents in the system. It allows dynamic addition of agents with unique IDs and specified roles, maintains a log of all exchanged messages, and facilitates message routing to the correct recipient. The network can initiate a collaborative task by sending the starting message to an Analyzer agent, and runs the full asynchronous event loop for a specified duration, enabling agents to operate concurrently and interactively within a shared environment.

    Copy CodeCopiedUse a different Browser
    async def demo_agent_network():
        """Demonstrate the Gemini Agent Network Protocol"""
       
        network = AgentNetwork()
       
        network.add_agent(AgentType.ANALYZER, "deep_analyzer")
        network.add_agent(AgentType.RESEARCHER, "info_gatherer")
        network.add_agent(AgentType.SYNTHESIZER, "insight_maker")
        network.add_agent(AgentType.VALIDATOR, "fact_checker")
       
        task = "Analyze the potential impact of quantum computing on cybersecurity"
       
        network_task = asyncio.create_task(network.run_network(20))
        await asyncio.sleep(1)  
        await network.initiate_task(task)
        await network_task
       
        print(f"n<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/1f4ca.png" alt="📊" class="wp-smiley" /> Network completed with {len(network.message_log)} messages exchanged")
        agent_participation = {aid: sum(1 for msg in network.message_log if msg['sender'] == aid)
                              for aid in network.agents}
        print("Agent participation:", agent_participation)
    
    
    def setup_api_key():
        """Interactive API key setup"""
        global API_KEY
       
        if IN_COLAB:
            from google.colab import userdata
            try:
                API_KEY = userdata.get('GEMINI_API_KEY')
                genai.configure(api_key=API_KEY)
                print("<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/2705.png" alt="✅" class="wp-smiley" /> API key loaded from Colab secrets")
                return True
            except:
                print("<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/1f4a1.png" alt="💡" class="wp-smiley" /> To use Colab secrets: Add 'GEMINI_API_KEY' in the secrets panel")
       
        print("<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/1f511.png" alt="🔑" class="wp-smiley" /> Please enter your Gemini API key:")
        print("   Get it from: https://makersuite.google.com/app/apikey")
       
        try:
            if IN_COLAB:
                from google.colab import userdata
                API_KEY = input("Paste your API key here: ").strip()
            else:
                import getpass
                API_KEY = getpass.getpass("Paste your API key here: ").strip()
           
            if API_KEY and len(API_KEY) > 10:
                genai.configure(api_key=API_KEY)
                print("<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/2705.png" alt="✅" class="wp-smiley" /> API key configured successfully!")
                return True
            else:
                print("<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/274c.png" alt="❌" class="wp-smiley" /> Invalid API key")
                return False
        except KeyboardInterrupt:
            print("n<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/274c.png" alt="❌" class="wp-smiley" /> Setup cancelled")
            return False

    Check out the Notebook

    The demo_agent_network() function orchestrates the entire agent workflow: it initializes an agent network, adds four role-specific agents, launches a cybersecurity task, and runs the network asynchronously for a fixed duration while tracking message exchanges and agent participation. Meanwhile, setup_api_key() provides an interactive mechanism to securely configure the Gemini API key, with tailored logic for both Colab and non-Colab environments, ensuring the AI agents can communicate with the Gemini model backend before the demo begins.

    Copy CodeCopiedUse a different Browser
    if __name__ == "__main__":
        print("<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/1f9e0.png" alt="🧠" class="wp-smiley" /> Gemini Agent Network Protocol")
        print("=" * 40)
       
        if not setup_api_key():
            print("<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/274c.png" alt="❌" class="wp-smiley" /> Cannot run without valid API key")
            exit()
       
        print("n<img src="https://s.w.org/images/core/emoji/15.1.0/72x72/1f680.png" alt="🚀" class="wp-smiley" /> Starting demo...")
       
        if IN_COLAB:
            import nest_asyncio
            nest_asyncio.apply()
            loop = asyncio.get_event_loop()
            loop.run_until_complete(demo_agent_network())
        else:
            asyncio.run(demo_agent_network())
    

    Finally, the above code serves as the entry point for executing the Gemini Agent Network Protocol. It begins by prompting the user to set up the Gemini API key, exiting if not provided. Upon successful configuration, the demo is launched. If running in Google Colab, it applies nest_asyncio to handle Colab’s event loop restrictions; otherwise, it uses Python’s native asyncio.run() to execute the asynchronous demo of agent collaboration.

    In conclusion, by completing this tutorial, users gain practical knowledge of implementing an AI-powered collaborative network using Gemini agents. The hands-on experience provided here demonstrates how autonomous agents can effectively break down complex problems, collaboratively generate insights, and ensure the accuracy of information through validation.


    Check out the Notebook. All credit for this research goes to the researchers of this project. Also, feel free to follow us on Twitter and don’t forget to join our 99k+ ML SubReddit and Subscribe to our Newsletter.

    The post How to Build an Asynchronous AI Agent Network Using Gemini for Research, Analysis, and Validation Tasks appeared first on MarkTechPost.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleHigh-Entropy Token Selection in Reinforcement Learning with Verifiable Rewards (RLVR) Improves Accuracy and Reduces Training Cost for LLMs
    Next Article Google Introduces Open-Source Full-Stack AI Agent Stack Using Gemini 2.5 and LangGraph for Multi-Step Web Search, Reflection, and Synthesis

    Related Posts

    Machine Learning

    How to Evaluate Jailbreak Methods: A Case Study with the StrongREJECT Benchmark

    September 3, 2025
    Machine Learning

    Announcing the new cluster creation experience for Amazon SageMaker HyperPod

    September 3, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    Trump’s AI plan says a lot about open source – but here’s what it leaves out

    News & Updates

    Google’s AI Mode is getting more links for you not to click on

    News & Updates

    Stable Diffusion Online – Free AI Image Generation

    Web Development

    CVE-2025-40924 – Catalyst::Plugin::Session Insecure Session ID Generation

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    Periodic Table Tools: 5 Best Free and Open Source Linux Tools

    April 12, 2025

    The periodic table, also known as the periodic table of the elements, is a rows…

    With GTA 6, next-gen exclusives, and a console comeback on the horizon, Xbox risks sitting on the sidelines — here’s why

    August 18, 2025

    GCP Cloud Composer Bug Let Attackers Elevate Access via Malicious PyPI Packages

    April 22, 2025

    The Red Car Man

    August 11, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.