How to Connect Google Analytics to AutoGen AI
Automating your Google Analytics reporting is a game-changer, letting you get insights without the endless cycle of manually pulling data. By connecting Google Analytics to an AI framework like Microsoft's AutoGen, you can create a team of AI agents that fetch, analyze, and report on your website's performance using simple conversational prompts. This guide will walk you through the entire process, step by step.
What is AutoGen and Why Connect it to Google Analytics?
AutoGen is a powerful open-source framework from Microsoft that lets developers build applications with multiple AI agents proficient at different tasks. These agents can "talk" to each other to collaborate and solve complex problems. Instead of relying on a single large language model (LLM), you can create specialized agents - one that acts as a project manager, another as a coder, another as a QA tester, and so on.
Connecting this framework to Google Analytics opens up incredible possibilities. Instead of logging into GA4, navigating menus, and setting up custom reports just to answer a simple question, you can have your AI agents do the work. Imagine asking in plain English:
- "What were our top 10 landing pages by sessions last week?"
- "Show me the conversion rate for users from the United States versus Canada over the last 30 days."
- "Generate a report on device usage (desktop vs. mobile) for the past quarter."
Your team of AI agents can understand the request, write the necessary code to call the Google Analytics API, fetch the data, process it, and deliver the answer. It’s like having a junior data analyst available 24/7 who works in seconds.
Prerequisites: Gearing Up for the Project
Before diving into the code, you’ll need a few things set up. Getting these ready now will save you time and headaches later.
- A Google Analytics 4 Property: You must have an active GA4 property with some data in it. You'll also need admin-level permissions to manage access.
- Google Cloud Platform (GCP) Account: The Google Analytics Data API is managed through GCP, so you'll need an account. If you don't have one, you can sign up for a free trial.
- Python Installed: This tutorial uses Python. You should have Python 3.8 or newer installed on your computer.
- An LLM API Key: AutoGen orchestrates Large Language Models, but it doesn't provide them. You'll need an API key from a provider like OpenAI, Azure OpenAI, or another model supported by the LiteLLM library. We will use OpenAI for this example.
- Basic Command Line Familiarity: You'll need to run a few basic commands in your terminal or command prompt to install packages and run the Python script.
Step-by-Step: Linking the Google Analytics API to Your Project
The first major task is to securely grant your Python script permission to access your Google Analytics data. This involves creating a “service account” in Google Cloud, which is a special type of account used by an application, not a person.
Step 1: Enable the Google Analytics Data API
- Navigate to the Google Cloud Console.
- Select a project from the top dropdown menu, or create a new one if you don't have one already.
- In the search bar at the top, type "Google Analytics Data API" and select that product from the results.
- Click the blue "Enable" button. If it's already enabled, you're all set.
Step 2: Create a Service Account and Get Credentials
- In the Google Cloud Console, use the search bar to find and navigate to "Service Accounts."
- Click "+ Create Service Account" near the top of the page.
- Give your service account a name (e.g., "autogen-ga-reporter") and a description. The Service account ID will auto-populate. Click "Create and Continue."
- You can skip granting a role on the next page for now. Just click "Continue."
- You can also skip granting user access. Click "Done."
- You will now see your new service account in the list. Click on the three dots under "Actions" and select "Manage keys."
- Click "Add Key" > "Create new key." Choose JSON as the key type and click "Create."
A JSON file containing your credentials will be downloaded to your computer. Treat this file like a password. Anyone with this file could potentially access your data. Move it to a secure location within your project folder and give it a memorable name, like ga_credentials.json.
Step 3: Grant the Service Account Access in Google Analytics
- Open the JSON file you just downloaded. Find the value associated with the
client_emailkey. It will look like an email address (e.g., "autogen-ga-reporter@your-project-id.iam.gserviceaccount.com"). Copy this email address. - Go to your Google Analytics account. Click on "Admin" in the bottom-left corner.
- Make sure you have the correct Account and Property selected. Go to the "Property" column and click on "Property Access Management."
- Click the blue "+" icon in the top right corner and select "Add users."
- Paste the service account's email address into the "Email addresses" field.
- Under "Permissions," assign it the role of "Viewer." Your script only needs to read data, so viewer access is sufficient and more secure.
- Click "Add." Your service account now has permission to access your GA4 property data.
Free PDF · the crash course
AI Agents for Marketing Crash Course
Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.
Building Your AutoGen Application
Now for the fun part: setting up the Python environment and writing the code to power your AI agents.
Step 4: Prepare the Python Environment
Let's create an isolated environment for this project to keep all the required packages neatly organized.
- Open your terminal or command prompt.
- Create a new directory for your project and navigate into it:
mkdir autogen-ga-project cd autogen-ga-project
- Create a Python virtual environment:
python -m venv venv
- Activate the virtual environment:
- On macOS/Linux:
source venv/bin/activate
- On Windows:
.\venv\Scripts\activate
- With your environment active, install the necessary Python libraries:
pip install pyautogen pandas google-analytics-data
pyautogenis the core framework for building agents.google-analytics-datais the official Google client library for the GA4 Data API.pandasis a crucial library for data manipulation, which will make the API response easier to work with.
Step 5: Define the Custom Tool For Your Agents
Out of the box, AutoGen's agents don't know how to talk to Google Analytics. We need to teach them by writing a custom Python function (a "tool") that they can learn to use.
Create a file named app.py in your project directory and add the following code. This function takes a request, formats it for the Google Analytics API, makes the call, and returns the data as a clean table (a pandas DataFrame).
import os
import autogen
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
DateRange,
Dimension,
Metric,
RunReportRequest,
)
import pandas as pd
# IMPORTANT: Set these environment variables before running!
# Set the path to your service account credentials file
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "ga_credentials.json"
# Your GA4 Property ID
GA_PROPERTY_ID = "YOUR_PROPERTY_ID" # <-- REPLACE WITH YOUR ACTUAL PROPERTY ID
def query_google_analytics(metrics, dimensions, start_date="7daysAgo", end_date="today"):
"""
Queries the Google Analytics Data API v1 beta.
Returns a pandas DataFrame with the results.
"""
try:
client = BetaAnalyticsDataClient()
request = RunReportRequest(
property=f"properties/{GA_PROPERTY_ID}",
dimensions=[Dimension(name=dim) for dim in dimensions],
metrics=[Metric(name=m) for m in metrics],
date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
)
response = client.run_report(request)
# Process the response into a readable format
output = []
header_row = [header.name for header in response.dimension_headers] + [
header.name for header in response.metric_headers
]
for row in response.rows:
row_data = [value.value for value in row.dimension_values] + [
value.value for value in row.metric_values
]
output.append(row_data)
df = pd.DataFrame(output, columns=header_row)
return df
except Exception as e:
return f"An error occurred: {e}"Before moving on, remember to replace YOUR_PROPERTY_ID with your actual GA4 property ID. You can find this in your GA4 admin settings under Property Details.
Step 6: Configure and Create the AI Agents
Now we define our team of AI agents. For this task, we will create two:
- AssistantAgent: An LLM-based agent that acts as the team lead. It analyzes the user's request and writes the Python code needed to fulfill it, using the function we just created.
- UserProxyAgent: This agent acts on the user's behalf. Its main job is to execute the code generated by the Assistant agent. Crucially, we will tell this agent that it has access to our
query_google_analyticstool.
In your app.py file, add the following code below the function you just wrote:
OPENAI_API_KEY = "YOUR_OPENAI_API_KEY" # <-- REPLACE WITH YOUR API KEY
# Configure the LLM for AutoGen
config_list = [{
'model': 'gpt-4',
'api_key': OPENAI_API_KEY
}]
llm_config = {
"functions": [
{
"name": "query_google_analytics",
"description": "Fetch data from a Google Analytics 4 property. Use this to get information about website traffic, user engagement, and conversions.",
"parameters": {
"type": "object",
"properties": {
"metrics": {
"type": "array",
"items": {"type": "string"},
"description": "A list of metrics to retrieve, e.g., ['sessions', 'totalUsers'].",
},
"dimensions": {
"type": "array",
"items": {"type": "string"},
"description": "A list of dimensions to group the data by, e.g., ['date', 'country'].",
},
"start_date": {
"type": "string",
"description": "The start date for the query in 'YYYY-MM-DD' or 'XdaysAgo' format. Defaults to '7daysAgo.'",
"default": "7daysAgo"
},
"end_date": {
"type": "string",
"description": "The end date for the query in 'YYYY-MM-DD' or 'today' format. Defaults to 'today.'",
"default": "today"
}
},
"required": ["metrics", "dimensions"],
},
}
],
"config_list": config_list,
"request_timeout": 120,
}
# Create the agents
assistant = autogen.AssistantAgent(
name="GA_Analytics_Assistant",
llm_config=llm_config,
system_message="You are a Google Analytics expert. Your goal is to write python code snippets (using the provided `query_google_analytics` function) to answer user questions about their website data."
)
user_proxy = autogen.UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER", # Use TERMINATE to require human approval of code
max_consecutive_auto_reply=10,
is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
code_execution_config={"work_dir": "coding"},
function_map={"query_google_analytics": query_google_analytics}
)Be sure to replace YOUR_OPENAI_API_KEY with your actual key.
The "functions" section within llm_config is critical. It describes our custom tool to the Assistant Agent in a format it can understand, turning our Python function into an API call the LLM knows how to make.
Free PDF · the crash course
AI Agents for Marketing Crash Course
Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.
Step 7: Putting It All Together and Running Your First Query
Finally, we initiate the conversation between the agents with a prompt from the user.
Add this final part to your app.py script:
# The user's query
user_query = "What were my top 5 landing pages by sessions for the last 14 days?"
# Initiate the conversation
user_proxy.initiate_chat(
assistant,
message=user_query
)With your script complete, you can now run it from your terminal (making sure your virtual environment is still active):
python app.py
You’ll see the agents start to "chat" in your terminal. The assistant will propose a plan and write code using the query_google_analytics function. The user proxy will execute that code, get the data from the Google Analytics API, and print the resulting pandas DataFrame. It’s an entirely automated workflow!
Final Thoughts
By connecting Google Analytics to a multi-agent framework like AutoGen, you transform a static data source into a dynamic, interactive partner for analysis. You can build on this foundation to have agents not only fetch data but also visualize it, send summaries to Slack, or even identify performance anomalies—automating the manual drudgery of weekly reporting.
This tutorial shows the powerful potential of custom AI, but it requires a good deal of setup, coding knowledge, and ongoing maintenance. For teams that want these conversational insights without the technical overhead, we built Graphed. We provide a turnkey solution that connects securely to your Google Analytics, Google Ads, Shopify, and sales platforms in minutes. Instead of building agents and managing API keys, your whole team can just ask questions in plain English—like "Which campaigns drove the most revenue this month?"—and instantly get real-time dashboards and answers, no coding required.
Related Articles
How to Create Facebook Ads API for Claude Code
Create a Meta Marketing API access token that never expires, using a system user, so Claude Code can pull Facebook ad reports and manage campaigns.
ClickHouse vs Postgres: When to Switch to Columnar
Comparing ClickHouse vs PostgreSQL means matching storage architecture to workload. Row storage wins for transactions. Columnar wins for scan-heavy analytics.
Google Ads for Orthodontists: Get More Booked Consults
Most orthodontic Google Ads campaigns waste money on low-intent searches. The problem is structure, not the platform.