使用 Google Analytics 顾问查询和分析数据

Data APIchat 方法可让您以程序化方式访问 Analytics 顾问,后者是一款 AI 赋能的分析助理,可帮助您使用自然语言查询、分析和诊断 Google Analytics 数据。

虽然 Analytics 顾问可在 Google Analytics 用户界面中以交互方式使用,但 chat API 可让开发者、自主 AI 代理和内部工具通过 HTTP 以程序化方式与 Analytics 顾问互动。

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

概览

借助 chat 方法,您可以提出单轮临时数据问题,也可以进行多轮对话会话:

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

身份验证

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:单轮查询(带配额跟踪)

如需发起新对话,请构建包含 userQueryChatRequest。 将 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

场景:与上一时间段相比

在上次设备比较的基础上,您要求顾问将结果与上个周期进行比较。

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 响应

Google Analytics 顾问会使用会话内存将结果与上一个周期相关联。

{
  "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 数组中返回结构化组件:

Block Type 字段 说明
叙述性文字 blocks[].text 人类可读的说明和高级分析总结。
结构化表格 blocks[].table 包含 headers(名称和数据类型)和 rows(单元格值)的表格数据细分。

表格标题数据类型

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

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

聊天配额管理

分析顾问请求会根据查询的复杂程度消耗聊天令牌。当 returnPropertyQuotatrue 时,系统会在 propertyQuota 中返回当前配额状态:

  • tokensPerDay:每日令牌授予率上限和剩余余额。
  • tokensPerHour:每小时滑动窗口速率限制和剩余余额。

建议的集成应用

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

企业聊天和协作机器人

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

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

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

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

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

自动生成高管简报和提醒

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

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