Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.mavera.io/llms.txt

Use this file to discover all available pages before exploring further.

Scenario

Traffic just spiked — maybe a tweet went viral, a Product Hunt launch is live, or a competitor’s outage is sending visitors your way. You pull GA4’s real-time report showing active users by page and traffic source, identify the spike, and send it to Mave for diagnosis and response recommendations. The result is a real-time playbook: what’s happening, why, and what to do next.

Architecture

Code

import os, requests
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    RunRealtimeReportRequest, Dimension, Metric,
)

PROPERTY_ID = os.environ["GA4_PROPERTY_ID"]
MV = os.environ["MAVERA_API_KEY"]

client = BetaAnalyticsDataClient()

rt_by_page = client.run_realtime_report(RunRealtimeReportRequest(
    property=f"properties/{PROPERTY_ID}",
    dimensions=[Dimension(name="unifiedPagePathScreen")],
    metrics=[Metric(name="activeUsers")],
    limit=20,
))

rt_by_source = client.run_realtime_report(RunRealtimeReportRequest(
    property=f"properties/{PROPERTY_ID}",
    dimensions=[Dimension(name="sessionSource"), Dimension(name="sessionMedium")],
    metrics=[Metric(name="activeUsers")],
    limit=15,
))

rt_total = client.run_realtime_report(RunRealtimeReportRequest(
    property=f"properties/{PROPERTY_ID}",
    metrics=[Metric(name="activeUsers")],
))

total_active = int(rt_total.rows[0].metric_values[0].value) if rt_total.rows else 0

page_data = []
for row in rt_by_page.rows:
    page_data.append({
        "page": row.dimension_values[0].value,
        "active": int(row.metric_values[0].value),
    })

source_data = []
for row in rt_by_source.rows:
    source_data.append({
        "source": row.dimension_values[0].value,
        "medium": row.dimension_values[1].value,
        "active": int(row.metric_values[0].value),
    })

BASELINE_ACTIVE = int(os.environ.get("BASELINE_ACTIVE_USERS", "50"))
spike_ratio = total_active / max(BASELINE_ACTIVE, 1)

page_block = "\n".join(f"- {p['page']}: {p['active']} active users" for p in page_data[:10])
source_block = "\n".join(f"- {s['source']}/{s['medium']}: {s['active']} active" for s in source_data[:10])

print(f"Total active: {total_active} (baseline: {BASELINE_ACTIVE}, ratio: {spike_ratio:.1f}x)")

if spike_ratio > 1.5:
    mave = requests.post(
        "https://app.mavera.io/api/v1/mave/chat",
        headers={"Authorization": f"Bearer {MV}", "Content-Type": "application/json"},
        json={"message": f"""We're seeing a traffic spike on our website. Diagnose and recommend a response.

REAL-TIME DATA:
- Total active users: {total_active} (normal baseline: {BASELINE_ACTIVE}, this is {spike_ratio:.1f}x normal)

TOP PAGES BY ACTIVE USERS:
{page_block}

TRAFFIC SOURCES:
{source_block}

Analyze:
1. What's likely driving this spike? (based on page + source patterns)
2. Is this an opportunity or a threat? (e.g. viral content vs competitor outage vs bot traffic)
3. Immediate actions (next 30 minutes)
4. Follow-up actions (next 24 hours)
5. Content to publish or promote RIGHT NOW to capitalize
6. If this is from a specific source (e.g. social, referral), what's the engagement playbook?"""},
    ).json()

    print("\n--- Spike Analysis ---")
    print(mave.get("content", "")[:2500])
else:
    print("No significant spike detected. Run this script when traffic exceeds 1.5x baseline.")

Example Output

Active: 342 (baseline: 50, 6.8x)

--- Spike Analysis ---

## Diagnosis
Traffic is concentrated on /blog/ai-marketing-2026 (189 active users) with
the primary source being twitter/social (201 active). This pattern indicates
a viral social share — likely a tweet linking to your blog post.

## Assessment: OPPORTUNITY
This is organic amplification. The blog post is resonating. No bot indicators
(diverse pages getting traffic, source is identifiable social media).

## Immediate Actions (Next 30 Minutes)
1. **Pin a reply** to the viral tweet with a CTA to your product
2. **Add an exit-intent popup** on the blog post with a lead magnet
3. **Publish a follow-up tweet thread** expanding on the blog's key points
4. **Alert sales** — any leads from this page in the last hour get priority

## Follow-Up (Next 24 Hours)
1. Publish a Part 2 blog post while attention is high
2. Create a LinkedIn post repurposing the blog's key insight
3. Email your list with the blog post as featured content
4. Build a retargeting audience from today's visitors

Error Handling

GA4 real-time reports show data from the last 30 minutes with ~1-minute latency. Numbers are approximate and may differ from standard reports.
Set BASELINE_ACTIVE_USERS to your typical real-time user count. Check GA4 → Reports → Real-time during normal hours to establish this.
Real-time reports count against the same 10 concurrent / 50,000 daily quota. Don’t poll more frequently than every 60 seconds.

What’s Next

GA4 Integration

Back to GA4 integration overview

Landing Page Performance → Content Refresh

Rewrite underperforming landing page copy

Acquisition Channel × Persona Mapping

Map channel-demographic pairs to personas

Mave Agent

Full reference for POST /api/v1/mave/chat