Close Menu
  • AI
  • Content Creation
  • Tech
  • Robotics
AI-trends.todayAI-trends.today
  • AI
  • Content Creation
  • Tech
  • Robotics
Trending
  • DeepSeek AI releases DeepSeek V4: Sparse attention and heavily compressed attention enable one-million-token contexts.
  • AI-Designed drugs by a DeepMind spinoff are headed to human trials
  • Apple’s new CEO must launch an AI killer product
  • OpenMythos Coding Tutorial: Recurrent-Depth Transformers, Depth Extrapolation and Mixture of Experts Routing
  • 5 Reasons to Think Twice Before Using ChatGPT—or Any Chatbot—for Financial Advice
  • OpenAI Releases GPT-5.5, a Absolutely Retrained Agentic Mannequin That Scores 82.7% on Terminal-Bench 2.0 and 84.9% on GDPval
  • Your Favorite AI Gay Thirst Traps: The Men Behind them
  • Mend Releases AI Safety Governance Framework: Masking Asset Stock, Danger Tiering, AI Provide Chain Safety, and Maturity Mannequin
AI-trends.todayAI-trends.today
Home»Tech»Modular Python Guide for Building AI Agents that are Event Driven with UAgents & Google Gemini

Modular Python Guide for Building AI Agents that are Event Driven with UAgents & Google Gemini

Tech By Gavin Wallace22/06/20255 Mins Read
Facebook Twitter LinkedIn Email
DeepSeek Releases R1-0528: An Open-Source Reasoning AI Model Delivering Enhanced
DeepSeek Releases R1-0528: An Open-Source Reasoning AI Model Delivering Enhanced
Share
Facebook Twitter LinkedIn Email

This tutorial will show you how to create a. UAgents The framework is used to develop a lightweight AI agent on Google’s Gemini API. Nest_asyncio will be used to create event loops that are nested. Then, configure your Gemini API Key and the GenAI Client. We’ll then define the communication contracts and Question and Answer Pydantic Models, as well as spin up two UAgents. “gemini_agent” Gemini is a Gemini that monitors incoming Question messages. “flash” Answer message model that emits Answer messages and generates responses “client_agent” This code triggers an initial query and then handles any incoming response. We’ll also learn to use Python’s Multiprocessing tool and gracefully close the event loop after the exchange has been completed. This will demonstrate UAgents seamless orchestration for inter-agent communication.

Google-genai Agents:!pip Install -q

The UAgents framework is installed, along with the Google GenAI library. This provides all the required tools to develop and run AI event agents in Gemini. This flag will run the installation in a quiet manner, so that your notebook output is clean. Take a look at the Notebook Here is a link to the article

import os, time, multiprocessing, asyncio
import nest_asyncio  
From Google, import Genai
BaseModel Field
Import Agents from Uagents, Context


nest_asyncio.apply()

We import essential Python modules. These include the Google GenAI Client, Pydantic to validate schemas and core UAgents. Finally, nest_asyncio.apply() Patches the event loop to run asynchronous UAgents in an interactive environment. Take a look at the Notebook Here is a link to the article

os.environ["GOOGLE_API_KEY"] = "Use Your Own API Key Here"


Client = client()

We now set the Gemini API key. The placeholder should be replaced with your key. Initialize the GenAI Client, which will then handle any subsequent requests made to Google Gemini Models. This will ensure that the agent can generate content via API.

This class is a base model for the question (basis) type.
    question: str = Field(...)


Class Answer (BaseModel:
 The answer is: str = Field (...)

The Pydantic model defines the message structures that agents exchange. Each model has a question and answer field. Pydantic allows us to validate and serialize incoming and egressing messages automatically, so that agents always work with properly-formatted data.

ai_agent = Agent(
    name="gemini_agent",
    seed="agent_seed_phrase",
    port=8000,
    endpoint=["http://127.0.0.1:8000/submit"]
)


@ai_agent.on_event("startup")
Async Def Ai_Startup(ctx Context)
    ctx.logger.info(f"{ai_agent.name} listening on {ai_agent.address}")


def ask_gemini(q: str) -> str:
    resp = client.models.generate_content(
        model="gemini-2.0-flash",
        contents=f"Answer the question: {q}"
    )
 Text return


@ai_agent.on_message(model=Question, replies=Answer)
async def handle_question(ctx: Context, sender: str, msg: Question):
    ans = ask_gemini(msg.question)
    await ctx.send(sender, Answer(answer=ans))

We instantiate UAgents in this block “gemini_agent” We then register a startup event handler that logs when the agent is ready, ensuring visibility into its lifecycle. The startup handler logs the ready state of the agent, giving us visibility into its entire lifecycle. The ask_gemini synchronous wrapper wraps the GenAI call from the client to Gemini. “flash” model. The @ai_agent.on_message handling handler also deserializes the incoming question messages, calls ask_gemini and sends back an answer payload asynchronously to the sender. Take a look at the Notebook Here is a link to the article

client_agent = Agent(
    name="client_agent",
    seed="client_seed_phrase",
    port=8001,
    endpoint=["http://127.0.0.1:8001/submit"]
)


@client_agent.on_event("startup")
Async ask_on_start (ctx: context)
    await ctx.send(ai_agent.address, Question(question="What is the capital of France?"))


@client_agent.on_message(model=Answer)
async def handle_answer(ctx: Context, sender: str, msg: Answer):
    print("📨 Answer from Gemini:", msg.answer)
 # Shutdown with more grace
    asyncio.create_task(shutdown_loop())


async def shutdown_loop():
 Wait for asyncio.sleep(1) to allow time for cleaning
    loop = asyncio.get_event_loop()
    loop.stop()

The premise of the a “client_agent” This program, when it starts, asks the gemini_agent for the capital city of France. It then waits to hear the answer, prints out the response and gracefully closes the loop. Take a look at the Notebook Here is a link to the article

def run_agent(agent):
    agent.run()


If the __name__ equals "__main__":
    p = multiprocessing.Process(target=run_agent, args=(ai_agent,))
    p.start()
    time.sleep(2)  


    client_agent.run()


    p.join()

We define an agent.run function to help us run the Agent.()The gemini_agent is launched in the process using Python multiprocessing. It starts the gemini_agent, blocks until the round trip is complete, then launches the client_agent.

This tutorial focuses on UAgents. We now have a blueprint to create modular AI services which communicate using well-defined message and event schemas. UAgents makes it easy to manage agent lifecycles, handle incoming messages and send structured responses, without the need for boilerplate network code. You can now expand the UAgents configuration to add more complex conversation workflows, different message types and dynamic agent detection.


Take a look at the Notebook here. This research is the work of researchers. Also, feel free to follow us on Twitter Don’t forget about our 100k+ 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.

AI Google google gemini
Share. Facebook Twitter LinkedIn Email
Avatar
Gavin Wallace

Related Posts

DeepSeek AI releases DeepSeek V4: Sparse attention and heavily compressed attention enable one-million-token contexts.

24/04/2026

OpenMythos Coding Tutorial: Recurrent-Depth Transformers, Depth Extrapolation and Mixture of Experts Routing

24/04/2026

OpenAI Releases GPT-5.5, a Absolutely Retrained Agentic Mannequin That Scores 82.7% on Terminal-Bench 2.0 and 84.9% on GDPval

24/04/2026

Mend Releases AI Safety Governance Framework: Masking Asset Stock, Danger Tiering, AI Provide Chain Safety, and Maturity Mannequin

24/04/2026
Top News

5 Reasons to Think Twice Before Using ChatGPT—or Any Chatbot—for Financial Advice

The jammer wants to block AI wearables that are always listening. This is probably not going to work

AI will never be conscious

The AGI Battle Between Microsoft and OpenAI is More Than Just a Contract

Bryan Johnson is going to die

Load More
AI-Trends.Today

Your daily source of AI news and trends. Stay up to date with everything AI and automation!

X (Twitter) Instagram
Top Insights

Amazon researchers reveal Mitra: Tabular Machine Learning Advanced with Synthetic Preferences

23/07/2025

Google releases Conductor, a Gemini CLI context-driven extension that saves knowledge in Markdown format and orchestrates workflows.

02/02/2026
Latest News

DeepSeek AI releases DeepSeek V4: Sparse attention and heavily compressed attention enable one-million-token contexts.

24/04/2026

AI-Designed drugs by a DeepMind spinoff are headed to human trials

24/04/2026
X (Twitter) Instagram
  • Privacy Policy
  • Contact Us
  • Terms and Conditions
© 2026 AI-Trends.Today

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