---
# Starter Pack Guidance
Guide for AI agents working with **generated projects** (projects created by Agent Starter Pack).

> **Scope**: This document is for developing, testing, and deploying **generated agent projects**. For contributing to the **Agent Starter Pack repository itself** (the template generator), see [GEMINI.md](./GEMINI.md).
---

### Section 1: Project Overview

*   **Project Name:** Agent Starter Pack
*   **Purpose:** Accelerate development of production-ready GenAI Agents on Google Cloud.
*   **Tagline:** Production-Ready Agents on Google Cloud, faster.

**The "Production Gap":**
While prototyping GenAI agents is quick, production deployment often takes 3-9 months.

**Key Challenges Addressed:**
*   **Customization:** Business logic, data grounding, security/compliance.
*   **Evaluation:** Metrics, quality assessment, test datasets.
*   **Deployment:** Cloud infrastructure, CI/CD, UI integration.
*   **Observability:** Performance tracking, user feedback.

**Solution: Agent Starter Pack**
Provides MLOps and infrastructure templates so developers focus on agent logic.

*   **You Build:** Prompts, LLM interactions, business logic, agent orchestration.
*   **We Provide:**
    *   Deployment infrastructure, CI/CD, testing
    *   Logging, monitoring
    *   Evaluation tools
    *   Data connections, UI playground
    *   Security best practices

Establishes production patterns from day one, saving setup time.

---
### Section 2: Creating & Enhancing Agent Projects

Start by creating a new agent project from a predefined template, or enhance an existing project with agent capabilities. Both processes support interactive and fully automated setup.

**Prerequisites:**
Before you begin, ensure you have `uv`/`uvx`, `gcloud` CLI, `terraform`, `git`, and `gh` CLI (for automated CI/CD setup) installed and authenticated.

**Installing the `agent-starter-pack` CLI:**
Choose one method to get the `agent-starter-pack` command:

1.  **`uvx` (Recommended for Zero-Install/Automation):** Run directly without prior installation.
    ```bash
    uvx agent-starter-pack create ...
    ```
2.  **Virtual Environment (`pip` or `uv`):**
    ```bash
    pip install agent-starter-pack
    ```
3.  **Persistent CLI Install (`pipx` or `uv tool`):** Installs globally in an isolated environment.

---
### `agent-starter-pack create` Command

Generates a new agent project directory based on a chosen template and configuration.

**Usage:**
```bash
agent-starter-pack create PROJECT_NAME [OPTIONS]
```

**Arguments:**
*   `PROJECT_NAME`: Name for your new project directory and base for GCP resource naming (max 26 chars, converted to lowercase).

**Template Selection:**
*   `-a, --agent`: Agent template - built-in agents (e.g., `adk`, `agentic_rag`), remote templates (`adk@gemini-fullstack`, `github.com/user/repo@branch`), or local projects (`local@./path`).

**Deployment Options:**
*   `-d, --deployment-target`: Target environment (`cloud_run` or `agent_engine`).
*   `--cicd-runner`: CI/CD runner (`google_cloud_build` or `github_actions`).
*   `--region`: GCP region (default: `us-central1`).

**Data & Storage:**
*   `-i, --include-data-ingestion`: Include data ingestion pipeline.
*   `-ds, --datastore`: Datastore type (`vertex_ai_search`, `vertex_ai_vector_search`, `cloud_sql`).
*   `--session-type`: Session storage (`in_memory`, `cloud_sql`, `agent_engine`).

**Project Creation:**
*   `-o, --output-dir`: Output directory (default: current directory).
*   `--agent-directory, -dir`: Agent code directory name (default: `app`).
*   `--in-folder`: Create files in current directory instead of new subdirectory.

**Automation:**
*   `--auto-approve`: **Skip all interactive prompts (crucial for automation).**
*   `--skip-checks`: Skip GCP/Vertex AI verification checks.
*   `--debug`: Enable debug logging.

**Automated Creation Example:**
```bash
uvx agent-starter-pack create my-automated-agent \
  -a adk \
  -d cloud_run \
  --region us-central1 \
  --auto-approve
```

---

### `agent-starter-pack enhance` Command

Enhance your existing project with AI agent capabilities by adding agent-starter-pack features in-place. This command supports all the same options as `create` but templates directly into the current directory instead of creating a new project directory.

**Usage:**
```bash
agent-starter-pack enhance [TEMPLATE_PATH] [OPTIONS]
```

**Key Differences from `create`:**
*   Templates into current directory (equivalent to `create --in-folder`)
*   `TEMPLATE_PATH` defaults to current directory (`.`)
*   Project name defaults to current directory name
*   Additional `--base-template` option to override template inheritance

**Enhanced Project Example:**
```bash
# Enhance current directory with agent capabilities
uvx agent-starter-pack enhance . \
  --base-template adk \
  -d cloud_run \
  --region us-central1 \
  --auto-approve
```

**Project Structure:** Expects agent code in `app/` directory (configurable via `--agent-directory`).

---

### `agent-starter-pack extract` Command

Creates a minimal, shareable version of an agent by stripping deployment scaffolding while preserving core agent logic.

**Usage:**
```bash
agent-starter-pack extract OUTPUT_PATH [OPTIONS]
```

**Key Options:**
*   `OUTPUT_PATH`: Required destination directory for extracted agent
*   `--source, -s`: Source project directory (default: `.`)
*   `--dry-run`: Preview what would be extracted without making changes
*   `--force, -f`: Overwrite output directory if it exists

**What Gets Extracted:**
- Agent directory (e.g., `app/`) with `agent.py` and custom modules
- `pyproject.toml` (scaffolding dependencies removed)
- Minimal `Makefile` and `README.md`

**What Gets Removed:**
- `deployment/`, `.github/`, `.cloudbuild/`, `frontend/`, `data_ingestion/`, `notebooks/`, `tests/`
- Scaffolding files: `fast_api_app.py`, `agent_engine_app.py`, `app_utils/`

**Example:**
```bash
# Extract current project to shareable form
uvx agent-starter-pack extract ../my-agent-share

# Preview changes first
uvx agent-starter-pack extract ../my-agent-share --dry-run
```

**Workflow:** Use `extract` to share agents, then recipients use `enhance` to add their own deployment infrastructure.

---

### `agent-starter-pack upgrade` Command

Upgrades projects to newer ASP versions using intelligent 3-way merge.

**Usage:**
```bash
agent-starter-pack upgrade [PROJECT_PATH] [OPTIONS]
```

**Key Options:**
*   `PROJECT_PATH`: Project to upgrade (default: `.`)
*   `--dry-run`: Preview changes without applying them
*   `--auto-approve, -y`: Auto-apply non-conflicting changes without prompts

**3-Way Merge Logic:**
- **You unchanged, ASP updated** → Auto-update the file
- **You modified, ASP unchanged** → Preserve your version
- **Both changed** → Prompt to resolve conflict
- **New ASP file** → Prompt to add
- **Removed in ASP** → Prompt to remove

**Files Never Modified:**
- Agent code (`app/agent.py`, custom modules)
- Configuration files (`.env`, secrets)

**Example:**
```bash
# Preview upgrade changes
uvx agent-starter-pack upgrade --dry-run

# Apply upgrade with auto-approve for non-conflicts
uvx agent-starter-pack upgrade -y
```

**Requirements:** Requires `uvx` and project must have `asp_version` in `[tool.agent-starter-pack]` section of `pyproject.toml`.

---

### Available Agent Templates

Templates for the `create` command (via `-a` or `--agent`):

| Agent Name             | Description                                  |
| :--------------------- | :------------------------------------------- |
| `adk`             | Base ReAct agent (ADK)                       |
| `adk_gemini_fullstack` | Production-ready fullstack research agent    |
| `agentic_rag`          | RAG agent for document retrieval & Q&A       |
| `langgraph`       | Base ReAct agent (LangGraph)                 |
| `adk_live`             | Real-time multimodal RAG agent               |

---

### Including a Data Ingestion Pipeline (for RAG agents)

For RAG agents needing custom document search, enabling this option automates loading, chunking, embedding documents with Vertex AI, and storing them in a vector database.

**How to enable:**
```bash
uvx agent-starter-pack create my-rag-agent \
  -a agentic_rag \
  -d cloud_run \
  -i \
  -ds vertex_ai_search \
  --auto-approve
```
**Post-creation:** Follow your new project's `data_ingestion/README.md` to deploy the necessary infrastructure.

---
### Section 3: Development & Automated Deployment Workflow
---

This section describes the end-to-end lifecycle of an agent, with emphasis on automation.


### 1. Local Development & Iteration

Once your project is created, navigate into its directory to begin development.

**First, install dependencies (run once):**
```bash
make install
```

**Next, test your agent. The recommended method is to use a programmatic script.**

#### Programmatic Testing (Recommended Workflow)

This method allows for quick, automated validation of your agent's logic.

1.  **Create a script:** In the project's root directory, create a Python script named `run_agent.py`.
2.  **Invoke the agent:** In the script, write code to programmatically call your agent with sample input and `print()` the output for inspection.
    *   **Guidance:** If you're unsure or no guidance exists, you can look at files in the `tests/` directory for examples of how to import and call the agent's main function.
    *   **Important:** This script is for simple validation. **Assertions are not required**, and you should not create a formal `pytest` file.
3.  **Run the test:** Execute your script from the terminal using `uv`.
    ```bash
    uv run python run_agent.py
    ```
You can keep the test file for future testing.

#### Manual Testing with the UI Playground (Optional)

If the user needs to interact with your agent manually in a chat interface for debugging:

1.  Run the following command to start the local web UI:
    ```bash
    make playground
    ```
    This is useful for human-in-the-loop testing and features hot-reloading.

### 2. Deploying to a Cloud Development Environment
Before setting up full CI/CD, you can deploy to a personal cloud dev environment.

1.  **Set Project:** `gcloud config set project YOUR_DEV_PROJECT_ID`
2.  **Provision Resources:** `make setup-dev-env` (uses Terraform).
3.  **Deploy Backend:** `make deploy` (builds and deploys the agent).

### 3. Automated Production-Ready Deployment with CI/CD
For reliable deployments, the `setup-cicd` command streamlines the entire process. It creates a GitHub repo, connects it to your chosen CI/CD runner (Google Cloud Build or GitHub Actions), provisions staging/prod infrastructure, and configures deployment triggers.

**Automated CI/CD Setup Example (Recommended):**
```bash
# Run from the project root. This command will guide you or can be automated with flags.
uvx agent-starter-pack setup-cicd
```

**CI/CD Workflow Logic:**
*   **On Pull Request:** CI pipeline runs tests.
*   **On Merge to `main`:** CD pipeline deploys to staging.
*   **Manual Approval:** A manual approval step triggers the production deployment.

---
### Section 4: Key Features & Customization
---

### Deploying with a User Interface (UI)
*   **Unified Deployment (for Dev/Test):** The backend and frontend can be packaged and served from a single Cloud Run service, secured with Identity-Aware Proxy (IAP).
*   **Deploying with UI:** `make deploy IAP=true`
*   **Access Control:** After deploying with IAP, grant users the `IAP-secured Web App User` role in IAM to give them access.

### Session Management

For stateful agents, the starter pack supports persistent sessions.
*   **Cloud Run:** Choose between `in_memory` (for testing) and durable `cloud_sql` sessions using the `--session-type` flag.
*   **Agent Engine:** Provides session management automatically.

### Monitoring & Observability
*   **Technology:** Uses OpenTelemetry to emit events to Google Cloud Trace and Logging.
*   **Custom Tracer:** A custom tracer in `app/utils/tracing.py` (or a different agent directory instead of app) handles large payloads by linking to GCS, overcoming default service limits.
*   **Infrastructure:** A Log Router to sink data to BigQuery is provisioned by Terraform.

---
### Section 5: CLI Reference for CI/CD Setup
---

### `agent-starter-pack setup-cicd`
Automates the complete CI/CD infrastructure setup for GitHub-based deployments. Intelligently detects your CI/CD runner (Google Cloud Build or GitHub Actions) and configures everything automatically.

**Usage:**
```bash
uvx agent-starter-pack setup-cicd [OPTIONS]
```

**Prerequisites:** 
- Run from the project root (directory with `pyproject.toml`)
- Required tools: `gh` CLI (authenticated), `gcloud` CLI (authenticated), `terraform`
- `Owner` role on GCP projects
- GitHub token with `repo` and `workflow` scopes

**Key Options:**
*   `--staging-project`, `--prod-project`: GCP project IDs (will prompt if omitted).
*   `--repository-name`, `--repository-owner`: GitHub repo details (will prompt if omitted).
*   `--cicd-project`: CI/CD resources project (defaults to prod project).
*   `--dev-project`: Development project ID (optional).
*   `--region`: GCP region (default: `us-central1`).
*   `--auto-approve`: Skip all interactive prompts.
*   `--local-state`: Use local Terraform state instead of GCS backend.
*   `--debug`: Enable debug logging.

**What it does:**
1. Creates/connects GitHub repository
2. Sets up Terraform infrastructure with remote state
3. Configures CI/CD runner connection (Cloud Build or GitHub Actions with WIF)
4. Provisions staging/prod environments
5. Sets up local Git repository with origin remote

**Automated Example:**
```bash
uvx agent-starter-pack setup-cicd \
  --staging-project your-staging-project \
  --prod-project your-prod-project \
  --repository-name your-repo-name \
  --repository-owner your-username \
  --auto-approve
```

**After setup, push to trigger pipeline:**
```bash
git add . && git commit -m "Initial commit" && git push -u origin main
```

* Note: For coding agents - ask user for required project IDs and repo details before running with `--auto-approve`.
* Note: If user prefers different git provider, refer to `deployment/README.md` for manual deployment.
---
### Section 6: Operational Guidelines for Coding Agents

These guidelines are essential for interacting with the Agent Starter Pack project effectively.

---

### Principle 1: Code Preservation & Isolation

When executing code modifications using tools like `replace` or `write_file`, your paramount objective is surgical precision. You **must alter only the code segments directly targeted** by the user's request, while **strictly preserving all surrounding and unrelated code.**

**Mandatory Pre-Execution Verification:**

Before finalizing any `new_string` for a `replace` operation, meticulously verify the following:

1.  **Target Identification:** Clearly define the exact lines or expressions to be changed, based *solely* on the user's explicit instructions.
2.  **Preservation Check:** Compare your proposed `new_string` against the `old_string`. Ensure all code, configuration values (e.g., `model`, `version`, `api_key`), comments, and formatting *outside* the identified target remain identical and verbatim.

**Example: Adhering to Preservation**

*   **User Request:** "Change the agent's instruction to be a recipe suggester."
*   **Original Code Snippet:**
    ```python
    root_agent = Agent(
        name="root_agent",
        model="gemini-3-flash-preview",
        instruction="You are a helpful AI assistant."
    )
    ```
*   **Incorrect Modification (VIOLATION):**
    ```python
    root_agent = Agent(
        name="recipe_suggester",
        model="gemini-1.5-flash", # UNINTENDED MUTATION - model was not requested to change
        instruction="You are a recipe suggester."
    )
    ```
*   **Correct Modification (COMPLIANT):**
    ```python
    root_agent = Agent(
        name="recipe_suggester", # OK, related to new purpose
        model="gemini-3-flash-preview", # MUST be preserved
        instruction="You are a recipe suggester." # OK, the direct target
    )
    ```

**Critical Error:** Failure to adhere to this preservation principle is a critical error. Always prioritize the integrity of existing, unchanged code over the convenience of rewriting entire blocks.

---

### Principle 2: Workflow & Execution Best Practices

*   **Standard Workflow:**
    The validated end-to-end process is: `create` → `test` → `setup-cicd` → push to deploy. Trust this high-level workflow as the default for developing and shipping agents.

*   **Agent Testing:**
    *   **Avoid `make playground`** unless specifically instructed; it is designed for human interaction. Focus on programmatic testing.

*   **Model Selection:**
    *   **When using Gemini, prefer modern model families** for optimal performance and capabilities: "gemini-2.5-pro", "gemini-2.5-flash", and "gemini-3-flash-preview"

*   **Running Python Commands:**
    *   Always use `uv` to execute Python commands within this repository (e.g., `uv run run_agent.py`).
    *   Ensure project dependencies are installed by running `make install` before executing scripts.
    *   Consult the project's `Makefile` and `README.md` for other useful development commands.

*   **Further Reading & Troubleshooting:**
    *   For questions about specific frameworks (e.g., LangGraph) or Google Cloud products (e.g., Cloud Run), their official documentation and online resources are the best source of truth.
    *   **When encountering persistent errors or if you're unsure how to proceed after initial troubleshooting, a targeted Google Search is strongly recommended.** It is often the fastest way to find relevant documentation, community discussions, or direct solutions to your problem.
