Building production-ready AI agents that can maintain conversational context and internal state across multiple sessions is a complex but crucial task. This chapter lays the essential groundwork by guiding you through setting up a robust local development environment and configuring your Google Cloud Project. By the end, you’ll have a fully equipped workspace, ready to develop, test, and interact with your first basic agent. This foundational setup is critical for efficiently tackling the complexities of state persistence, reliable operation, and eventual deployment in subsequent chapters.
Project Overview
Our goal throughout this project is to build a long-running, stateful AI agent using Google’s Agent Development Kit (ADK). This agent will be capable of:
- Persisting State: Saving its internal memory and conversational context to an external durable store.
- Pause and Resume: Stopping execution and later resuming precisely where it left off, without losing information.
- Error Recovery: Handling interruptions gracefully and recovering its state to continue operations.
- Production Deployment: Being containerized and deployed to Google Cloud for scalability and reliability.
This first chapter focuses on the initial setup, ensuring all tools and cloud resources are correctly configured before we write any agent logic.
Tech Stack
This project leverages a modern, cloud-native tech stack designed for scalability and maintainability:
- Python: The primary programming language for agent logic and Google Cloud client libraries.
- Google ADK (Agent Development Kit): For this project, “Google ADK” refers to a collection of Google Cloud’s Python client libraries, specifically
google-cloud-aiplatform, which provides interfaces to Google’s Vertex AI services (e.g., large language models). There isn’t a singlepip install google-adkpackage; instead, we assemble the necessary components. - Google Cloud Platform (GCP): The cloud infrastructure for hosting our agent, managing resources, and providing backend services. We’ll specifically use:
- Vertex AI: For accessing powerful large language models.
- Cloud Run: For deploying our containerized agent as a scalable, serverless service.
- Firestore (or Cloud SQL/Redis): As a durable, external state store for agent memory and context.
- Google Cloud SDK (gcloud CLI): For interacting with GCP resources from the command line.
Milestones for This Chapter
This chapter is structured around setting up your development environment. By following these steps, you’ll establish a solid base:
- Python Environment Preparation: Install Python and create an isolated virtual environment.
- Google Cloud Project Configuration: Create a GCP project, enable required APIs, and set up a secure service account.
- Google Cloud SDK Installation: Install the
gcloudcommand-line interface. - Credential and Project Setup: Authenticate
gcloudand configure environment variables for Python applications. - ADK Core Library Installation: Install the primary Python client libraries for Google Cloud AI services.
- Initial Project Structure: Create a basic local project directory and pin dependencies.
- Verification: Confirm that all components are correctly installed and communicating with Google Cloud.
Architecture: Development Environment Flow
The setup process involves configuring both your local machine and your Google Cloud Project to work in harmony.
This diagram illustrates the dependencies: your local Python environment (A) needs the GCP SDK (B) to interact with your cloud project (C). Credentials (F) are generated in the cloud and then referenced locally via environment variables (D) to allow your ADK libraries (E) to authenticate and communicate with Vertex AI.
Step-by-Step Implementation
We’ll proceed methodically, using Python’s venv for dependency isolation and gcloud CLI for Google Cloud interactions. We prioritize service account authentication, which is a best practice for production environments.
1. Install Python and Create a Virtual Environment
Python will host our agent’s logic. A virtual environment is crucial for managing project-specific dependencies without conflicts.
Install Python 3.13.x (or later stable): As of 2026-05-23, Python 3.13.x is anticipated to be a stable and recommended version. If you don’t have it, download it from the official Python website or use a version manager like
pyenvfor flexibility.# Verify your Python version python3 --version # Expected output: Python 3.13.x (e.g., Python 3.13.0, or similar recent stable version)🧠 Important:Always use the latest stable version recommended for your project. If Python 3.13.x is not yet stable, use the latest3.12.xrelease.Create Project Directory and Virtual Environment: A virtual environment (
venv) isolates your project’s Python packages from your system-wide Python installation.# Create the main project directory mkdir adk-long-running-agent cd adk-long-running-agent # Create a virtual environment named 'venv' python3 -m venv venv # Activate the virtual environment # On macOS/Linux: source venv/bin/activate # On Windows (Cmd): # venv\Scripts\activate.bat # On Windows (PowerShell): # venv\Scripts\Activate.ps1Your terminal prompt should now show
(venv), indicating the virtual environment is active.
2. Set Up Your Google Cloud Project
Your AI agent will leverage Google Cloud services. This step ensures you have a dedicated project and secure credentials.
Create a Google Cloud Project: Navigate to the Google Cloud Console and create a new project. Choose a descriptive name, such as
adk-long-running-agent-project. Note down yourPROJECT_ID(e.g.,my-project-12345) as you’ll need it frequently.Enable Required APIs: For agents leveraging large language models and other AI services, you’ll need to enable several APIs. The most crucial one for modern LLM-based agents is Vertex AI.
In the Google Cloud Console, go to APIs & Services > Enabled APIs & Services and ensure the following APIs are enabled:
Vertex AI APICloud Resource Manager API(usually enabled by default)Cloud Run API(for deploying containerized agents, recommended for this project)Firestore API(for state persistence in later chapters, or chooseCloud SQL APIorMemorystore for Redis APIbased on your preference).
Alternatively, you can enable them via the
gcloudCLI after installing it:# Replace YOUR_PROJECT_ID with your actual project ID gcloud config set project YOUR_PROJECT_ID gcloud services enable \ aiplatform.googleapis.com \ cloudresourcemanager.googleapis.com \ run.googleapis.com \ firestore.googleapis.com \ --project YOUR_PROJECT_ID📌 Key Idea:Enabling only necessary APIs adheres to the principle of least privilege, enhancing security.Create a Service Account and Download Credentials: Your agent needs credentials to authenticate with Google Cloud services. Using a service account is the most secure and recommended approach for server-to-server interaction.
- In the Google Cloud Console, navigate to IAM & Admin > Service Accounts.
- Click + Create Service Account.
- Give it a descriptive name (e.g.,
adk-agent-svc). - Grant it the following roles (start with the minimum necessary and add more if needed):
Vertex AI UserService Account User(allows this service account to impersonate others for specific tasks)Cloud Run Invoker(if deploying to Cloud Run)Cloud Datastore UserorCloud Firestore User(depending on your chosen database for state persistence).
- Click Done.
- Click on the newly created service account, then go to the Keys tab.
- Click Add Key > Create new key, choose
JSON, and click Create. - A JSON key file will be downloaded. Store this file securely and never commit it to version control. For local development, we’ll place it in the project root. For production, Google Secret Manager is the appropriate solution. Rename the downloaded file to
key.jsonand place it in youradk-long-running-agentdirectory.
3. Install Google Cloud SDK
The Google Cloud SDK provides the gcloud command-line tool, which is essential for managing GCP resources and authenticating.
Install
gcloud CLI: Follow the official installation instructions for your operating system from the Google Cloud SDK documentation.# Example for Debian/Ubuntu (always check official docs for the latest commands) # sudo apt-get update # sudo apt-get install apt-transport-https ca-certificates gnupg # echo "deb [signed-by=/usr/share/keyrings/cloud.google.com.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list # curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key --keyring /usr/share/keyrings/cloud.google.com.gpg add - # sudo apt-get update && sudo apt-get install google-cloud-sdk⚡ Quick Note:For other operating systems, the installation steps will differ. Always refer to the official documentation.Authenticate
gcloudCLI with Service Account: For consistency with our service account-driven approach, we’ll authenticate thegcloudCLI using thekey.jsonfile. This ensures that commands executed viagclouduse the same permissions as your agent.# Ensure you are in the adk-long-running-agent directory where key.json is located gcloud auth activate-service-account --key-file=./key.json # Set your project ID explicitly for gcloud commands # Replace YOUR_PROJECT_ID with your actual project ID gcloud config set project YOUR_PROJECT_IDThis approach uses the service account for
gcloudoperations, aligning with how your agent will authenticate.Set
GOOGLE_APPLICATION_CREDENTIALSandGCP_PROJECT_IDEnvironment Variables: Python applications using Google Cloud client libraries automatically pick up credentials from theGOOGLE_APPLICATION_CREDENTIALSenvironment variable. SettingGCP_PROJECT_IDsimplifies project referencing.Add the following lines to your virtual environment’s activation script to ensure these variables are set whenever your
venvis active. This provides a consistent environment.- On macOS/Linux (
venv/bin/activate):# Add to the end of venv/bin/activate export GOOGLE_APPLICATION_CREDENTIALS="$(pwd)/key.json" export GCP_PROJECT_ID="$(gcloud config get-value project)" - On Windows (Cmd -
venv\Scripts\activate.bat)::: Add to the end of venv\Scripts\activate.bat set GOOGLE_APPLICATION_CREDENTIALS=%cd%\key.json for /f "delims=" %%i in ('gcloud config get-value project') do set GCP_PROJECT_ID=%%i - On Windows (PowerShell -
venv\Scripts\Activate.ps1):# Add to the end of venv\Scripts\Activate.ps1 $env:GOOGLE_APPLICATION_CREDENTIALS = (Get-Item 'key.json').FullName $env:GCP_PROJECT_ID = (gcloud config get-value project)
After modifying, deactivate and reactivate your virtual environment for these changes to take effect:
deactivatethensource venv/bin/activate.- On macOS/Linux (
4. Install Google ADK Core Libraries
The primary Python library for interacting with Vertex AI’s LLMs and other AI services is google-cloud-aiplatform.
# Ensure your virtual environment is active
# (venv)
# Install the core Google Cloud AI Platform library
# As of 2026-05-23, we assume version 2.0.0 is stable. Always check PyPI for the absolute latest.
pip install google-cloud-aiplatform==2.0.0 # Placeholder: Check PyPI for latest stable release
# You might also need specific client libraries later, such as:
# pip install google-cloud-firestore # For Firestore database (if chosen)
# pip install google-cloud-storage # For Google Cloud Storage (if used)google-cloud-aiplatform version 2.0.0 is an assumed stable version for 2026-05-23, given typical major release cycles for robust libraries. Always check PyPI for google-cloud-aiplatform for the most current stable release at your installation time. Pinning a specific version (==X.Y.Z) is best practice for production and reproducibility.
5. Create a Basic Project Structure and Pin Dependencies
Let’s create a minimal file structure and capture our installed dependencies.
Create a basic Python file:
# Ensure you are in the adk-long-running-agent directory # (venv) cd adk-long-running-agent # Create a basic Python file to test the ADK installation touch main.pyAdd verification code to
main.py: Openmain.pyand add the following code. This script verifies thegoogle-cloud-aiplatformlibrary import and attempts to initialize a Vertex AI client using your configured credentials and project ID.main.pyimport os from google.cloud import aiplatform print("Google Cloud AI Platform library imported successfully!") # Verify environment variables gcp_project_id = os.environ.get("GCP_PROJECT_ID") gcp_credentials_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") print(f"GCP_PROJECT_ID: {gcp_project_id if gcp_project_id else 'Not Set'}") print(f"GOOGLE_APPLICATION_CREDENTIALS: {gcp_credentials_path if gcp_credentials_path else 'Not Set'}") # Initialize Vertex AI client # We use 'us-central1' as a common region for Vertex AI. # Choose a region geographically relevant to your deployment for lower latency and data residency. vertex_ai_location = "us-central1" if gcp_project_id: try: aiplatform.init(project=gcp_project_id, location=vertex_ai_location) print(f"Vertex AI client initialized for project '{gcp_project_id}' in region '{vertex_ai_location}'.") except Exception as e: print(f"Error initializing Vertex AI client: {e}") print("Ensure GOOGLE_APPLICATION_CREDENTIALS is set correctly and the service account has 'Vertex AI User' role.") else: print("GCP_PROJECT_ID environment variable is not set. Cannot initialize Vertex AI client.") print("Environment setup verification complete.")Generate
requirements.txt: It’s crucial to pin your project’s dependencies for reproducibility. After installinggoogle-cloud-aiplatform, usepip freezeto capture all installed packages and their exact versions.# Ensure your virtual environment is active # (venv) pip freeze > requirements.txtReview the
requirements.txtfile. For production, consider using a tool like Poetry or Pip-tools for more controlled dependency management from apyproject.tomlorrequirements.infile, which can generate a fully pinnedrequirements.txt. For now,pip freezeis sufficient.
Testing & Verification
Let’s confirm everything is working as expected.
Verify Python Environment and Libraries: Run the
main.pyscript within your activated virtual environment.# Ensure (venv) is active python main.pyExpected Output:
Google Cloud AI Platform library imported successfully! GCP_PROJECT_ID: your-project-id GOOGLE_APPLICATION_CREDENTIALS: /path/to/your/adk-long-running-agent/key.json Vertex AI client initialized for project 'your-project-id' in region 'us-central1'. Environment setup verification complete.If you see the success messages, especially for
Vertex AI client initialized, your Python environment, ADK libraries, and Google Cloud credentials are correctly configured.Verify
gcloudCLI Authentication: Confirm that yourgcloudCLI can access your project using the service account.gcloud auth list gcloud config list projectThe
gcloud auth listcommand should show your service account as active, andgcloud config list projectshould display yourPROJECT_PROJECT_ID.
Production Considerations
Even at this early stage, thinking about production best practices is vital for building robust systems.
- Secure Credential Management: The
key.jsonfile is suitable for local development but highly insecure for production deployments. In a real Google Cloud deployment (e.g., Cloud Run, GKE, Cloud Functions), Google Cloud services leverage built-in service accounts automatically, eliminating the need forkey.jsonfiles. For any other sensitive information (e.g., external API keys), always use Google Secret Manager to securely store and retrieve them. - Dependency Management: Always use a
requirements.txtfile (orpyproject.tomlwith tools like Poetry or Rye) to precisely define your project’s dependencies. This ensures consistent installations across development, testing, and production environments, preventing “it works on my machine” issues. - Version Pinning: Pinning exact package versions (e.g.,
google-cloud-aiplatform==2.0.0) prevents unexpected breaking changes from newer library releases, enhancing stability and reproducibility. - Regionality: Choosing the right Google Cloud region (e.g.,
us-central1,europe-west1) for your Vertex AI services and other resources is important for latency, cost, and data residency requirements. This decision should be made early in the project lifecycle.
Common Issues & Solutions
ModuleNotFoundError: No module named 'google.cloud.aiplatform':- Cause: The virtual environment is not active, or the library wasn’t installed into the active
venv. - Solution: Ensure you run
source venv/bin/activate(or Windows equivalent) and thenpip install google-cloud-aiplatformafter activating thevenv.
- Cause: The virtual environment is not active, or the library wasn’t installed into the active
google.auth.exceptions.DefaultCredentialsErroror similar authentication errors:- Cause: The
GOOGLE_APPLICATION_CREDENTIALSenvironment variable is not set correctly, thekey.jsonfile path is wrong, or the service account lacks necessary IAM permissions (e.g.,Vertex AI User). - Solution: Double-check the
export GOOGLE_APPLICATION_CREDENTIALScommand in yourvenvactivation script and ensure thekey.jsonpath is correct. In the Google Cloud Console, verify your service account has all required roles.
- Cause: The
gcloudcommands fail or return permission denied:- Cause:
gcloudis not authenticated with the correct service account, or the authenticated identity doesn’t have permissions for the selected project. - Solution: Re-run
gcloud auth activate-service-account --key-file=./key.json. Check IAM roles for the authenticated service account in the Google Cloud Console for the specific project.
- Cause:
GCP_PROJECT_IDnot set inmain.pyoutput:- Cause: The
GCP_PROJECT_IDenvironment variable was not set, or thevenvactivation script was not updated/re-sourced. - Solution: Ensure the
export GCP_PROJECT_ID=...line is correctly added to yourvenvactivation script and that you’ve deactivated and reactivated yourvenvafter making the change.
- Cause: The
Summary & Next Step
You’ve successfully established a robust development environment for building long-running AI agents with Google ADK. You now have:
- A dedicated Python virtual environment for isolated dependencies.
- A Google Cloud project with necessary APIs enabled and a secure service account.
- The
gcloudCLI installed and authenticated using your service account. - The core
google-cloud-aiplatformlibrary installed. - Environment variables (
GOOGLE_APPLICATION_CREDENTIALS,GCP_PROJECT_ID) configured for seamless interaction with Google Cloud services. - A basic project structure with a
main.pyfor verification and arequirements.txtfor dependency management.
This robust foundation is ready for the next step. In Chapter 2, “Building Your First Stateless ADK Agent,” we’ll implement a simple agent that can process requests and generate responses using Vertex AI, laying the groundwork for introducing robust state management.
References
- Python Downloads
- Google Cloud SDK Installation Guide
- PyPI: google-cloud-aiplatform
- Google Cloud IAM Documentation
- Google Cloud Secret Manager Documentation
This page is AI-assisted and reviewed. It references official documentation and recognized resources where relevant.