How to Connect Google Analytics to LangGraph
Building a custom AI agent that can chat with your Google Analytics data sounds complex, but it's more accessible than you think. Using a powerful framework like LangGraph, you can create a conversational tool that answers plain-English questions about your website traffic. This article walks you through the entire process, from setting up your Google Cloud project to building and running a functional LangGraph agent that pulls live data from your GA4 property.
What is LangGraph and Why Connect it to Google Analytics?
LangGraph is a library that extends the popular LangChain framework, specifically designed for building stateful, multi-agent LLM applications. While LangChain is great for chaining components together, LangGraph excels at creating "agentic" systems - AI that can reason, use tools, and operate in cycles until a task is complete. Think of it as a flowchart for your AI, allowing for more complex and robust logic.
Connecting this framework to Google Analytics unlocks a powerful new way to interact with your data. Instead of navigating the GA4 interface, you can simply ask questions like:
- "How many new users did we get last week?"
- "What were our top 5 traffic sources in the last 30 days?"
- "Compare user engagement from the US vs. Canada this quarter."
The goal is to build an "analyst bot" that fetches the relevant data, processes it, and gives you a clear answer, saving you the time and effort of manual reporting.
Prerequisites: Getting Your Credentials in Order
Before writing any code, you need to gather a few essential items. This setup is the most tedious part of the process, but getting it right ensures everything else runs smoothly.
1. A Google Cloud Platform (GCP) Project
Your Google Analytics data is accessed through a GCP project. If you don't have one, you'll need to create one.
- Go to the Google Cloud Console.
- Create a new project (e.g., "GA4-LangGraph-Agent").
- Once your project is created, make sure it's selected as your active project.
2. Enable the Google Analytics Data API
APIs aren't enabled by default. You need to tell Google you intend to use this specific one.
- In the Cloud Console search bar, type "Google Analytics Data API" and select it.
- Click the "Enable" button. This might take a minute or two.
3. Create a Service Account and Get Credentials
A service account is like a robot user that your script will use to log in and access data on your behalf. It's more secure than using your personal login credentials in a script.
- In the Cloud Console, navigate to "IAM & Admin" > "Service Accounts."
- Click "Create Service Account." Give it a name like "ga4-api-reader."
- Grant it the "Viewer" role, which provides read-only access to your GA property. This is a crucial security step - never give an automated script more permission than it needs.
- After creating the account, go to its "Keys" tab, click "Add Key," and choose "Create new key." Select "JSON" and a
credentials.jsonfile will be downloaded to your computer. Keep this file safe and private, it contains a password!
4. Add the Service Account to Your Google Analytics Property
Just because you created a user doesn't mean it can access your specific analytics data yet. You have to invite it.
- Open your Google Analytics 4 property.
- Go to "Admin" > "Property Access Management."
- Click the "+" icon to add a new user.
- Paste the long email address of the service account you just created (it looks something like
ga4-api-reader@your-project-id.iam.gserviceaccount.com). - Assign it the "Viewer" role and save.
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.
5. Your GA4 Property ID
Find and copy your GA4 property ID. You can find this in your Google Analytics dashboard under "Admin" > "Property Settings." It's a string of numbers.
6. OpenAI API Key
Your LangGraph agent needs an LLM to power its "brain." We'll use OpenAI for this example, so you'll need an API key from their developer platform.
Step-by-Step: Building Your GA4 Agent with LangGraph
With the setup complete, it's time to write some Python code. This guide assumes you have a basic understanding of Python.
Step 1: Set Up Your Python Environment
It's always best practice to work in a dedicated virtual environment to avoid conflicting package versions.
Open your terminal and run:
# Create a virtual environment
python -m venv ga4-agent-env
# Activate it (on Mac/Linux)
source ga4-agent-env/bin/activate
# Or on Windows
ga4-agent-env\Scripts\activate.batNext, install all the necessary libraries:
pip install langgraph langchain langchain-openai google-analytics-dataYou'll also need to set your API keys as environment variables. Add these lines to your script (or set them directly in your terminal), replacing the placeholders.
import os
# Your OpenAI API key
os.environ["OPENAI_API_KEY"] = "sk-..."
# Path to your downloaded service account JSON file
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/your/credentials.json"
# Your GA4 Property ID
GA4_PROPERTY_ID = "YOUR_PROPERTY_ID"Step 2: Create a Google Analytics "Tool"
In LangChain terminology, a "tool" is a function the AI agent can decide to use to get information about the outside world. We'll create a function that queries the GA4 Data API.
from langchain.tools import tool
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import RunReportRequest, Dimension, Metric, DateRange
@tool
def query_google_analytics(dimensions: list, metrics: list, start_date: str, end_date: str) -> str:
"""
Queries the Google Analytics Data API v1beta to retrieve a report.
Returns the report response as a string.
"""
try:
client = BetaAnalyticsDataClient()
request = RunReportRequest(
property=f"properties/{GA4_PROPERTY_ID}",
dimensions=[Dimension(name=dim) for dim in dimensions],
metrics=[Metric(name=mtc) for mtc in metrics],
date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
)
response = client.run_report(request)
return str(response) # Return the response as a string for the LLM to process
except Exception as e:
return f"An error occurred: {e}"Example Usage (for testing):
# print(query_google_analytics.invoke({
# "dimensions": ["country"],
# "metrics": ["activeUsers"],
# "start_date": "2024-01-01",
# "end_date": "2024-01-31"
# }))This function takes the necessary GA4 report parameters as an input, uses the official Google client library to make the API call, and returns the data. It also includes error handling in case the API request fails.
Step 3: Define the Agent's State and Nodes
LangGraph works by passing a "state" object between different functions called "nodes." Our agent's state will simply be the list of messages in our conversation so far.
from typing import TypedDict, Annotated, Sequence
import operator
from langchain_core.messages import BaseMessage
class AgentState(TypedDict):
messages: Annotated[Sequence[BaseMessage], operator.add]Now, let's create our primary node. This function will take the current conversation state, call the LLM, and decide if it needs to use our GA4 tool.
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
# Initialize the LLM and bind our tool to it
llm = ChatOpenAI(model="gpt-4-turbo-preview")
tools = [query_google_analytics]
llm_with_tools = llm.bind_tools(tools)
def agent_node(state):
"""
The primary node that calls the LLM. It decides whether to call a tool or respond directly.
"""
# The LLM chooses whether to call a tool or not based on the conversation history
response_with_tool_call = llm_with_tools.invoke(state["messages"])
return {"messages": [response_with_tool_call]}Step 4: Create the Tool Node and Build the Graph
Next, we need a node to actually execute the tool if the LLM decides to use it. LangGraph provides a handy ToolNode for this.
from langgraph.graph import StateGraph, END
from langgraph.prebuilt import ToolNode
# This node executes the chosen tool
tool_node = ToolNode(tools=[query_google_analytics])
# This function determines the next step. If the AI calls a tool, we run the tool_node. Otherwise, the conversation is over.
def should_continue(state):
last_message = state["messages"][-1]
if "tool_calls" in last_message.additional_kwargs:
return "call_tool"
return END
# Now, we define the graph
workflow = StateGraph(AgentState)
# Add the nodes
workflow.add_node("agent", agent_node)
workflow.add_node("call_tool", tool_node)
# Define the edges that connect the nodes
workflow.set_entry_point("agent")
workflow.add_conditional_edges(
"agent",
should_continue,
{
"call_tool": "call_tool",
END: END
}
)
workflow.add_edge("call_tool", "agent")
# Compile the graph into a runnable app
app = workflow.compile()This code constructs our flowchart: The flow starts at the agent node. After the agent replies, the should_continue function checks if a tool was called. If yes, it routes to tool_node to execute the query, otherwise, it ends. After the tool runs, it goes back to the agent node so the LLM can interpret the results and formulate a final answer.
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 5: Chat with Your Google Analytics Data
Your agent is ready to go! You can now ask it questions by invoking the compiled app.
# Let's ask a question
human_input = "how many active users did we have yesterday and the day before?"
conversation_chain = Mappable.prepare().map()({
"messages": [
HumanMessage(
content=human_input
)
]
})
for chunk in app.stream(conversation_chain):
# Print the full state at each step
print("---")
print(chunk)When you run this, you can see the agent's "thinking" process in your terminal. It will first call the query_google_analytics tool with the correct parameters (metrics=['activeUsers'], start_date='yesterday', etc.). The tool will return raw data from the API. The agent then gets this data, interprets it, and gives you a clean, conversational answer.
Final Thoughts
By connecting Google Analytics to a custom LangGraph agent, you've moved beyond static dashboards and learned to have a direct conversation with your data. This is a powerful technique for automating custom reports, embedding analytics into other applications, or simply getting faster answers to your most pressing questions without leaving your workflow.
While building a custom AI agent like this offers ultimate flexibility, it requires a good deal of setup, coding, and maintenance. At Graphed, we created a way to get these same conversational insights without writing a single line of code. We provide one-click integrations with tools like Google Analytics, Shopify, and Salesforce, allowing you to ask questions and build real-time dashboards using simple, natural language. It’s for anyone who needs immediate insights from their data but doesn’t have the time or technical resources to build a custom solution from scratch.
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.