惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LINUX DO - 最新话题
小众软件
小众软件
C
Check Point Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
V
Visual Studio Blog
Last Week in AI
Last Week in AI
P
Proofpoint News Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The GitHub Blog
The GitHub Blog
T
Tailwind CSS Blog
Recorded Future
Recorded Future
雷峰网
雷峰网
WordPress大学
WordPress大学
A
Arctic Wolf
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Project Zero
Project Zero
T
Tor Project blog
T
Threat Research - Cisco Blogs
Scott Helme
Scott Helme
Spread Privacy
Spread Privacy
G
Google Developers Blog
Security Latest
Security Latest
MongoDB | Blog
MongoDB | Blog
T
Threatpost
I
InfoQ
T
Tenable Blog
T
The Exploit Database - CXSecurity.com
S
Security Affairs
H
Hackread – Cybersecurity News, Data Breaches, AI and More
人人都是产品经理
人人都是产品经理
C
Cisco Blogs
博客园 - 三生石上(FineUI控件)
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
aimingoo的专栏
aimingoo的专栏
C
CXSECURITY Database RSS Feed - CXSecurity.com
美团技术团队
Google DeepMind News
Google DeepMind News
The Hacker News
The Hacker News
D
Docker
博客园 - 【当耐特】
大猫的无限游戏
大猫的无限游戏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Vercel News
Vercel News
PCI Perspectives
PCI Perspectives
Microsoft Azure Blog
Microsoft Azure Blog
C
CERT Recently Published Vulnerability Notes
月光博客
月光博客
Cloudbric
Cloudbric
A
About on SuperTechFans
F
Fortinet All Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
GCP: Upgrading a LINE Bot with Vertex AI ADK Tools for Smart Business Cards and Backup Search
Evan Lin · 2026-05-27 · via DEV Community

image-20260526210750701

Preface

In the previous article, we successfully upgraded the LINE business card assistant robot (linebot-namecard-python) from the AI Studio API Key verification mode to the enterprise-grade Google Cloud Vertex AI mechanism, completely freeing us from the 429 quota anxiety.

However, the original method of searching for business cards had significant limitations: We had to first fetch all the user's business cards from Firebase, package them into a huge JSON array, and then stuff them into the prompt, asking Gemini to select the most relevant business card object to return.

This approach has three major drawbacks:

  1. Token Waste: With many business cards, each search is a ruthless blow to the token balance.
  2. Lack of Flexibility: The model can only search passively; it cannot proactively ask for details or perform data updates.
  3. Unable to Link Operations: If the user says, "Help me change David Wang's phone number," we have to write a bunch of complex NLP judgments and branches in the Webhook.

To solve these pain points, we decided to refactor the robot and embrace Google Cloud's latest, powerful, and code-friendly Agent Development Kit (ADK)!

This article will share with you how we completely refactored Firebase access into ADK Tools, implemented dynamic closures, and the various top-tier blood and tears pitfalls we encountered during deployment on Cloud Run and with the Antigravity CLI tool!


Architecture Upgrade: Why Choose ADK and Tools?

Agent Development Kit (ADK) is a code-first agent development framework launched by Google Cloud. Previously, in order for us to allow large models to call external APIs, we had to manually write long OpenAPI schemas or complex function-calling descriptions; ADK simplifies all of this into simple Python functions!

We planned five core data operation functions for the business card Agent and registered them as Tools of the Agent in the form of Python functions:

  1. get_all_namecards(): Reads the list of all business cards (including IDs) for the current user.
  2. get_namecard_by_id(card_id): Retrieves the detailed content of a specific business card.
  3. display_namecard(card_id): The core tool! Called when the model matches a business card, used to tell the Python main program "it's time to display this business card on the screen".
  4. update_namecard_memo(card_id, memo): Updates the business card memo.
  5. update_namecard_field(card_id, field, value): Directly updates the specified fields of the business card (name, phone, email, etc.) in natural language.

Core Code Rewrite: Dynamic Closure Tools Implementation

In Webhook development, the most important thing is security. We absolutely cannot allow user A to search or modify user B's business cards.

Therefore, we cannot implement static, global Database Tools. Instead, in handle_smart_query, we dynamically create exclusive Tools for each conversation request through the closure mechanism.

This approach not only perfectly binds the user's user_id but also utilizes the found_card_ids list in the closure to perfectly collect "all business card IDs that the model wants to present to the user" during the decision-making process:

def make_adk_tools(user_id: str, found_card_ids: list):
    """Dynamically create exclusive Firebase data access and operation tools for a specific user"""
    def get_all_namecards() -> list[dict]:
        """Get the list of all business card data in the Firebase database for the current user.
        Each business card data contains a unique card_id field."""
        cards_dict = firebase_utils.get_all_cards(user_id)
        all_cards_list = []
        for card_id, card_data in cards_dict.items():
            card_data_with_id = card_data.copy()
            card_data_with_id['card_id'] = card_id
            all_cards_list.append(card_data_with_id)
        return all_cards_list

    def get_namecard_by_id(card_id: str) -> dict:
        """Get the detailed fields and data of a single business card through a specific card_id."""
        return firebase_utils.get_card_by_id(user_id, card_id)

    def display_namecard(card_id: str) -> str:
        """Display a specific business card to the user.
        When a business card matching the search is found, be sure to call this tool."""
        if card_id not in found_card_ids:
            found_card_ids.append(card_id)
        return f"已將名片 ID 標記為顯示:{card_id}"

    def update_namecard_memo(card_id: str, memo: str) -> bool:
        """Update the memo/note information of a specific business card."""
        return firebase_utils.update_namecard_memo(card_id, user_id, memo)

    def update_namecard_field(card_id: str, field: str, value: str) -> bool:
        """Update the specified field of a specific business card (optional fields: name, title, company, address, phone, email)."""
        return firebase_utils.update_namecard_field(
            user_id, card_id, field, value
        )

    return [
        get_all_namecards,
        get_namecard_by_id,
        display_namecard,
        update_namecard_memo,
        update_namecard_field
    ]

Refactored Main Webhook Logic (handle_smart_query)

Now, when LINE receives a text query, we only need to pass the message to the ADK Runner to run once. Once the Agent decides to call display_namecard, we combine the Agent's friendly Chinese explanation (text reply) with the business card Flex Message (the entire business card) in the LINE reply:

async def handle_smart_query(event: MessageEvent, user_id: str, msg: str):
    found_card_ids = []
    tools = make_adk_tools(user_id, found_card_ids)

    # 1. Create an ADK Agent equipped with exclusive Tools
    agent = Agent(
        name="namecard_agent",
        model="gemini-3-flash-preview",
        instruction=(
            "You are a smart and friendly LINE business card assistant. Your job is to help users manage their business card data.\n"
            "You can use the appropriate tools to read or modify business card records in the Firebase database.\n\n"
            "【Core Operation Guidelines】\n"
            "1. 【Query】When a user queries for someone's or a company's business card, please first call get_all_namecards to get all the data and perform analysis and comparison in the background.\n"
            "2. 【Display】As long as a business card that meets the conditions is found, 『must』 call the display_namecard tool to mark the card_id of that business card for display, so that the system can draw and present it on the LINE screen.\n"
            "3. 【Modify】If the user wants to modify a business card (e.g., phone number, Email, memo), please first compare and find the card_id, and then call the corresponding update tool (such as update_namecard_field or update_namecard_memo) to make the modification. After the modification is successful, 『must』 call display_namecard again to display the updated business card, allowing the user to confirm.\n"
            "4. 【Reply】Finally, please reply to the user with a friendly and concise traditional Chinese tone about the operation results or search progress."
        ),
        tools=tools,
    )

    # 2. Execute the Runner with an in-memory Session
    runner = Runner(
        app_name="namecard_bot_app",
        agent=agent,
        session_service=InMemorySessionService()
    )

    try:
        events = await runner.run_debug(
            msg, user_id=user_id, session_id=user_id
        )

        # Combine the Agent's text reply
        final_text = ""
        for ev in events:
            if ev.content and ev.content.parts:
                for part in ev.content.parts:
                    if part.text:
                        final_text += part.text

        final_text = final_text.strip() or "為您完成處理。"

        reply_msgs = [TextSendMessage(
            text=final_text,
            quick_reply=get_quick_reply_items()
        )]

        # 3. Get the business cards marked for display by the Agent and convert them to Flex Messages
        if found_card_ids:
            for card_id in found_card_ids[:5]:
                card_data = firebase_utils.get_card_by_id(user_id, card_id)
                if card_data:
                    reply_msgs.append(
                        flex_messages.get_namecard_flex_msg(card_data, card_id)
                    )

        await line_bot_api.reply_message(event.reply_token, reply_msgs)


Blood and Tears Pitfalls During the Migration Process

The refactoring process cannot be smooth sailing. In this upgrade, we encountered three top-tier deep pits, each of which almost prevented the online container from providing services. Here is valuable pit-filling experience:

Pitfall 1: Uvicorn Crashes the Event Loop at Startup

When we excitedly pushed the container containing google-adk onto Cloud Run, the deployment failed due to a health check timeout at the last moment! Checking the GCP Log, we were greeted with this heartbreaking RuntimeError:

  File "/app/app/bot_instance.py", line 7, in <module>
    session = aiohttp.ClientSession()
  File "/usr/local/lib/python3.10/site-packages/aiohttp/client.py", line 321, in __init__
    loop = loop or asyncio.get_running_loop()
RuntimeError: no running event loop

Reason: Under the new dependency environment, app/bot_instance.py directly instantiated aiohttp.ClientSession() globally when it was imported (Import Time). However, at this time, Uvicorn's asyncio Event Loop had not even started! This caused aiohttp to throw an exception and crash directly because it couldn't find a running event loop.

Solution: We designed a lazy-load LazyLineBotApi wrapper, delaying the creation of ClientSession and AsyncLineBotApi until the first LINE Webhook request comes in (at this time, the Event Loop must be running), perfectly avoiding the Import Time initialization crash:

class LazyLineBotApi:
    def __init__ (self):
        self._api = None
        self.session = None

    def _get_api(self):
        if self._api is None:
            self.session = aiohttp.ClientSession()
            async_http_client = AiohttpAsyncHttpClient(self.session)
            self._api = AsyncLineBotApi(
                config.CHANNEL_ACCESS_TOKEN, async_http_client
            )
        return self._api

    def __getattr__ (self, name):
        return getattr(self._get_api(), name)

line_bot_api = LazyLineBotApi()


Pitfall 2: GCP's Default GOOGLE_CLOUD_LOCATION and Region 404

After successfully starting the container, we tried entering text in LINE, but saw a big red error again in the background:

Error executing ADK smart query: 404 NOT_FOUND. 
Publisher Model `projects/line-vertex/locations/asia-east1/publishers/google/models/gemini-3-flash-preview` was not found.

Reason: Because our Cloud Run service is deployed in Taiwan (asia-east1), GCP will automatically inject GOOGLE_CLOUD_LOCATION=asia-east1 into the environment variables. However, in the Vertex AI ecosystem, many of the latest and most powerful models (such as gemini-3-flash-preview) only provide services in the global region! When the underlying SDK of ADK automatically reads asia-east1 to search for models, it will naturally throw a 404.

Solution: We directly override the environment variable at the first moment in the system's configuration entry app/config.py, directing all Vertex AI model searches to the global region:

# Force GOOGLE_CLOUD_LOCATION to global so that Vertex AI and ADK look
# for models in the global region
os.environ["GOOGLE_CLOUD_LOCATION"] = "global"


Pitfall 3: Insurance Mechanism in Extreme Situations - Local Keyword Backup Search

After the user's LINE bot goes live, any API quota explosion or network timeout should not cause the user to see a cold "server failure". To guarantee production-level SLA, we added a seamless keyword search backup mechanism (Local Keyword Fallback) in the except block of handle_smart_query.

If Vertex AI or ADK encounters any exceptions during execution, the system will automatically enable Firebase local keyword matching in the background, still perfectly returning matching business card Flex messages, providing the user with the most elegant protection net:

    except Exception as e:
        print(f"Error executing ADK smart query: {e}")
        # Backup search mechanism: When Vertex AI or ADK API is abnormal, automatically enable local keyword filtering search to ensure service continuity
        try:
            all_cards_dict = firebase_utils.get_all_cards(user_id)
            fallback_matches = []
            if all_cards_dict:
                for card_id, card_data in all_cards_dict.items():
                    name = card_data.get("name", "").lower()
                    company = card_data.get("company", "").lower()
                    query_lower = msg.lower()
                    if query_lower in name or query_lower in company:
                        fallback_matches.append((card_id, card_data))

            if fallback_matches:
                reply_msgs = [TextSendMessage(
                    text="「智慧搜尋」服務暫時無法取得,"
                         "已自動啟用「關鍵字備援搜尋」為您找到以下相關名片:",
                    quick_reply=get_quick_reply_items()
                )]
                for card_id, card_data in fallback_matches[:5]:
                    reply_msgs.append(
                        flex_messages.get_namecard_flex_msg(card_data, card_id)
                    )
                await line_bot_api.reply_message(event.reply_token, reply_msgs)
                return
        except Exception as fallback_err:
            print(f"Fallback search also failed: {fallback_err}")


Summary and Benefits

After refactoring into an ADK Agent + Tools architecture, it brought amazing substantial changes:

  1. Extreme Token Saving: The model only calls get_all_namecards when it needs to read business cards, and general conversations no longer need to repeatedly transmit huge JSON data.
  2. Multi-step Natural Dialogue Linking: The user only needs to type "Help me change David Wang's memo to 'Meeting next Monday'", and the model will automatically and continuously call get_all_namecards() -> find the ID -> call update_namecard_memo(id, ...) -> and then call display_namecard(id) to show the latest results.
  3. Code Quality Leap: In this refactoring, we also strictly controlled through flake8, completing 100% clean code formatting and zero-warning compilation.

The complete and linter-optimized code has been pushed to GitHub simultaneously. I hope this dynamic closure design and Cloud Run, Event Loop pit-filling practice can help everyone avoid more detours when building production-level AI Agent Web applications! See you next time!