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

      The Power Of The Intl API: A Definitive Guide To Browser-Native Internationalization

      August 8, 2025

      This week in AI dev tools: GPT-5, Claude Opus 4.1, and more (August 8, 2025)

      August 8, 2025

      Elastic simplifies log analytics for SREs and developers with launch of Log Essentials

      August 7, 2025

      OpenAI launches GPT-5

      August 7, 2025

      3 portable power stations I travel everywhere with (and how they differ)

      August 9, 2025

      I tried Lenovo’s new rollable ThinkBook and can’t go back to regular-sized screens

      August 9, 2025

      The Creators of the Acclaimed Silent Hill 2 Remake Present a Deep Dive Into the Story of Their Newest Horror Game IP — and It’s So Bizarre and Insane That It’s Convinced Me To Put It on My Wishlist

      August 9, 2025

      Forget Back to School Deals — Lenovo’s Clearance Sale is Where You’ll Find Amazing Discounts on Laptops, Mini PCs, and More, While Supplies Last

      August 9, 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

      spatie/laravel-flare

      August 9, 2025
      Recent

      spatie/laravel-flare

      August 9, 2025

      Establishing Consistent Data Foundations with Laravel’s Database Population System

      August 8, 2025

      Generate Postman Collections from Laravel Routes

      August 8, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      The Creators of the Acclaimed Silent Hill 2 Remake Present a Deep Dive Into the Story of Their Newest Horror Game IP — and It’s So Bizarre and Insane That It’s Convinced Me To Put It on My Wishlist

      August 9, 2025
      Recent

      The Creators of the Acclaimed Silent Hill 2 Remake Present a Deep Dive Into the Story of Their Newest Horror Game IP — and It’s So Bizarre and Insane That It’s Convinced Me To Put It on My Wishlist

      August 9, 2025

      Forget Back to School Deals — Lenovo’s Clearance Sale is Where You’ll Find Amazing Discounts on Laptops, Mini PCs, and More, While Supplies Last

      August 9, 2025

      The Gaming Desktop I’ve Relied on More Than Any Other Is More Powerful and Sleeker Than Ever — But Damn, It’s Expensive

      August 9, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Machine Learning»Building Event-Driven AI Agents with UAgents and Google Gemini: A Modular Python Implementation Guide

    Building Event-Driven AI Agents with UAgents and Google Gemini: A Modular Python Implementation Guide

    June 21, 2025

    In this tutorial, we demonstrate how to use the UAgents framework to build a lightweight, event-driven AI agent architecture on top of Google’s Gemini API. We’ll start by applying nest_asyncio to enable nested event loops, then configure your Gemini API key and instantiate the GenAI client. Next, we’ll define our communication contracts, Question and Answer Pydantic models, and spin up two UAgents: one “gemini_agent” that listens for incoming Question messages, invokes the Gemini “flash” model to generate responses, and emits Answer messages; and one “client_agent” that triggers a query upon startup and handles the incoming answer. Finally, we’ll learn how to run these agents concurrently using Python’s multiprocessing utility and gracefully shut down the event loop once the exchange is complete, illustrating UAgents’ seamless orchestration of inter-agent messaging.

    Copy CodeCopiedUse a different Browser
    !pip install -q uagents google-genai

    We install the UAgents framework and the Google GenAI client library, providing the necessary tooling to build and run your event-driven AI agents with Gemini. The q flag runs the installation quietly, keeping your notebook output clean. Check out the Notebook here

    Copy CodeCopiedUse a different Browser
    import os, time, multiprocessing, asyncio
    import nest_asyncio  
    from google import genai
    from pydantic import BaseModel, Field
    from uagents import Agent, Context
    
    
    nest_asyncio.apply()
    

    We set up our Python environment by importing essential modules, system utilities (os, time, multiprocessing, asyncio), nest_asyncio for enabling nested event loops (critical in notebooks), the Google GenAI client, Pydantic for schema validation, and core UAgents classes. Finally, nest_asyncio.apply() patches the event loop so you can run asynchronous UAgents workflows seamlessly in interactive environments. Check out the Notebook here

    Copy CodeCopiedUse a different Browser
    os.environ["GOOGLE_API_KEY"] = "Use Your Own API Key Here"
    
    
    client = genai.Client()
    

    Here we set our Gemini API key in the environment. Be sure to replace the placeholder with your actual key, and then initialize the GenAI client, which will handle all subsequent requests to Google’s Gemini models. This step ensures our agent has authenticated access to generate content through the API.

    Copy CodeCopiedUse a different Browser
    class Question(BaseModel):
        question: str = Field(...)
    
    
    class Answer(BaseModel):
        answer: str = Field(...)

    These Pydantic models define the structured message formats that our agents will exchange with each other. The Question model carries a single question string field, and the Answer model carries a single answer string field. By using Pydantic, we get automatic validation and serialization of incoming and outgoing messages, ensuring that each agent always works with well-formed data.

    Copy CodeCopiedUse a different Browser
    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}"
        )
        return resp.text
    
    
    @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))

    In this block, we instantiate the UAgents “gemini_agent” with a unique name, seed phrase (for deterministic identity), listening port, and HTTP endpoint for message submissions. We then register a startup event handler that logs when the agent is ready, ensuring visibility into its lifecycle. The synchronous helper ask_gemini wraps the GenAI client call to Gemini’s “flash” model. At the same time, the @ai_agent.on_message handler deserializes incoming Question messages, invokes ask_gemini, and asynchronously sends back a validated Answer payload to the original sender. Check out the Notebook here

    Copy CodeCopiedUse a different Browser
    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 def 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)
        # Use a more graceful shutdown
        asyncio.create_task(shutdown_loop())
    
    
    async def shutdown_loop():
        await asyncio.sleep(1)  # Give time for cleanup
        loop = asyncio.get_event_loop()
        loop.stop()
    

    We set up a “client_agent” that, upon startup, sends a Question to the gemini_agent asking for the capital of France, then listens for an Answer, prints the received response, and gracefully shuts down the event loop after a brief delay. Check out the Notebook here

    Copy CodeCopiedUse a different Browser
    def run_agent(agent):
        agent.run()
    
    
    if __name__ == "__main__":
        p = multiprocessing.Process(target=run_agent, args=(ai_agent,))
        p.start()
        time.sleep(2)  
    
    
        client_agent.run()
    
    
        p.join()
    

    Finally, we define a helper run_agent function that calls agent.run(), then uses Python’s multiprocessing to launch the gemini_agent in its process. After giving it a moment to spin up, it runs the client_agent in the main process, blocking until the answer round-trip completes, and finally joins the background process to ensure a clean shutdown.

    In conclusion, with this UAgents-focused tutorial, we now have a clear blueprint for creating modular AI services that communicate via well-defined event hooks and message schemas. You’ve seen how UAgents simplifies agent lifecycle management, registering startup events, handling incoming messages, and sending structured replies, all without boilerplate networking code. From here, you can expand your UAgents setup to include more sophisticated conversation workflows, multiple message types, and dynamic agent discovery.


    Check out the Notebook here. 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 100k+ ML SubReddit and Subscribe to our Newsletter.

    The post Building Event-Driven AI Agents with UAgents and Google Gemini: A Modular Python Implementation Guide appeared first on MarkTechPost.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleMistral AI Releases Mistral Small 3.2: Enhanced Instruction Following, Reduced Repetition, and Stronger Function Calling for AI Integration
    Next Article Why Generalization in Flow Matching Models Comes from Approximation, Not Stochasticity

    Related Posts

    Machine Learning

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

    August 9, 2025
    Machine Learning

    VL-Cogito: Advancing Multimodal Reasoning with Progressive Curriculum Reinforcement Learning

    August 9, 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

    CVE-2025-53934 – WeGIA Stored Cross-Site Scripting (XSS) Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-47785 – Emlog SQL Injection and Remote Code Execution

    Common Vulnerabilities and Exposures (CVEs)

    Leaked Meta Quest 3S Xbox Edition could launch tomorrow

    Operating Systems

    Mlmmj is a simple and slim mailing list manager

    Linux

    Highlights

    CVE-2025-44083 – D-Link DI-8100 Remote Authentication Bypass Vulnerability

    May 21, 2025

    CVE ID : CVE-2025-44083

    Published : May 21, 2025, 7:16 p.m. | 1 hour, 25 minutes ago

    Description : An issue in D-Link DI-8100 16.07.26A1 allows a remote attacker to bypass administrator login authentication

    Severity: 0.0 | NA

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    UX analytics changed my career — here’s how it can change yours

    August 7, 2025

    Google’s Jules AI coding agent built a new feature I could actually ship – while I made coffee

    May 27, 2025

    The Mainframe Muggle Chronicles – Part 2: A Heretic Among Zealots

    May 22, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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