@intentsolutionsio/jeremy-gcp-starter-examples 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,477 @@
1
+ # Examples — GCP Starter Examples
2
+
3
+ ## Example 1: ADK Agent with Code Execution and Memory Bank
4
+
5
+ Create a production ADK agent deployed to Vertex AI Agent Engine.
6
+
7
+ ### Project Setup
8
+
9
+ ```bash
10
+ # Install ADK CLI and dependencies
11
+ pip install google-adk google-cloud-aiplatform
12
+
13
+ # Authenticate
14
+ gcloud auth application-default login
15
+ gcloud config set project my-gcp-project
16
+ gcloud services enable aiplatform.googleapis.com
17
+ ```
18
+
19
+ ### Agent Implementation
20
+
21
+ ```python
22
+ # agent.py
23
+ from google.adk.agents import Agent
24
+ from google.adk.tools import CodeExecution, MemoryBank
25
+
26
+ # Define the agent with Code Execution Sandbox and Memory Bank
27
+ agent = Agent(
28
+ model="gemini-2.5-flash",
29
+ name="data-analyst",
30
+ description="Analyzes datasets using code execution with persistent memory",
31
+ system_instruction="""You are a data analyst agent.
32
+
33
+ CAPABILITIES:
34
+ - Execute Python code in a secure sandbox to analyze data
35
+ - Remember previous analyses and user preferences via Memory Bank
36
+ - Generate visualizations and statistical summaries
37
+
38
+ WORKFLOW:
39
+ 1. Understand the user's data question
40
+ 2. Check Memory Bank for relevant context from prior sessions
41
+ 3. Write and execute Python code to analyze the data
42
+ 4. Store key findings in Memory Bank for future reference
43
+ 5. Return clear, actionable insights with visualizations
44
+
45
+ CONSTRAINTS:
46
+ - Always validate data before analysis
47
+ - Use pandas for tabular data, matplotlib/seaborn for plots
48
+ - Cap output to 20 rows for large datasets
49
+ - Store analysis summaries, not raw data, in Memory Bank
50
+ """,
51
+ tools=[
52
+ CodeExecution(
53
+ sandbox_type="SECURE_ISOLATED",
54
+ state_ttl_days=14,
55
+ ),
56
+ MemoryBank(
57
+ enabled=True,
58
+ retention_count=100,
59
+ ),
60
+ ],
61
+ )
62
+
63
+ # Local testing
64
+ if __name__ == "__main__":
65
+ response = agent.run("Analyze the sales trends in Q4 from sales_data.csv")
66
+ print(response.text)
67
+ ```
68
+
69
+ ### Deployment to Agent Engine
70
+
71
+ ```bash
72
+ # Deploy to Vertex AI Agent Engine
73
+ adk deploy \
74
+ --agent-file agent.py \
75
+ --project-id my-gcp-project \
76
+ --region us-central1 \
77
+ --service-name data-analyst-agent \
78
+ --min-instances 1 \
79
+ --max-instances 5
80
+
81
+ # Verify deployment
82
+ gcloud run services list --project=my-gcp-project --region=us-central1
83
+ ```
84
+
85
+ ### Expected Output
86
+
87
+ ```
88
+ Deploying agent 'data-analyst' to us-central1...
89
+ Agent deployed successfully.
90
+ Name: projects/my-gcp-project/locations/us-central1/agents/data-analyst-agent
91
+ Endpoint: https://us-central1-my-gcp-project.agent.vertexai.goog
92
+ Status: ACTIVE
93
+ Model: gemini-2.5-flash
94
+ Tools: CodeExecution (SECURE_ISOLATED, 14d TTL), MemoryBank (100 memories)
95
+ ```
96
+
97
+ ---
98
+
99
+ ## Example 2: Genkit RAG Flow with Firestore Vector Search
100
+
101
+ Build a retrieval-augmented generation system deployed to Cloud Run.
102
+
103
+ ### Project Initialization
104
+
105
+ ```bash
106
+ mkdir genkit-rag && cd genkit-rag
107
+ npm init -y
108
+ npm install genkit @genkit-ai/googleai @genkit-ai/firebase zod
109
+ npm install -D typescript @types/node tsx
110
+ ```
111
+
112
+ ### Flow Implementation
113
+
114
+ ```typescript
115
+ // src/rag-flow.ts
116
+ import { genkit, z } from "genkit";
117
+ import { googleAI, gemini25Flash, textEmbedding004 } from "@genkit-ai/googleai";
118
+
119
+ const ai = genkit({
120
+ plugins: [googleAI()],
121
+ });
122
+
123
+ // Define input/output schemas
124
+ const QuerySchema = z.object({
125
+ question: z.string().min(1).describe("The user's question"),
126
+ maxResults: z.number().min(1).max(20).default(5),
127
+ });
128
+
129
+ const AnswerSchema = z.object({
130
+ answer: z.string(),
131
+ sources: z.array(z.object({
132
+ title: z.string(),
133
+ snippet: z.string(),
134
+ relevanceScore: z.number(),
135
+ })),
136
+ tokenUsage: z.object({
137
+ prompt: z.number(),
138
+ completion: z.number(),
139
+ }),
140
+ });
141
+
142
+ // Define the retriever using text-embedding-004
143
+ const docRetriever = ai.defineRetriever(
144
+ { name: "firestore-docs" },
145
+ async (query: string, options?: { k?: number }) => {
146
+ const k = options?.k ?? 5;
147
+
148
+ // Generate embedding for the query
149
+ const { embedding } = await ai.embed({
150
+ embedder: textEmbedding004,
151
+ content: query,
152
+ });
153
+
154
+ // Query Firestore vector index (using Admin SDK)
155
+ const { Firestore } = await import("firebase-admin/firestore");
156
+ const db = new Firestore();
157
+ const snapshot = await db
158
+ .collection("documents")
159
+ .findNearest("embedding", embedding, { limit: k, distanceMeasure: "COSINE" })
160
+ .get();
161
+
162
+ return snapshot.docs.map((doc) => ({
163
+ content: doc.data().content as string,
164
+ metadata: {
165
+ title: doc.data().title as string,
166
+ source: doc.id,
167
+ score: doc.data().score as number,
168
+ },
169
+ }));
170
+ }
171
+ );
172
+
173
+ // Define the RAG flow
174
+ export const ragFlow = ai.defineFlow(
175
+ {
176
+ name: "rag-query",
177
+ inputSchema: QuerySchema,
178
+ outputSchema: AnswerSchema,
179
+ },
180
+ async (input) => {
181
+ // Step 1: Retrieve relevant documents
182
+ const docs = await ai.retrieve({
183
+ retriever: docRetriever,
184
+ query: input.question,
185
+ options: { k: input.maxResults },
186
+ });
187
+
188
+ // Step 2: Build context from retrieved docs
189
+ const context = docs
190
+ .map((d, i) => `[${i + 1}] ${d.metadata?.title}: ${d.content}`)
191
+ .join("\n\n");
192
+
193
+ // Step 3: Generate grounded answer
194
+ const { text, usage } = await ai.generate({
195
+ model: gemini25Flash,
196
+ prompt: `Answer the question using ONLY the provided context. Cite sources by number.
197
+
198
+ Context:
199
+ ${context}
200
+
201
+ Question: ${input.question}
202
+
203
+ If the context doesn't contain enough information, say so clearly.`,
204
+ config: { temperature: 0.3, maxOutputTokens: 1024 },
205
+ });
206
+
207
+ return {
208
+ answer: text,
209
+ sources: docs.map((d, i) => ({
210
+ title: d.metadata?.title ?? `Source ${i + 1}`,
211
+ snippet: d.content.substring(0, 200),
212
+ relevanceScore: d.metadata?.score ?? 0,
213
+ })),
214
+ tokenUsage: {
215
+ prompt: usage?.inputTokens ?? 0,
216
+ completion: usage?.outputTokens ?? 0,
217
+ },
218
+ };
219
+ }
220
+ );
221
+
222
+ // Start the Genkit server for local development and Cloud Run
223
+ ai.startFlowServer({ flows: [ragFlow] });
224
+ ```
225
+
226
+ ### Deployment to Cloud Run
227
+
228
+ ```bash
229
+ # Build and deploy
230
+ gcloud run deploy genkit-rag \
231
+ --source . \
232
+ --region us-central1 \
233
+ --memory 512Mi \
234
+ --min-instances 2 \
235
+ --max-instances 10 \
236
+ --set-env-vars "GOOGLE_GENAI_API_KEY=$(gcloud secrets versions access latest --secret=genai-api-key)" \
237
+ --allow-unauthenticated
238
+
239
+ # Test the deployed endpoint
240
+ curl -X POST https://genkit-rag-abc123-uc.a.run.app/rag-query \
241
+ -H "Content-Type: application/json" \
242
+ -d '{"question": "How do I configure VPC Service Controls?", "maxResults": 3}'
243
+ ```
244
+
245
+ ### Expected Output
246
+
247
+ ```json
248
+ {
249
+ "answer": "To configure VPC Service Controls, follow these steps:\n\n1. Create a service perimeter in the Access Context Manager [1]\n2. Add your GCP project to the perimeter [2]\n3. Configure restricted services (e.g., aiplatform.googleapis.com) [1]\n4. Set up access levels for authorized identities [3]\n\nNote: Changes can take up to 30 minutes to propagate.",
250
+ "sources": [
251
+ {
252
+ "title": "VPC-SC Setup Guide",
253
+ "snippet": "VPC Service Controls create security perimeters around GCP resources...",
254
+ "relevanceScore": 0.94
255
+ },
256
+ {
257
+ "title": "Project Security Baseline",
258
+ "snippet": "Every production project should be added to a VPC-SC perimeter...",
259
+ "relevanceScore": 0.89
260
+ },
261
+ {
262
+ "title": "Access Context Manager",
263
+ "snippet": "Access levels define conditions under which access is granted...",
264
+ "relevanceScore": 0.82
265
+ }
266
+ ],
267
+ "tokenUsage": {
268
+ "prompt": 1240,
269
+ "completion": 185
270
+ }
271
+ }
272
+ ```
273
+
274
+ ---
275
+
276
+ ## Example 3: Gemini Multimodal Video Analysis
277
+
278
+ Analyze video content using Gemini 2.5 Pro with structured output.
279
+
280
+ ```python
281
+ # video_analyzer.py
282
+ import vertexai
283
+ from vertexai.generative_models import GenerativeModel, Part, SafetySetting
284
+ import json
285
+
286
+ vertexai.init(project="my-gcp-project", location="us-central1")
287
+
288
+ model = GenerativeModel(
289
+ "gemini-2.5-pro",
290
+ generation_config={
291
+ "temperature": 0.2,
292
+ "max_output_tokens": 2048,
293
+ "response_mime_type": "application/json",
294
+ },
295
+ safety_settings=[
296
+ SafetySetting(
297
+ category="HARM_CATEGORY_DANGEROUS_CONTENT",
298
+ threshold="BLOCK_ONLY_HIGH",
299
+ ),
300
+ ],
301
+ )
302
+
303
+ def analyze_video(video_uri: str, questions: list[str]) -> dict:
304
+ """Analyze a video stored in GCS with specific questions."""
305
+
306
+ video_part = Part.from_uri(video_uri, mime_type="video/mp4")
307
+
308
+ prompt = f"""Analyze this video and answer the following questions.
309
+ Return a JSON object with this structure:
310
+ {{
311
+ "duration_estimate": "estimated video duration",
312
+ "scene_count": number,
313
+ "answers": [
314
+ {{"question": "...", "answer": "...", "confidence": 0.0-1.0, "timestamp": "MM:SS"}}
315
+ ],
316
+ "key_objects": ["list of notable objects/people/text seen"],
317
+ "overall_summary": "2-3 sentence summary"
318
+ }}
319
+
320
+ Questions:
321
+ {chr(10).join(f'{i+1}. {q}' for i, q in enumerate(questions))}
322
+ """
323
+
324
+ response = model.generate_content([video_part, prompt])
325
+
326
+ # Parse structured JSON output
327
+ result = json.loads(response.text)
328
+
329
+ # Add token usage for cost tracking
330
+ result["usage"] = {
331
+ "prompt_tokens": response.usage_metadata.prompt_token_count,
332
+ "completion_tokens": response.usage_metadata.candidates_token_count,
333
+ "estimated_cost_usd": (
334
+ response.usage_metadata.prompt_token_count * 0.00000125
335
+ + response.usage_metadata.candidates_token_count * 0.000005
336
+ ),
337
+ }
338
+
339
+ return result
340
+
341
+
342
+ # Usage
343
+ result = analyze_video(
344
+ video_uri="gs://my-bucket/product-demo.mp4",
345
+ questions=[
346
+ "What product is being demonstrated?",
347
+ "How many people appear in the video?",
348
+ "What is the main call to action?",
349
+ ],
350
+ )
351
+
352
+ print(json.dumps(result, indent=2))
353
+ ```
354
+
355
+ ### Expected Output
356
+
357
+ ```json
358
+ {
359
+ "duration_estimate": "2 minutes 34 seconds",
360
+ "scene_count": 5,
361
+ "answers": [
362
+ {
363
+ "question": "What product is being demonstrated?",
364
+ "answer": "A cloud-based project management tool with Kanban boards and time tracking",
365
+ "confidence": 0.95,
366
+ "timestamp": "00:15"
367
+ },
368
+ {
369
+ "question": "How many people appear in the video?",
370
+ "answer": "Two people: a presenter and a user demonstrating the interface",
371
+ "confidence": 0.88,
372
+ "timestamp": "00:05"
373
+ },
374
+ {
375
+ "question": "What is the main call to action?",
376
+ "answer": "Sign up for a free 14-day trial at the URL shown at 02:28",
377
+ "confidence": 0.92,
378
+ "timestamp": "02:28"
379
+ }
380
+ ],
381
+ "key_objects": ["laptop", "Kanban board UI", "company logo", "pricing table", "QR code"],
382
+ "overall_summary": "A product demo video showcasing a cloud project management tool. The presenter walks through Kanban board features, time tracking, and team collaboration tools before closing with a free trial offer.",
383
+ "usage": {
384
+ "prompt_tokens": 48200,
385
+ "completion_tokens": 312,
386
+ "estimated_cost_usd": 0.0619
387
+ }
388
+ }
389
+ ```
390
+
391
+ ---
392
+
393
+ ## Example 4: Terraform Module for Agent Engine Deployment
394
+
395
+ Infrastructure-as-code for reproducible agent deployments.
396
+
397
+ ```hcl
398
+ # main.tf — Vertex AI Agent Engine with VPC-SC and monitoring
399
+ terraform {
400
+ required_providers {
401
+ google = {
402
+ source = "hashicorp/google"
403
+ version = "~> 5.0"
404
+ }
405
+ }
406
+ }
407
+
408
+ variable "project_id" { type = string }
409
+ variable "region" { default = "us-central1" }
410
+ variable "agent_name" { type = string }
411
+
412
+ # Enable required APIs
413
+ resource "google_project_service" "apis" {
414
+ for_each = toset([
415
+ "aiplatform.googleapis.com",
416
+ "monitoring.googleapis.com",
417
+ "logging.googleapis.com",
418
+ "secretmanager.googleapis.com",
419
+ ])
420
+ project = var.project_id
421
+ service = each.value
422
+ }
423
+
424
+ # Least-privilege service account
425
+ resource "google_service_account" "agent_sa" {
426
+ account_id = "${var.agent_name}-sa"
427
+ display_name = "Agent Engine SA for ${var.agent_name}"
428
+ project = var.project_id
429
+ }
430
+
431
+ resource "google_project_iam_member" "agent_roles" {
432
+ for_each = toset([
433
+ "roles/aiplatform.user",
434
+ "roles/logging.logWriter",
435
+ "roles/monitoring.metricWriter",
436
+ ])
437
+ project = var.project_id
438
+ role = each.value
439
+ member = "serviceAccount:${google_service_account.agent_sa.email}"
440
+ }
441
+
442
+ # Monitoring alert for error rate > 5%
443
+ resource "google_monitoring_alert_policy" "agent_errors" {
444
+ display_name = "${var.agent_name} Error Rate"
445
+ project = var.project_id
446
+
447
+ conditions {
448
+ display_name = "Error rate exceeds 5%"
449
+ condition_threshold {
450
+ filter = "resource.type=\"aiplatform.googleapis.com/Agent\" AND metric.type=\"aiplatform.googleapis.com/agent/error_count\""
451
+ comparison = "COMPARISON_GT"
452
+ threshold_value = 5
453
+ duration = "300s"
454
+ aggregations {
455
+ alignment_period = "60s"
456
+ per_series_aligner = "ALIGN_RATE"
457
+ }
458
+ }
459
+ }
460
+
461
+ notification_channels = [] # Add your notification channel IDs
462
+ }
463
+
464
+ output "service_account_email" {
465
+ value = google_service_account.agent_sa.email
466
+ }
467
+ ```
468
+
469
+ ```bash
470
+ # Deploy
471
+ terraform init
472
+ terraform plan -var="project_id=my-gcp-project" -var="agent_name=data-analyst"
473
+ terraform apply -auto-approve -var="project_id=my-gcp-project" -var="agent_name=data-analyst"
474
+ ```
475
+
476
+ ---
477
+ *[Tons of Skills](https://tonsofskills.com) by [Intent Solutions](https://intentsolutions.io) | [jeremylongshore.com](https://jeremylongshore.com)*
@@ -0,0 +1,38 @@
1
+ # Workflow
2
+
3
+ ## Workflow
4
+
5
+ ### Phase 1: Identify Use Case
6
+ ```
7
+ 1. Listen for trigger phrases in user request
8
+ 2. Determine which repository has relevant examples
9
+ 3. Identify specific code pattern needed
10
+ 4. Select appropriate framework (ADK, Genkit, Vertex AI)
11
+ ```
12
+
13
+ ### Phase 2: Provide Code Example
14
+ ```
15
+ 1. Fetch relevant code snippet from knowledge base
16
+ 2. Adapt to user's specific requirements
17
+ 3. Include imports and dependencies
18
+ 4. Add configuration details
19
+ 5. Cite source repository
20
+ ```
21
+
22
+ ### Phase 3: Explain Best Practices
23
+ ```
24
+ 1. Highlight security considerations (IAM, VPC-SC, Model Armor)
25
+ 2. Show monitoring and observability setup
26
+ 3. Demonstrate error handling patterns
27
+ 4. Include infrastructure deployment code
28
+ 5. Provide cost optimization tips
29
+ ```
30
+
31
+ ### Phase 4: Deployment Guidance
32
+ ```
33
+ 1. Provide Terraform/IaC templates
34
+ 2. Show Cloud Build CI/CD configuration
35
+ 3. Include testing strategies
36
+ 4. Document environment variables
37
+ 5. Link to official documentation
38
+ ```
@@ -0,0 +1,93 @@
1
+ #!/bin/bash
2
+ # create-example.sh - Create GCP starter example project
3
+
4
+ set -euo pipefail
5
+
6
+ EXAMPLE_TYPE="${1:-}"
7
+ PROJECT_NAME="${2:-gcp-example}"
8
+
9
+ usage() {
10
+ cat <<EOF
11
+ Usage: $0 <EXAMPLE_TYPE> [PROJECT_NAME]
12
+
13
+ Create GCP starter example projects with best practices.
14
+
15
+ Example Types:
16
+ cloud-run - Cloud Run service with CI/CD
17
+ gke - GKE cluster with workloads
18
+ vertex-ai - Vertex AI model deployment
19
+ bigquery - BigQuery data pipeline
20
+ functions - Cloud Functions
21
+ genkit - Firebase Genkit app
22
+ adk - Agent Development Kit
23
+
24
+ Example:
25
+ $0 cloud-run my-service
26
+ $0 vertex-ai ml-model
27
+
28
+ EOF
29
+ exit 1
30
+ }
31
+
32
+ if [[ -z "$EXAMPLE_TYPE" ]]; then
33
+ usage
34
+ fi
35
+
36
+ echo "Creating GCP Starter Example"
37
+ echo "Type: $EXAMPLE_TYPE"
38
+ echo "Project: $PROJECT_NAME"
39
+ echo ""
40
+
41
+ mkdir -p "$PROJECT_NAME"
42
+
43
+ case "$EXAMPLE_TYPE" in
44
+ cloud-run)
45
+ cat > "$PROJECT_NAME/Dockerfile" <<'EOF'
46
+ FROM node:20-alpine
47
+ WORKDIR /app
48
+ COPY package*.json ./
49
+ RUN npm install
50
+ COPY . .
51
+ EXPOSE 8080
52
+ CMD ["npm", "start"]
53
+ EOF
54
+ cat > "$PROJECT_NAME/app.js" <<'EOF'
55
+ const express = require('express');
56
+ const app = express();
57
+ const port = process.env.PORT || 8080;
58
+
59
+ app.get('/', (req, res) => {
60
+ res.json({ message: 'Hello from Cloud Run!' });
61
+ });
62
+
63
+ app.listen(port, () => {
64
+ console.log(`Server running on port ${port}`);
65
+ });
66
+ EOF
67
+ echo "✓ Cloud Run example created"
68
+ ;;
69
+
70
+ vertex-ai)
71
+ cat > "$PROJECT_NAME/train.py" <<'EOF'
72
+ from google.cloud import aiplatform
73
+
74
+ aiplatform.init(project='your-project', location='us-central1')
75
+
76
+ model = aiplatform.Model.upload(
77
+ display_name='my-model',
78
+ artifact_uri='gs://your-bucket/model',
79
+ serving_container_image_uri='gcr.io/cloud-aiplatform/prediction/tf2-cpu.2-8:latest'
80
+ )
81
+ print(f"Model deployed: {model.resource_name}")
82
+ EOF
83
+ echo "✓ Vertex AI example created"
84
+ ;;
85
+
86
+ *)
87
+ echo "Unknown example type: $EXAMPLE_TYPE"
88
+ usage
89
+ ;;
90
+ esac
91
+
92
+ echo ""
93
+ echo "Example created in: $PROJECT_NAME/"