This tutorial introduces the Gemini Agent Network Protocol. It is a flexible and powerful framework that enables intelligent collaboration between specialized AI agents. The protocol uses Google Gemini models to facilitate dynamic communication among agents. Agents are equipped with different roles such as Analyzer, Reseacher, Synthesizer and Validator. Learn how to create and configure an agent network that enables automated task allocation, collaborative problem-solving and enhanced dialogue management. The framework allows users to leverage collective AI intelligence in scenarios like deep research, complex analysis of data, or information validation.
import asyncio
Import json
Import random
Import dataclasses from asdict
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. The toolkit includes dynamic message handling utilities and agent roles that enhance scalability.
API_KEY = none
try:
Google.colab
IN_COLAB = TRUE
If you get an ImportError, it's because your import is not working.
Incorrect color code (IN_COLAB)
Initialize the API_KEY, and check if the code runs in a Colab-enviroment. In the case of a successful import, the IN_COLAB Flag is set as True. If not, then it will default to False.
Class AgentType (Enum)
ANALYZER "analyzer"
In search of: "researcher"
Synthesizer = "synthesizer"
The VALIDATOR is = "validator"
@dataclass
Class Message
sender: str
Receiver:
Content:
msg_type str
No metadata
Take a look at the Notebook
The core structure of agent interaction is defined. AgentType is a n-bit enum that categorizes four roles in a network: Analyst, Researcher and Synthesizer. Each role has specialized functions. The Message dataclass is the standard format of inter-agent communications. It includes sender IDs and recipient IDs as well as message type and content. Optional metadata can also be included.
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 API_KEY is not available:
Return to the Homepage "❌ 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}
Give a specific response (maximum 100 words) to add value to the discussion on your network.
"""
try:
response = await asyncio.to_thread(
self.model.generate_content, prompt
)
Return response.text.strip()
Special Exceptions as follows:
The return of 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, see self.network.agents
If agent_id and exclude_self are equal, the condition is:
You can continue reading
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"🤖 {self.id} ({self.type.value}): {response}")
If you are random()
Take a look at the Notebook
GeminiAgent is a class that defines behavior and abilities of agents in the network. Upon initialization the class assigns a unique identifier, role type and a referential to the network of agents and loads Gemini 2.0 Flash. Role-specific system prompts are used to create intelligent responses, based on the incoming message. This is done asynchronously by a queue. The context memory of each agent allows them to remember recent interactions. They can then respond to messages directly or send out targeted ones. The run() The method is a continuous processing of messages that promotes communication by allowing agents to respond when necessary.
It is a class agentNetwork.
def __init__(self):
Self-agents:[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 agent_id is not:
Agent_id=f"{agent_type.value}_{len(self.agents)+1}"
agent = GeminiAgent(agent_id, agent_type, self)
self.agents[agent_id] = Agent
print(f"✅ 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 is in the self.agent:
await self.agents[message.receiver].inbox.put(message)
else:
print(f"⚠️ Agent {message.receiver} not found")
async def initiate_task(self, task: str):
"""Start a collaborative task"""
print(f"🚀 Starting task: {task}")
analyzer_agents = [aid for aid, agent in self.agents.items()
if agent.type == AgentType.ANALYZER]
If you 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"🌐 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("⏰ Network session completed")
finally:
Self-running = FALSE
Take a look at the Notebook
AgentNetwork manages coordination and communication among all agents within the system. The class allows for dynamically adding agents, each with a unique ID and role, keeps a record of messages exchanged, and routes the message to its intended recipient. It can send the initial message to an agent Analyzer and run the asynchronous loop of events for a specific duration. This allows the agents to interact and work together in a shared space.
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📊 Network completed with {len(network.message_log)} messages exchanged")
agent_participation = {Agent_participation: aid msg = sum (1 for message 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 you are interested in a specific color, please click on the IN_COLAB button.
Import user data from Google.colab
try:
API_KEY = userdata.get('GEMINI_API_KEY')
genai.configure(api_key=API_KEY)
print("✅ API key loaded from Colab secrets")
Return to True
except:
print("💡 To use Colab secrets: Add 'GEMINI_API_KEY' in the secrets panel")
print("🔑 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("✅ API key configured successfully!")
return True
else:
print("❌ Invalid API key")
Return False
Except KeyboardInterrupt
print("n❌ Setup cancelled")
Return False
Take a look at the Notebook
The Demo_Agent_Network() The function is responsible for orchestrating the entire workflow of the agents. It creates a new agent network, assigns roles to four specific agents, starts a cybersecurity task and then runs the network in asynchronous mode, tracking the message exchanges. Meanwhile, setup_api_key() Provides an interactive way to secure configure the Gemini API keys, tailored for Colab as well as non-Colab environments.
If the __name__ equals "__main__":
print("🧠 Gemini Agent Network Protocol")
print("=" * 40)
If setup_api_key is not set up():
print("❌ Cannot run without valid API key")
()
print("n🚀 Starting demo...")
If you are interested in a specific color, please click on the IN_COLAB button.
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, this code is used to launch the Gemini Agent Network Protocol. This begins with a prompt asking the user to enter the Gemini API keys, and exiting if the API key was not supplied. The demo will launch after successful configuration. When running on Google Colab it will use nest_asyncio in order to comply with Colab event loop limitations. If not, then it uses Python’s native Asyncio.() Execute the agent collaboration asynchronous demonstration.
The tutorial concludes with a practical guide to implementing a Gemini-powered collaboration network. Here, the hands-on demonstration shows how autonomous agents are able to break complex problems down, generate insights collaboratively, and validate information.
Take a look at the Notebook. This research is the work of researchers. Also, feel free to follow us on Twitter Join our Facebook group! 99k+ ML SubReddit Subscribe Now our Newsletter.
Asif Razzaq, CEO of Marktechpost Media Inc. is a visionary engineer and entrepreneur who is dedicated to harnessing Artificial Intelligence’s potential for the social good. Marktechpost is his latest venture, a media platform that focuses on Artificial Intelligence. It is known for providing in-depth news coverage about machine learning, deep learning, and other topics. The content is technically accurate and easy to understand by an audience of all backgrounds. This platform has over 2,000,000 monthly views which shows its popularity.

