以程序化方式使用 Google Analytics 中的 Ask Advisor 查询和分析数据

Data API 的 chat 方法支持以程序化方式访问 Google Analytics 中的 Ask Advisor,这是一款 AI 赋能的 Analytics 助手,可帮助您使用自然语言查询、分析和诊断 Google Analytics 数据。

虽然 Ask Advisor 可在 Google Analytics 用户界面中以交互方式使用,但 chat API 允许开发者、自主 AI 智能体和内部工具通过 HTTP 以编程方式与 Ask Advisor 进行交互。

重要提示:此产品使用了 AI 技术,可能会显示不准确的信息。您的对话活动可能会用于改进该产品,您在使用时须遵守 Google 的《条款》《AI 使用政策》和《隐私权政策》。

概览

chat 方法支持单轮临时数据问题和多轮对话会话:

  1. 单轮查询:提出即时分析问题(例如“上周我们的主要流量渠道是什么?”),并获得自然语言回答以及结构化数据表。
  2. 多轮对话:传递 sessionId 以保留对话记录并提出诊断性后续问题(例如,“为什么该时段的自然流量下降了?”)。
  3. 结构化数据回答:除了文本叙述外,回答还包含带有列标题和行的结构化 table 块。
  4. Chat 配额监控:通过将 returnPropertyQuota 设置为 true,检查剩余的每日和每小时 Chat 词元配额。

身份验证

调用 chat 方法需要使用以下范围进行 OAuth 2.0 授权:

准备工作

  1. 安装并初始化 gcloud CLI。

  2. 如需生成应用默认凭证并为您的账号提供必要的范围,请运行以下命令:

    gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.chatbot.read"
    
  3. 在 Google Analytics 界面中,向您的用户账号授予对 Google Analytics 媒体资源的访问权限。

  4. 输入以下命令来配置环境变量。 将 PROJECT_ID 替换为您的 项目的 ID,并将 PROPERTY_ID 替换为您的 Google Analytics 媒体资源的 ID。

      export PROJECT_ID=PROJECT_ID
      export PROPERTY_ID=PROPERTY_ID

示例 1:包含配额跟踪的单轮查询

如需发起新对话,请构建一个包含 userQuery 的 ChatRequest。将 returnPropertyQuota 设置为 true,以检查剩余的令牌余额。

场景:按设备细分的收入和转化率

您想比较过去 30 天内不同设备的收入和会话转化率。

HTTP 请求

curl -X POST \
  "https://analyticsdata.googleapis.com/v1alpha/properties/${PROPERTY_ID}:chat" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "x-goog-user-project: ${PROJECT_ID}" \
  -H "Content-Type: application/json" \
  -d '{
    "userQuery": "Compare our revenue and conversion rate across mobile vs desktop over the last 30 days.",
    "returnPropertyQuota": true
  }'

HTTP 响应

响应包含:

  • 新分配的 sessionId,可用于后续轮次。
  • blocks 列表,其中包含自然语言摘要 (text) 和结构化表格 (table)。文本块可以包含 Markdown 格式,例如粗体文字、标题和链接。
  • 媒体资源的 propertyQuota 详细信息。
{
  "sessionId": "692e9ab9-b338-4426-b006-a05f21ac7cd6",
  "blocks": [
    {
      "text": "Your report on revenue and conversion rates for mobile vs. desktop over the last 30 days (August 15 - September 13, 2026) is ready.\n\nHere is a summary of your revenue and conversion rate by device category:\n"
    },
   {
      "table": {
        "headers": [
          {
            "header": "Device Category",
            "dataType": "string"
          },
          {
            "header": "Total Revenue",
            "dataType": "string"
          },
          {
            "header": "User Conversion Rate",
            "dataType": "string"
          }
        ],
        "rows": [
          {
            "columns": [
              {
                "value": "Desktop"
              },
              {
                "value": "$17,412.62"
              },
              {
                "value": "99.9%"
              }
            ]
          },
          {
            "columns": [
              {
                "value": "Mobile"
              },
              {
                "value": "$15,309.41"
              },
              {
                "value": "99.46%"
              }
            ]
          }
      }
    },
    {
      "text": "**Revenue and Conversion Rate Trends:**\n\nRevenue from desktop devices saw a peak on August 18th, while mobile revenue peaked on August 30th. Conversion rates remained high and relatively stable for both desktop and mobile throughout the period."
    },
    {
      "text": "This product uses AI and may display inaccurate info. Your chat activity may be used to improve the product and your use is subject to Google's [Terms](https://policies.google.com/terms), [AI Use Policy](https://policies.google.com/terms/generative-ai/use-policy), and [Privacy Policy](https://policies.google.com/privacy). [Learn more about Chat AI Privacy](https://support.google.com/helpguide/answer/14185196)."
    }
  ],
   "propertyQuota": {
    "tokensPerDay": {
      "consumed": 26849,
      "remaining": 3723151
    },
    "tokensPerHour": {
      "consumed": 26849,
      "remaining": 473151
    }
  }
}

示例 2:多轮对话式诊断

如需在保留上下文的同时提出后续问题,请在请求中添加上一个回答返回的 sessionId。

场景:与上一时间段进行比较

在完成之前的设备比较后,您要求 Advisor 将结果与上一时间段进行比较。

HTTP 请求

curl -X POST \
  "https://analyticsdata.googleapis.com/v1alpha/properties/${PROPERTY_ID}:chat" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "x-goog-user-project: ${PROJECT_ID}" \
  -H "Content-Type: application/json" \
  -d '{
    "sessionId": "692e9ab9-b338-4426-b006-a05f21ac7cd6",
    "userQuery": "Compare results with the same period in the previous mounth."
  }'

HTTP 响应

Ask Advisor 会使用会话记忆将结果与上一时间段进行关联。

{
  "sessionId": "eb3284b2-49ce-4aed-b6d0-fdc15cb87b5f",
  "blocks": [
    {
      "text": "The following table provides a detailed comparison of total revenue and user conversion rate by device category for the two periods.\n"
    },
    {
      "table": {
        "headers": [
          {
            "header": "Device Category",
            "dataType": "string"
          },
          {
            "header": "Metric",
            "dataType": "string"
          },
          {
            "header": "Jul 16 - Aug 15, 2026",
            "dataType": "string"
          },
          {
            "header": "Aug 16 - Sep 14, 2026",
            "dataType": "string"
          }
        ],
        "rows": [
          {
            "columns": [
              {
                "value": "Desktop"
              },
              {
                "value": "Total Revenue"
              },
              {
                "value": "$17,412.62"
              },
              {
                "value": "$19,565.46"
              }
            ]
          },
          {
            "columns": [
              {
                "value": "Desktop"
              },
              {
                "value": "User Conversion Rate"
              },
              {
                "value": "1.90%"
              },
              {
                "value": "1.95%"
              }
            ]
          },
          {
            "columns": [
              {
                "value": "Mobile"
              },
              {
                "value": "Total Revenue"
              },
              {
                "value": "$13,997.19"
              },
              {
                "value": "$15,309.41"
              }
            ]
          },
          {
            "columns": [
              {
                "value": "Mobile"
              },
              {
                "value": "User Conversion Rate"
              },
              {
                "value": "1.95%"
              },
              {
                "value": "1.99%"
              }
            ]
          }
      }
    }
  ]
}

响应结构和数据块

ChatResponse 对象会返回 blocks 数组中的结构化组件:

屏蔽类型 字段 说明
叙述性文字 blocks[].text 人类可读的说明和全局性分析要点。
结构化表格 blocks[].table 表格数据细分,包含 headers(名称和数据类型)和 rows(单元格值)。

表头数据类型

blocks[].table.headers 中的列描述了语义数据类型:

  • string:分类文本值(例如 "desktop"、"/shop/apparel")。
  • float:数值浮点数。

Chat 配额管理

Ask Advisor 请求会根据查询复杂度消耗对话 token。 当 returnPropertyQuota 为 true 时,当前配额状态会在 propertyQuota 中返回:

建议的集成应用

properties.chat 方法可解锁跨团队和工具的多种集成架构:

企业聊天和协作机器人

将您的团队聊天工作区直接关联到 Google Analytics。

  • 会话串:将 sessionId 与聊天会话串 ID 一起存储,以便团队成员协作提出后续问题。
  • 复合信息卡呈现:将 table 响应块格式化为交互式卡片 widget。

自主 AI 智能体和 Model Context Protocol (MCP) 工具

为 LLM 编排器(例如 Gemini、LangChain 或 Claude)配备 GA 分析工具:

  • LLM 智能体可以调用 chat 方法,并传入自然语言意图,而无需强制 LLM 生成复杂的 runReport 查询。
  • 智能体接收高度符合事实的摘要和结构化表格,并将其合成为多渠道营销建议。

自动生成的高管简报和提醒

创建主动调查异常情况的预定服务:

  • 每日 cron 作业查询:“总结昨天的关键效果指标,并找出转化次数的任何异常下降。”
  • 如果发现异常,脚本会自动触发后续查询,以诊断根本原因,并将摘要发布到内部信息中心或 CRM 系统。

后续步骤