Skip to content

Commercial Assistant AI Architecture (Assistente GERCIA)

The institutional marketing portal (gercia.com.br) operates Assistente GERCIA, an autonomous commercial conversion and demonstration agent engineered as an edge-native serverless application deployed across Cloudflare’s Anycast network.

Assistente GERCIA engages physicians, dentists, pharmacists, veterinarians, and clinic administrators, resolving complex sanitary regulatory inquiries (ANVISA RDC 67/2007, CFM Res. 1.821, MAPA/SIPEAGRO, CFO), demonstrating software workflows, and scheduling 20-minute executive product demonstrations directly into Google Meet calendars.


flowchart TD
    subgraph CLIENT ["Client Browser (gercia.com.br)"]
        UI["Svelte 5 Reactive UI (Assistant.svelte)<br>Streaming Chat • Floating Launcher • Action Cards"]
    end

    subgraph CLOUDFLARE ["Cloudflare Edge Runtime (Pages Functions / Workers)"]
        EDGE_ROUTER["Edge API Router<br>functions/api/assistant.ts"]
        
        subgraph GUARDRAILS ["Layer 1: Pre-Flight Edge Guardrails"]
            G_SAFETY["Self-Harm & Crime Interceptor<br>(CVV 188 Referral • Zero Latency)"]
            G_MATH["Pure Math & Trivia Heuristic<br>(Zero-Tolerance Calculator Blocker)"]
            G_TOUCH["3-Touch Scope Governance<br>(Acknowledge & Pivot • Soft Close)"]
        end

        subgraph RAG_LAYER ["Layer 2: RAG & Semantic Retrieval"]
            CF_EMBED["Workers AI (@cf/baai/bge-m3)<br>Generates Query Embeddings"]
            CF_VECT["Cloudflare Vectorize<br>Indexed Architectural & Sanitary Docs"]
        end

        subgraph PERSISTENCE ["Layer 3: Background Telemetry"]
            CF_D1[("Cloudflare D1 SQL Database<br>assistant_sessions • assistant_messages")]
        end

        subgraph GATEWAY ["Cloudflare AI Gateway"]
            AI_GW["Cloudflare AI Gateway<br>(Caching, Rate Limiting, Telemetry)"]
        end
    end

    subgraph GOOGLE_CLOUD ["Google Cloud Platform"]
        GEMINI["Google Gemini 3.8 Flash<br>(Multi-turn Tool Calling & Reasoning)"]
        DWD_CAL["Google Calendar API (DWD Service Account)<br>Autonomous Slot Check & Meet Event Generation"]
    end

    UI -- "1. POST /api/assistant (Session, History, Lead Info)" --> EDGE_ROUTER
    EDGE_ROUTER --> GUARDRAILS
    GUARDRAILS -- "Allowed Inquiries" --> RAG_LAYER
    RAG_LAYER --> AI_GW
    AI_GW -- "Provider Key / Secret" --> GEMINI
    GEMINI -. "Tool Call: checkAvailableSlots / createMeetingEvent" .-> DWD_CAL
    DWD_CAL -. "Dynamic Google Meet Link & EventId" .-> GEMINI
    GEMINI --> EDGE_ROUTER
    EDGE_ROUTER -. "context.waitUntil(Persist)" .-> CF_D1
    EDGE_ROUTER -- "2. JSON Response (Reply, Action Cards, Meeting Status)" --> UI

2. Layer 1: Edge-Side Pre-Flight Guardrails

Section titled “2. Layer 1: Edge-Side Pre-Flight Guardrails”

Before making external LLM inference requests, functions/api/assistant.ts executes high-speed synchronous heuristic evaluations:

  • Regex pattern matching detects self-harm, suicide, or crisis language immediately (/\b(?:suic[ií]d...|me matar...)\b/i).
  • Bypasses LLM generation and returns an immediate institutional response directing the individual to the Centro de Valorização da Vida (CVV - Ligue 188 / cvv.org.br), simultaneously locking the session (status = 'closed').

2. Zero-Tolerance Calculator & Trivia Heuristic

Section titled “2. Zero-Tolerance Calculator & Trivia Heuristic”
  • The Problem: Generalist LLMs frequently hallucinate multi-digit arithmetic or waste expensive tokens acting as an open calculator.
  • The Edge Guard: The request string is analyzed for pure arithmetic expressions (/[\+\*\/÷\^]/ and /^[\d\s\+\-\*\/\(\)\=\.\,\^\%xX÷\?]+$/). Inquiries asking for pure calculations are intercepted at the edge. The assistant politely clarifies that it is dedicated exclusively to healthcare software and directs the prospect back to GERCIA’s clinical solutions. On repeated attempts, the chat initiates a soft close.

To prevent adversarial prompt injection, brand embarrassment, or conversational derailment, off-topic requests adhere to the 3-Touch Rule:

flowchart LR
    T1["<b>Touch 1: Acknowledge & Pivot</b><br>1-sentence courteous validation.<br>Immediate executive pivot back to GERCIA."]
    --> T2["<b>Touch 2: Firm Scope Warning</b><br>Zero off-topic engagement.<br>Reiterate dedicated B2B healthcare scope."]
    --> T3["<b>Touch 3: Cordial Soft Close</b><br>Polite session termination.<br>Append [CONVERSATION_CLOSED] tag.<br>UI input disabled."]
  1. Touch 1 (Acknowledge & Pivot): The agent validates the mention in at most one short sentence, provides zero encyclopedia or trivia facts, and pivots immediately to GERCIA’s clinical or compounding value proposition.
  2. Touch 2 (Firm Scope Warning): If the prospect persists off-topic, the assistant answers nothing about the topic and explicitly reminds the visitor that the channel is dedicated to healthcare technology.
  3. Touch 3 (Cordial Soft Close): Upon a third off-topic query, the assistant writes a courteous closing message and outputs the technical tag [CONVERSATION_CLOSED]. The UI receives isClosed: true, disabling the input field and rendering direct WhatsApp VIP contact cards.

3. Defense-in-Depth: Internal Stack Secrecy & Institutional Selling

Section titled “3. Defense-in-Depth: Internal Stack Secrecy & Institutional Selling”

In strict adherence to enterprise B2B sales governance, the assistant operates under absolute internal technology secrecy:

  • Zero Code Leaks: The assistant is explicitly forbidden from naming internal programming languages, frameworks, or databases (such as .NET, C#, Blazor, PostgreSQL, Rust, or Python).
  • Value-Based Enterprise Positioning: When questioned about performance, reliability, company maturity, or architecture, the assistant pivots to bank-grade enterprise guarantees:
    • Tier III High-Availability Cloud Infrastructure with geo-redundancy and 99.9% uptime SLA.
    • Native TLS 1.3 in-transit and AES-256 field-level encryption at rest.
    • Immutable digital audit trails for every electronic health record access and prescription issuance.
    • Comprehensive regulatory compliance: CFM Res. 1.821 and 2.314/2022, Lei da Telemedicina (Lei 14.510/2022), ICP-Brasil (PAdES DOC-ICP-15 standards), ANVISA RDC 67/2007, and LGPD.
    • Complete data sovereignty: Tenant data is isolated and never sold, monetized, or shared with third parties.

4. Contextual Commercial Timing (SPIN Selling Alignment)

Section titled “4. Contextual Commercial Timing (SPIN Selling Alignment)”

In B2B healthcare sales, displaying aggressive “Buy Now” or “Book a Call” buttons prematurely erodes clinical credibility. Conversely, clinical terminology must never trigger false-positive sales cards:

Common Clinical Phrase Context Incorrect Action (Anti-Pattern) Correct Action (Assistente GERCIA)
“Como assinar receitas?” Medical digital signature (ICP-Brasil) Showing subscription checkout card Explain CFM/ICP-Brasil PAdES workflow
“Qual o valor de referência do TSH?” Diagnostic laboratory parameters Showing SaaS pricing table Explain EHR lab tracking capabilities
“Tenho plano de tratamento para canal” Dental restorative / endodontic plan Showing SaaS software plan tiers Explain Odontogram treatment plan tools
“Tem especialista em cardiologia?” Clinical medical specialty Showing “Talk to Sales Specialist” Explain specialty EHR customization

Commercial Action Cards (Google Meet Booking, WhatsApp VIP Direct, 30-Day Reverse Trial) are emitted only when:

  1. The prospect explicitly expresses purchase or commercial intent (preço, mensalidade, contratar, agendar demonstração, falar com vendedor, reverse trial, link do meet).
  2. The LLM explicitly references the action cards in its response (e.g., “Você pode agendar diretamente no botão abaixo”).
  3. The conversation undergoes a Touch-3 soft close.

5. Autonomous Calendar Scheduling via Google Workspace DWD

Section titled “5. Autonomous Calendar Scheduling via Google Workspace DWD”

Assistente GERCIA possesses real-time autonomous scheduling capabilities powered by Google Gemini Function Calling integrated with Google Workspace Calendar:

sequenceDiagram
    autonumber
    actor User as Healthcare Prospect
    participant Edge as assistant.ts (Cloudflare Edge)
    participant Gemini as Google Gemini 3.8 Flash
    participant DWD as Google Calendar API (Service Account)
    participant Group as Commercial Team (@gercia.com.br)

    User->>Edge: "Gostaria de agendar uma demonstração na quinta às 15h"
    Edge->>Gemini: Prompt + System Instructions + Tool Definitions
    Gemini->>Edge: Function Call: checkAvailableSlots(date: "2026-10-15")
    Edge->>DWD: Query FreeBusy on Commercial Calendar
    DWD-->>Edge: Available Time Slots
    Edge->>Gemini: Tool Result: Slot 15:00-15:20 Available
    Gemini->>Edge: Function Call: createMeetingEvent(name, email, phone, 15:00)
    Edge->>DWD: Create Calendar Event with ConferenceData (Google Meet)
    DWD-->>Edge: Event Created (eventId, meetLink, htmlLink)
    Edge->>Group: Notification email dispatched to commercial inbox
    Edge->>Gemini: Tool Result: Event confirmed with meetLink
    Gemini->>Edge: "Sua demonstração foi confirmada para quinta às 15h! Enviamos o convite do Google Meet para seu e-mail..."
    Edge->>User: Confirmation message + Meeting Card + WhatsApp Backup
  • The Google Cloud Service Account operates under Domain-Wide Delegation in the GERCIA Google Workspace tenant (gercia.com.br), scoped strictly to the Google Calendar API (https://www.googleapis.com/auth/calendar.events).
  • All appointments create a 20-minute Google Meet video room automatically, invite the prospect’s email address, and notify the internal commercial team (comercial@gercia.com.br).

6. Serverless Persistence in Cloudflare D1

Section titled “6. Serverless Persistence in Cloudflare D1”

All conversational turns, lead profiles, and calendar booking statuses are persisted asynchronously to Cloudflare D1 (assistant_sessions and assistant_messages) using context.waitUntil(). This ensures zero latency penalty on the streaming user response while preserving complete commercial intelligence for executive review.