How to Connect Google Analytics to LangChain
Building a custom chatbot on your own data is one of the most powerful applications of modern AI, and your Google Analytics data is a perfect place to start. By connecting Google Analytics to a framework like LangChain, you can create a conversational agent that answers questions about your website traffic, user behavior, and campaign performance in plain English. This post will walk you through the entire process, step-by-step, from setting up your credentials to asking your first question.
Why Connect Google Analytics to LangChain?
The standard Google Analytics interface is powerful, but it can be rigid. Finding specific insights often requires navigating through complex reports, applying filters, and knowing precisely which metrics and dimensions to combine. LangChain opens up a more dynamic and intuitive way to interact with your data.
Here’s what you can achieve:
- Natural Language Q&A: Stop hunting through menus. Simply ask questions like, "How many users did we get from organic search last month?" or "What were our top 10 landing pages by sessions?"
- Automated Reporting Bots: Create a simple script or a Slack bot that can pull daily or weekly metrics for your team on demand.
- Deeper Data Exploration: Use the conversational interface to follow your curiosity. An initial question like "Which country sends us the most traffic?" can naturally lead to "What's the user engagement rate for traffic from that country?" without building a new report from scratch.
- Custom Dashboards: While you won't be building a visual dashboard directly in your terminal, the agent can quickly provide the specific data points you need to build a custom report in another tool.
Prerequisites: What You'll Need Before You Start
This process is moderately technical and requires a few setup steps upfront. Getting these pieces in place first will make the rest of the tutorial much smoother. Here’s a checklist:
- A Google Analytics 4 Property: This process works with GA4, not the older Universal Analytics. You'll need the Property ID for your GA4 property (it looks something like
123456789). - Access to a Google Cloud Platform (GCP) Project: The Google Analytics APIs are managed through GCP. You'll need a project linked to the same Google account that has access to your GA4 property.
- The Google Analytics Data API Enabled: Inside your GCP project, you must enable the "Google Analytics Data API." You can find this by searching for it in the API & Services library.
- A Service Account with Credentials: A service account is like a robot user that your script can use to authenticate. You’ll need to create one, grant it "Viewer" access to your Google Analytics property, and download its credentials as a JSON key file. Keep this file secure!
- A Python Environment: You should have Python installed on your machine (version 3.8 or newer is recommended).
- An OpenAI API Key: LangChain agents need a Large Language Model (LLM) to power their decision-making. We'll use OpenAI's models in this example, so you'll need an API key from them.
Step-by-Step Guide to Connecting GA to LangChain
Once you've ticked off the prerequisites, you're ready to start coding. We’ll break this down into a few clear steps.
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 1: Set Up Your Python Environment and Install Libraries
First, create a new project folder and set up a virtual environment to keep your dependencies organized. Then, install the required Python libraries using pip.
pip install langchain langchain-openai google-analytics-data "pandas<,2.2.0"We're installing LangChain itself, the OpenAI integration, the official Google Analytics data library, and a specific version of Pandas to ensure compatibility. The quotes around "pandas<,2.2.0" help prevent shell command errors.
Step 2: Set Up Authentication
Your Python script needs to authenticate with both Google and OpenAI. The most secure way to do this is by setting environment variables in your terminal before running your script. This prevents you from hardcoding sensitive keys directly in your code.
First, tell your terminal where to find your Google Service Account key:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-key.json"Replace /path/to/your/service-account-key.json with the actual path to the JSON file you downloaded.
Next, set your OpenAI API key:
export OPENAI_API_KEY="your-openai-api-key"Replace your-openai-api-key with your actual key.
Step 3: Write the Python Script to Create the Agent
Now, let's create our Python script. Create a file named ga_agent.py and add the following code. We'll build it up block by block.
First, import the necessary modules and initialize your LLM. For this, we'll use OpenAI's ChatOpenAI model, specifically GPT-4, as it's better at reasoning and following instructions for API calls.
from langchain_openai import ChatOpenAI
from langchain_community.agent_toolkits import GoogleAnalyticsToolkit
# Initialize the LLM you want to use
# GPT-4 tends to work better for this as it's better at generating the correct API calls
llm = ChatOpenAI(temperature=0, model="gpt-4")Next, we will use the built-in GoogleAnalyticsToolkit from LangChain. This toolkit is a specialized wrapper that simplifies interactions with the Google Analytics Data API. It bundles pre-built "tools" that know how to fetch specific GA4 metrics and dimensions.
You’ll need to provide your GA4 Property ID when you initialize the toolkit.
# Go to your GA4 property -> Admin -> Property Details to get this
GA4_PROPERTY_ID = "YOUR_GA4_PROPERTY_ID"
# Instantiate the GA Toolkit
toolkit = GoogleAnalyticsToolkit(
llm=llm,
property_id=GA4_PROPERTY_ID
)Be sure to replace "YOUR_GA4_PROPERTY_ID" with your actual ID.
Finally, we'll create an agent. An agent in LangChain is a system that uses an LLM to decide which sequence of actions (or "tools") to take to answer a user's question. We'll use the toolkit's tools to create the agent executor.
from langchain.agents import create_conversational_retrieval_agent
# Get the tools from the toolkit
ga_tools = toolkit.get_tools()
# Create the agent by passing in the LLM and the tools
agent_executor = create_conversational_retrieval_agent(llm, ga_tools, verbose=True)Setting verbose=True is very helpful for debugging. It lets you see the agent's "chain-of-thought" in your terminal, showing you exactly what it's thinking, which tools it's choosing, and what API calls it's making to Google Analytics.
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 4: Ask Questions to Your Data
With the agent executor created, you can now start asking questions! Add this small loop to the end of your script to make it interactive.
while True:
try:
query = input("Ask a question about your Google Analytics data: ")
if query.lower() == 'exit':
break
# We pass the question to the agent executor
result = agent_executor.invoke({"input": query, "chat_history": []})
print(result["output"])
except Exception as e:
print(f"An error occurred: {e}")Now, save your file and run it from your terminal:
python ga_agent.pyYou can now ask questions in natural language. Try some of these:
- "How many active users did I have in the last 7 days?"
- "What were my top 5 pages by pageviews yesterday?"
- "List the sessions by country for the past 30 days."
- "What was the user engagement rate last week?"
The agent will interpret your question, select the appropriate Google Analytics tool, make a live API call to fetch the data, and then generate a human-readable answer for you.
Tips for Better Results
Working with GA4 data via an LLM agent is powerful, but it has its quirks. Here are a few tips to help you get more accurate answers.
- Be Specific: The more specific your question, the better. Instead of "How's traffic?", ask "What was the total number of sessions in the last 7 days?". Always include a date range.
- Know Your Metrics and Dimensions: Have a basic understanding of what GA4 metrics (like
sessions,activeUsers,conversions) and dimensions (likecountry,pagePath,sessionSourceMedium) are available. The agent is smart, but it can't query data that isn't there. If you ask for a metric from Universal Analytics that doesn't exist in GA4, it will likely fail. - Start Simple: Begin with simple, single-metric questions to confirm the connection is working before moving on to more complex queries that involve multiple dimensions or filters.
- Check the Verbose Output: If you get a strange answer, the
verbose=Trueoutput is your best friend. You can see if the LLM misinterpreted your question or if the Google Analytics API returned an error. A common issue is the agent trying to query dimensions and metrics that can't be combined in a single GA4 report.
Final Thoughts
You've just successfully built an AI agent that can query your live Google Analytics data using natural language. This powerful setup reduces manual work, unlocks faster data exploration for technical users, and opens the door for building custom internal tools, like reporting Slack bots or automated weekly email summaries.
While building your own agent is a great project, the process of managing Google Cloud permissions, service accounts, Python environments, and code can be time-consuming. We built Graphed to solve this very problem. You can connect your Google Analytics account in just a few clicks - no code or API keys required. You can then immediately start asking questions or describe the dashboard you want to see, and our AI data analyst builds real-time, interactive dashboards for you in seconds.
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.