[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71FWNFX8KX9VG78G03AQFAE":3,"skill-same:01M71FWNFX8KX9VG78G03AQFAE":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":48,"commitSha":49,"skillDirectory":50,"forksCount":51,"repositoryHtmlUrl":52,"repositoryHomepageUrl":6,"ownerHtmlUrl":53,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":54,"install":55,"resources":68},"01M71FWNFX8KX9VG78G03AQFAE","vertex-agent-builder",null,"Build and deploy production-ready generative AI agents using Vertex AI, Gemini models, and Google Cloud infrastructure with RAG, function calling, and multi-modal capabilities","JSGforever\u002Fskillguard","JSGforever","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F85541948?v=4","01M71FQD3E132VMR5F4TAYX3YS","01M71FQD4DYW0XJ4XQ4YQH75Y9",2,"MIT","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__BbgnsurfTech--vertex-agent-builder\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"agent builder","vertex agent builder","builder","calling","gemini","infrastructure","deploy production","google","edit","write","read","rag","capabilities","ai agents","Bash","production-ready","google cloud","generative","generative ai","ready","2026-11-10 10:12:30",false,"---\ndescription: Build and deploy production-ready generative AI agents using Vertex AI,\n  Gemini models, and Google Cloud infrastructure with RAG, function calling, and multi-modal\n  capabilities\nname: vertex-agent-builder\nallowed-tools:\n- Read\n- Write\n- Edit\n- Grep\n- Bash\nlicense: MIT\n---\n# Vertex AI Agent Builder Skill\n\n## Overview\n\nThis skill provides production-ready scaffolding and deployment for generative AI agents using Google Cloud's Vertex AI platform. Built on actual Google Cloud source code from `GoogleCloudPlatform\u002Fgenerative-ai` and `agent-starter-pack` repositories, it offers:\n\n- **Gemini Model Integration** (1.5 Pro, 1.5 Flash, experimental models)\n- **Multi-modal Capabilities** (text, image, video, audio processing)\n- **RAG Implementation** (Retrieval Augmented Generation with Vector Search)\n- **Function Calling** (Tool use with Gemini models)\n- **Production Deployment** (Cloud Run, Vertex AI Endpoints)\n- **Evaluation Framework** (AutoSxS, ROUGE, custom metrics)\n- **Observability** (Cloud Logging, Monitoring, Trace)\n\n## Installation\n\n```bash\n# Install Google Cloud SDK\ncurl https:\u002F\u002Fsdk.cloud.google.com | bash\nexec -l $SHELL\ngcloud init\n\n# Install Python SDK\npip install google-cloud-aiplatform>=1.38.0\npip install vertexai>=1.46.0\npip install google-generativeai>=0.3.2\n\n# Clone source repositories\ngit clone https:\u002F\u002Fgithub.com\u002FGoogleCloudPlatform\u002Fgenerative-ai.git\ngit clone https:\u002F\u002Fgithub.com\u002FGoogleCloudPlatform\u002Fagent-starter-pack.git\ngit clone https:\u002F\u002Fgithub.com\u002FGoogleCloudPlatform\u002Fvertex-ai-samples.git\n\n# Install this plugin\n\u002Fplugin install jeremy-vertex-ai@jeremylongshore\n```\n\n## Quick Start (5 Minutes)\n\n### Create Your First Vertex AI Agent\n\n```python\nimport vertexai\nfrom vertexai.generative_models import GenerativeModel, ChatSession\nfrom vertexai.preview.generative_models import grounding\n\n# Initialize Vertex AI\nvertexai.init(project=\"your-project-id\", location=\"us-central1\")\n\n# Create Gemini model\nmodel = GenerativeModel(\n    \"gemini-1.5-pro-002\",\n    system_instruction=\"\"\"You are a helpful AI assistant that can:\n    - Search the web for information\n    - Analyze documents and images\n    - Execute Python code\n    - Call external APIs\n    \"\"\"\n)\n\n# Start chat session\nchat = model.start_chat()\n\n# Send message with grounding\nresponse = chat.send_message(\n    \"What are the latest developments in quantum computing?\",\n    generation_config={\n        \"temperature\": 0.3,\n        \"max_output_tokens\": 2048,\n        \"top_p\": 0.95,\n    },\n    safety_settings={\n        \"HARM_CATEGORY_HATE_SPEECH\": \"BLOCK_MEDIUM_AND_ABOVE\",\n        \"HARM_CATEGORY_DANGEROUS_CONTENT\": \"BLOCK_MEDIUM_AND_ABOVE\",\n    },\n    tools=[grounding.Tool(google_search_retrieval=grounding.GoogleSearchRetrieval())]\n)\n\nprint(response.text)\n```\n\n## Agent Patterns\n\n### 1. Production Agent with Agent Builder\n\nBased on `GoogleCloudPlatform\u002Fagent-starter-pack`:\n\n```python\nfrom vertexai.preview import agents\nfrom vertexai.preview.generative_models import Tool, FunctionDeclaration\nimport functions_framework\n\nclass ProductionAgent:\n    \"\"\"\n    Production-ready agent using Vertex AI Agent Builder\n    \"\"\"\n\n    def __init__(self, project_id: str, location: str = \"us-central1\"):\n        self.project_id = project_id\n        self.location = location\n\n        # Initialize agent\n        self.agent = agents.Agent.create(\n            project=project_id,\n            location=location,\n            display_name=\"production-agent\",\n            description=\"Production-ready agent with tools and RAG\",\n            model=\"gemini-1.5-pro-002\",\n            tools=self._create_tools(),\n            system_instruction=self._get_system_instruction()\n        )\n\n    def _create_tools(self):\n        \"\"\"Create function calling tools\"\"\"\n        return [\n            Tool(function_declarations=[\n                FunctionDeclaration(\n                    name=\"search_knowledge_base\",\n                    description=\"Search internal knowledge base\",\n                    parameters={\n                        \"type\": \"object\",\n                        \"properties\": {\n                            \"query\": {\"type\": \"string\"},\n                            \"top_k\": {\"type\": \"integer\", \"default\": 5}\n                        }\n                    }\n                ),\n                FunctionDeclaration(\n                    name=\"execute_sql\",\n                    description=\"Execute SQL query on BigQuery\",\n                    parameters={\n                        \"type\": \"object\",\n                        \"properties\": {\n                            \"query\": {\"type\": \"string\"},\n                            \"dataset\": {\"type\": \"string\"}\n                        }\n                    }\n                ),\n                FunctionDeclaration(\n                    name=\"send_email\",\n                    description=\"Send email notification\",\n                    parameters={\n                        \"type\": \"object\",\n                        \"properties\": {\n                            \"to\": {\"type\": \"string\"},\n                            \"subject\": {\"type\": \"string\"},\n                            \"body\": {\"type\": \"string\"}\n                        }\n                    }\n                )\n            ])\n        ]\n\n    def _get_system_instruction(self):\n        \"\"\"Get system instruction for agent\"\"\"\n        return \"\"\"You are a production AI agent that helps users with:\n        1. Information retrieval from knowledge bases\n        2. Data analysis using BigQuery\n        3. Automated communications\n\n        Always verify user intent before executing critical operations.\n        Provide clear explanations of what you're doing and why.\n        \"\"\"\n\n    async def process_request(self, user_input: str):\n        \"\"\"Process user request\"\"\"\n        session = self.agent.start_session()\n        response = await session.send_message(user_input)\n\n        # Handle function calls\n        if response.function_calls:\n            for func_call in response.function_calls:\n                result = await self._execute_function(\n                    func_call.name,\n                    func_call.args\n                )\n                # Send function result back to model\n                response = await session.send_message(\n                    content=None,\n                    function_responses=[{\n                        \"name\": func_call.name,\n                        \"response\": result\n                    }]\n                )\n\n        return response.text\n\n    async def _execute_function(self, name: str, args: dict):\n        \"\"\"Execute function call\"\"\"\n        if name == \"search_knowledge_base\":\n            return await self._search_kb(args[\"query\"], args.get(\"top_k\", 5))\n        elif name == \"execute_sql\":\n            return await self._execute_bigquery(args[\"query\"], args[\"dataset\"])\n        elif name == \"send_email\":\n            return await self._send_email(args[\"to\"], args[\"subject\"], args[\"body\"])\n\n# Deploy as Cloud Function\n@functions_framework.http\ndef agent_endpoint(request):\n    \"\"\"HTTP Cloud Function for agent\"\"\"\n    agent = ProductionAgent(\n        project_id=\"your-project\",\n        location=\"us-central1\"\n    )\n\n    request_json = request.get_json()\n    response = agent.process_request(request_json[\"message\"])\n\n    return {\"response\": response}\n```\n\n### 2. RAG-Enhanced Agent\n\nBased on `GoogleCloudPlatform\u002Fgenerative-ai\u002Fgemini\u002Fuse-cases\u002Fretrieval-augmented-generation`:\n\n```python\nfrom vertexai.language_models import TextEmbeddingModel\nfrom vertexai.preview import rag\nfrom google.cloud import aiplatform\n\nclass RAGAgent:\n    \"\"\"\n    Agent with Retrieval Augmented Generation using Vertex AI Search\n    \"\"\"\n\n    def __init__(self, project_id: str, corpus_name: str):\n        self.project_id = project_id\n\n        # Create RAG corpus\n        self.corpus = rag.create_corpus(\n            display_name=corpus_name,\n            description=\"Knowledge base for RAG\"\n        )\n\n        # Initialize embedding model\n        self.embedding_model = TextEmbeddingModel.from_pretrained(\n            \"text-embedding-004\"\n        )\n\n        # Initialize Gemini model\n        self.model = GenerativeModel(\"gemini-1.5-pro-002\")\n\n    async def import_documents(self, gcs_uris: list):\n        \"\"\"Import documents into RAG corpus\"\"\"\n        import_job = rag.import_files(\n            corpus_name=self.corpus.name,\n            gcs_uris=gcs_uris,\n            chunk_size=512,\n            chunk_overlap=100\n        )\n\n        # Wait for import to complete\n        import_job.wait()\n\n        return import_job\n\n    async def query_with_rag(self, query: str, similarity_top_k: int = 5):\n        \"\"\"Query with RAG retrieval\"\"\"\n\n        # Retrieve relevant chunks\n        retrieval_response = rag.retrieval_query(\n            rag_resources=[\n                rag.RagResource(\n                    rag_corpus=self.corpus.name,\n                    similarity_top_k=similarity_top_k\n                )\n            ],\n            query=query\n        )\n\n        # Build context from retrieved chunks\n        context = \"\\n\\n\".join([\n            f\"Source: {chunk.source}\\nContent: {chunk.text}\"\n            for chunk in retrieval_response.contexts\n        ])\n\n        # Generate response with context\n        prompt = f\"\"\"Based on the following context, answer the question.\n\nContext:\n{context}\n\nQuestion: {query}\n\nAnswer:\"\"\"\n\n        response = self.model.generate_content(\n            prompt,\n            generation_config={\n                \"temperature\": 0.2,\n                \"max_output_tokens\": 1024,\n            }\n        )\n\n        return {\n            \"answer\": response.text,\n            \"sources\": [chunk.source for chunk in retrieval_response.contexts],\n            \"confidence\": retrieval_response.attribution_score\n        }\n```\n\n### 3. Multi-Modal Agent\n\nBased on `GoogleCloudPlatform\u002Fgenerative-ai\u002Fgemini\u002Fmultimodality`:\n\n```python\nfrom vertexai.generative_models import GenerativeModel, Part\nimport vertexai.preview.generative_models as generative_models\n\nclass MultiModalAgent:\n    \"\"\"\n    Agent that processes text, images, video, and audio\n    \"\"\"\n\n    def __init__(self):\n        self.model = GenerativeModel(\"gemini-1.5-flash-002\")\n\n    async def analyze_image(self, image_path: str, prompt: str):\n        \"\"\"Analyze image with text prompt\"\"\"\n        image = Part.from_uri(\n            uri=f\"gs:\u002F\u002Fyour-bucket\u002F{image_path}\",\n            mime_type=\"image\u002Fjpeg\"\n        )\n\n        response = self.model.generate_content([prompt, image])\n        return response.text\n\n    async def analyze_video(self, video_path: str, prompt: str):\n        \"\"\"Analyze video content\"\"\"\n        video = Part.from_uri(\n            uri=f\"gs:\u002F\u002Fyour-bucket\u002F{video_path}\",\n            mime_type=\"video\u002Fmp4\"\n        )\n\n        response = self.model.generate_content(\n            [prompt, video],\n            generation_config={\n                \"temperature\": 0.4,\n                \"max_output_tokens\": 2048,\n            }\n        )\n        return response.text\n\n    async def analyze_document(self, pdf_path: str):\n        \"\"\"Extract and analyze PDF document\"\"\"\n        document = Part.from_uri(\n            uri=f\"gs:\u002F\u002Fyour-bucket\u002F{pdf_path}\",\n            mime_type=\"application\u002Fpdf\"\n        )\n\n        prompt = \"\"\"Extract all key information from this document:\n        1. Main topics covered\n        2. Key findings or conclusions\n        3. Important data or statistics\n        4. Actionable recommendations\n        \"\"\"\n\n        response = self.model.generate_content([prompt, document])\n        return response.text\n\n    async def generate_code(self, description: str, language: str = \"python\"):\n        \"\"\"Generate code from natural language\"\"\"\n        prompt = f\"\"\"Generate {language} code for the following requirement:\n        {description}\n\n        Requirements:\n        - Include proper error handling\n        - Add comprehensive comments\n        - Follow best practices for {language}\n        - Make it production-ready\n        \"\"\"\n\n        response = self.model.generate_content(\n            prompt,\n            generation_config={\n                \"temperature\": 0.2,\n                \"max_output_tokens\": 4096,\n            }\n        )\n        return response.text\n```\n\n## Deployment Patterns\n\n### 1. Cloud Run Deployment\n\n```yaml\n# cloudbuild.yaml\nsteps:\n  # Build container\n  - name: 'gcr.io\u002Fcloud-builders\u002Fdocker'\n    args: ['build', '-t', 'gcr.io\u002F$PROJECT_ID\u002Fvertex-agent:$COMMIT_SHA', '.']\n\n  # Push to Container Registry\n  - name: 'gcr.io\u002Fcloud-builders\u002Fdocker'\n    args: ['push', 'gcr.io\u002F$PROJECT_ID\u002Fvertex-agent:$COMMIT_SHA']\n\n  # Deploy to Cloud Run\n  - name: 'gcr.io\u002Fgoogle.com\u002Fcloudsdktool\u002Fcloud-sdk'\n    entrypoint: gcloud\n    args:\n      - 'run'\n      - 'deploy'\n      - 'vertex-agent'\n      - '--image'\n      - 'gcr.io\u002F$PROJECT_ID\u002Fvertex-agent:$COMMIT_SHA'\n      - '--region'\n      - 'us-central1'\n      - '--platform'\n      - 'managed'\n      - '--allow-unauthenticated'\n      - '--set-env-vars'\n      - 'GCP_PROJECT=$PROJECT_ID'\n```\n\n```dockerfile\n# Dockerfile\nFROM python:3.11-slim\n\nWORKDIR \u002Fapp\n\n# Install dependencies\nCOPY requirements.txt .\nRUN pip install --no-cache-dir -r requirements.txt\n\n# Copy application\nCOPY . .\n\n# Run as non-root user\nRUN useradd -m -u 1000 agent && chown -R agent:agent \u002Fapp\nUSER agent\n\nEXPOSE 8080\n\nCMD [\"gunicorn\", \"--bind\", \":8080\", \"--workers\", \"1\", \"--threads\", \"8\", \"--timeout\", \"0\", \"main:app\"]\n```\n\n### 2. Vertex AI Endpoint Deployment\n\n```python\nfrom google.cloud import aiplatform\n\ndef deploy_to_vertex_endpoint():\n    \"\"\"Deploy model to Vertex AI Endpoint\"\"\"\n\n    aiplatform.init(project=\"your-project\", location=\"us-central1\")\n\n    # Upload model\n    model = aiplatform.Model.upload(\n        display_name=\"vertex-agent-model\",\n        artifact_uri=\"gs:\u002F\u002Fyour-bucket\u002Fmodel\",\n        serving_container_image_uri=\"us-docker.pkg.dev\u002Fvertex-ai\u002Fprediction\u002Fsklearn-cpu.1-3:latest\"\n    )\n\n    # Create endpoint\n    endpoint = aiplatform.Endpoint.create(\n        display_name=\"vertex-agent-endpoint\",\n    )\n\n    # Deploy model to endpoint\n    endpoint.deploy(\n        model=model,\n        deployed_model_display_name=\"vertex-agent-v1\",\n        machine_type=\"n1-standard-4\",\n        min_replica_count=1,\n        max_replica_count=5,\n        accelerator_type=\"NVIDIA_TESLA_T4\",\n        accelerator_count=1,\n    )\n\n    return endpoint\n```\n\n## Evaluation Framework\n\nBased on `GoogleCloudPlatform\u002Fgenerative-ai\u002Fgemini\u002Fevaluation`:\n\n```python\nfrom vertexai.preview.evaluation import EvalTask, MetricPromptTemplate\nimport pandas as pd\n\nclass AgentEvaluator:\n    \"\"\"\n    Evaluate agent performance using Vertex AI evaluation framework\n    \"\"\"\n\n    def __init__(self):\n        self.eval_dataset = self._load_eval_dataset()\n\n    def _load_eval_dataset(self):\n        \"\"\"Load evaluation dataset\"\"\"\n        return pd.DataFrame([\n            {\n                \"prompt\": \"What is the capital of France?\",\n                \"reference\": \"The capital of France is Paris.\",\n                \"context\": \"France is a country in Western Europe.\"\n            },\n            # Add more test cases\n        ])\n\n    async def evaluate_accuracy(self, agent):\n        \"\"\"Evaluate agent accuracy\"\"\"\n        eval_task = EvalTask(\n            dataset=self.eval_dataset,\n            metrics=[\n                \"rouge_l_sum\",\n                \"bleu\",\n                \"exact_match\",\n                MetricPromptTemplate(\n                    metric=\"custom_factuality\",\n                    metric_prompt_template=\"\"\"Rate the factual accuracy of the response.\n                    Reference: {reference}\n                    Response: {response}\n                    Score (0-1):\"\"\"\n                )\n            ]\n        )\n\n        # Run evaluation\n        results = []\n        for _, row in self.eval_dataset.iterrows():\n            response = await agent.process_request(row[\"prompt\"])\n            results.append({\n                \"prompt\": row[\"prompt\"],\n                \"reference\": row[\"reference\"],\n                \"response\": response\n            })\n\n        eval_result = eval_task.evaluate(\n            model=agent.model,\n            response_column=\"response\"\n        )\n\n        return eval_result.summary_metrics\n```\n\n## Monitoring & Observability\n\n```python\nfrom google.cloud import monitoring_v3\nfrom google.cloud import logging\nimport time\n\nclass AgentMonitor:\n    \"\"\"\n    Monitor agent performance and usage\n    \"\"\"\n\n    def __init__(self, project_id: str):\n        self.project_id = project_id\n        self.monitoring_client = monitoring_v3.MetricServiceClient()\n        self.logging_client = logging.Client()\n        self.logger = self.logging_client.logger(\"vertex-agent\")\n\n    def log_request(self, request_id: str, user_input: str, response: str, latency: float):\n        \"\"\"Log agent request\"\"\"\n        self.logger.log_struct({\n            \"request_id\": request_id,\n            \"timestamp\": time.time(),\n            \"user_input\": user_input,\n            \"response\": response[:500],  # Truncate long responses\n            \"latency_ms\": latency * 1000,\n            \"model\": \"gemini-1.5-pro-002\",\n            \"success\": True\n        })\n\n    def create_custom_metric(self, metric_name: str, value: float):\n        \"\"\"Create custom metric in Cloud Monitoring\"\"\"\n        project_name = f\"projects\u002F{self.project_id}\"\n\n        series = monitoring_v3.TimeSeries()\n        series.metric.type = f\"custom.googleapis.com\u002Fagent\u002F{metric_name}\"\n\n        now = time.time()\n        seconds = int(now)\n        nanos = int((now - seconds) * 10 ** 9)\n        interval = monitoring_v3.TimeInterval(\n            {\"end_time\": {\"seconds\": seconds, \"nanos\": nanos}}\n        )\n        point = monitoring_v3.Point({\n            \"interval\": interval,\n            \"value\": {\"double_value\": value}\n        })\n        series.points = [point]\n\n        self.monitoring_client.create_time_series(\n            name=project_name,\n            time_series=[series]\n        )\n\n    def create_dashboard(self):\n        \"\"\"Create monitoring dashboard\"\"\"\n        # Dashboard configuration\n        dashboard_config = {\n            \"displayName\": \"Vertex Agent Dashboard\",\n            \"widgets\": [\n                {\n                    \"title\": \"Request Latency\",\n                    \"xyChart\": {\n                        \"dataSets\": [{\n                            \"timeSeriesQuery\": {\n                                \"timeSeriesFilter\": {\n                                    \"filter\": 'metric.type=\"custom.googleapis.com\u002Fagent\u002Flatency\"'\n                                }\n                            }\n                        }]\n                    }\n                },\n                {\n                    \"title\": \"Error Rate\",\n                    \"xyChart\": {\n                        \"dataSets\": [{\n                            \"timeSeriesQuery\": {\n                                \"timeSeriesFilter\": {\n                                    \"filter\": 'metric.type=\"custom.googleapis.com\u002Fagent\u002Ferrors\"'\n                                }\n                            }\n                        }]\n                    }\n                }\n            ]\n        }\n        return dashboard_config\n```\n\n## Cost Optimization\n\n```python\nclass CostOptimizedAgent:\n    \"\"\"\n    Cost-optimized agent configuration\n    \"\"\"\n\n    def __init__(self):\n        # Model selection based on task complexity\n        self.models = {\n            \"simple\": \"gemini-1.5-flash-002\",  # Fastest and cheapest\n            \"standard\": \"gemini-1.5-pro-002\",   # Balanced\n            \"complex\": \"gemini-1.5-pro-002\",    # Most capable\n        }\n\n        # Caching for repeated queries\n        self.response_cache = {}\n\n    def select_model(self, query: str) -> str:\n        \"\"\"Select appropriate model based on query complexity\"\"\"\n        # Simple heuristic based on query length and keywords\n        complexity_score = len(query) \u002F 100\n\n        if \"analyze\" in query or \"explain\" in query:\n            complexity_score += 0.3\n        if \"code\" in query or \"implement\" in query:\n            complexity_score += 0.4\n\n        if complexity_score \u003C 0.3:\n            return self.models[\"simple\"]\n        elif complexity_score \u003C 0.7:\n            return self.models[\"standard\"]\n        else:\n            return self.models[\"complex\"]\n\n    async def process_with_caching(self, query: str):\n        \"\"\"Process query with response caching\"\"\"\n        # Check cache first\n        cache_key = hashlib.md5(query.encode()).hexdigest()\n        if cache_key in self.response_cache:\n            return self.response_cache[cache_key]\n\n        # Select optimal model\n        model_name = self.select_model(query)\n        model = GenerativeModel(model_name)\n\n        # Process query\n        response = model.generate_content(\n            query,\n            generation_config={\n                \"temperature\": 0.1,  # Lower temperature for consistency\n                \"max_output_tokens\": 1024,  # Limit output size\n            }\n        )\n\n        # Cache response\n        self.response_cache[cache_key] = response.text\n\n        return response.text\n```\n\n## Integration with Google Cloud Services\n\n### BigQuery Integration\n\n```python\nfrom google.cloud import bigquery\n\nclass BigQueryAgent:\n    \"\"\"Agent with BigQuery data access\"\"\"\n\n    def __init__(self, project_id: str):\n        self.bq_client = bigquery.Client(project=project_id)\n        self.model = GenerativeModel(\"gemini-1.5-pro-002\")\n\n    async def nl2sql(self, natural_language_query: str, dataset: str):\n        \"\"\"Convert natural language to SQL\"\"\"\n\n        # Get table schemas\n        tables = self.bq_client.list_tables(dataset)\n        schema_info = []\n        for table in tables:\n            table_ref = self.bq_client.get_table(table.reference)\n            schema_info.append(f\"Table: {table.table_id}\\nSchema: {table_ref.schema}\")\n\n        prompt = f\"\"\"Convert this natural language query to SQL:\n        Query: {natural_language_query}\n\n        Available tables and schemas:\n        {chr(10).join(schema_info)}\n\n        Return only the SQL query, no explanation.\n        \"\"\"\n\n        response = self.model.generate_content(prompt)\n        sql_query = response.text.strip()\n\n        # Execute query\n        query_job = self.bq_client.query(sql_query)\n        results = query_job.result()\n\n        return {\n            \"sql\": sql_query,\n            \"results\": [dict(row) for row in results],\n            \"total_rows\": results.total_rows\n        }\n```\n\n### Cloud Storage Integration\n\n```python\nfrom google.cloud import storage\n\nclass StorageAgent:\n    \"\"\"Agent with Cloud Storage access\"\"\"\n\n    def __init__(self, bucket_name: str):\n        self.storage_client = storage.Client()\n        self.bucket = self.storage_client.bucket(bucket_name)\n\n    async def process_documents(self, prefix: str):\n        \"\"\"Process all documents in a GCS prefix\"\"\"\n        blobs = self.bucket.list_blobs(prefix=prefix)\n\n        results = []\n        for blob in blobs:\n            if blob.name.endswith(('.pdf', '.txt', '.docx')):\n                # Download and process\n                content = blob.download_as_text()\n                analysis = await self.analyze_document(content)\n                results.append({\n                    \"file\": blob.name,\n                    \"analysis\": analysis\n                })\n\n        return results\n```\n\n## Best Practices\n\n### 1. Security\n\n```python\nfrom google.cloud import secretmanager\n\nclass SecureAgent:\n    \"\"\"Agent with security best practices\"\"\"\n\n    def __init__(self, project_id: str):\n        self.secret_client = secretmanager.SecretManagerServiceClient()\n        self.project_id = project_id\n\n    def get_secret(self, secret_id: str) -> str:\n        \"\"\"Get secret from Secret Manager\"\"\"\n        name = f\"projects\u002F{self.project_id}\u002Fsecrets\u002F{secret_id}\u002Fversions\u002Flatest\"\n        response = self.secret_client.access_secret_version(request={\"name\": name})\n        return response.payload.data.decode(\"UTF-8\")\n\n    def sanitize_input(self, user_input: str) -> str:\n        \"\"\"Sanitize user input\"\"\"\n        # Remove potential injection attempts\n        sanitized = user_input.replace(\"```\", \"\")\n        sanitized = sanitized.replace(\"\u003Cscript>\", \"\")\n        # Add more sanitization as needed\n        return sanitized\n```\n\n### 2. Error Handling\n\n```python\nfrom tenacity import retry, stop_after_attempt, wait_exponential\nimport logging\n\nclass ResilientAgent:\n    \"\"\"Agent with robust error handling\"\"\"\n\n    @retry(\n        stop=stop_after_attempt(3),\n        wait=wait_exponential(multiplier=1, min=4, max=60)\n    )\n    async def process_with_retry(self, request):\n        \"\"\"Process with automatic retry\"\"\"\n        try:\n            response = await self._process(request)\n            return response\n        except Exception as e:\n            logging.error(f\"Processing failed: {e}\")\n            raise\n```\n\n## Examples Repository\n\nComplete working examples from Google Cloud repositories:\n\n1. **Text Generation** - `\u002Fgemini\u002Ffunction-calling\u002F`\n2. **RAG Implementation** - `\u002Fgemini\u002Fuse-cases\u002Fretrieval-augmented-generation\u002F`\n3. **Multi-modal Processing** - `\u002Fgemini\u002Fmultimodality\u002F`\n4. **Agent Builder** - `\u002Fagent-builder\u002F`\n5. **Production Templates** - From `agent-starter-pack`\n\n## Resources\n\n- [Vertex AI Documentation](https:\u002F\u002Fcloud.google.com\u002Fvertex-ai\u002Fdocs)\n- [Gemini API Reference](https:\u002F\u002Fcloud.google.com\u002Fvertex-ai\u002Fgenerative-ai\u002Fdocs\u002Fmodel-reference\u002Fgemini)\n- [Agent Builder Guide](https:\u002F\u002Fcloud.google.com\u002Fgenerative-ai-app-builder\u002Fdocs\u002Fagent-builder)\n- [GitHub: GoogleCloudPlatform\u002Fgenerative-ai](https:\u002F\u002Fgithub.com\u002FGoogleCloudPlatform\u002Fgenerative-ai)\n- [GitHub: GoogleCloudPlatform\u002Fagent-starter-pack](https:\u002F\u002Fgithub.com\u002FGoogleCloudPlatform\u002Fagent-starter-pack)\n\n---\n\n**Version:** 1.0.0\n**Last Updated:** October 2025\n**Author:** Jeremy Longshore\n**Based on:** Official Google Cloud repositories\n**License:** MIT","# Vertex AI Agent Builder Skill\n\n## Overview\n\nThis skill provides production-ready scaffolding and deployment for generative AI agents using Google Cloud's Vertex AI platform. Built on actual Google Cloud source code from `GoogleCloudPlatform\u002Fgenerative-ai` and `agent-starter-pack` repositories, it offers:\n\n- **Gemini Model Integration** (1.5 Pro, 1.5 Flash, experimental models)\n- **Multi-modal Capabilities** (text, image, video, audio processing)\n- **RAG Implementation** (Retrieval Augmented Generation with Vector Search)\n- **Function Calling** (Tool use with Gemini models)\n- **Production Deployment** (Cloud Run, Vertex AI Endpoints)\n- **Evaluation Framework** (AutoSxS, ROUGE, custom metrics)\n- **Observability** (Cloud Logging, Monitoring, Trace)\n\n## Installation\n\n```bash\n# Install Google Cloud SDK\ncurl https:\u002F\u002Fsdk.cloud.google.com | bash\nexec -l $SHELL\ngcloud init\n\n# Install Python SDK\npip install google-cloud-aiplatform>=1.38.0\npip install vertexai>=1.46.0\npip install google-generativeai>=0.3.2\n\n# Clone source repositories\ngit clone https:\u002F\u002Fgithub.com\u002FGoogleCloudPlatform\u002Fgenerative-ai.git\ngit clone https:\u002F\u002Fgithub.com\u002FGoogleCloudPlatform\u002Fagent-starter-pack.git\ngit clone https:\u002F\u002Fgithub.com\u002FGoogleCloudPlatform\u002Fvertex-ai-samples.git\n\n# Install this plugin\n\u002Fplugin install jeremy-vertex-ai@jeremylongshore\n```\n\n## Quick Start (5 Minutes)\n\n### Create Your First Vertex AI Agent\n\n```python\nimport vertexai\nfrom vertexai.generative_models import GenerativeModel, ChatSession\nfrom vertexai.preview.generative_models import grounding\n\n# Initialize Vertex AI\nvertexai.init(project=\"your-project-id\", location=\"us-central1\")\n\n# Create Gemini model\nmodel = GenerativeModel(\n    \"gemini-1.5-pro-002\",\n    system_instruction=\"\"\"You are a helpful AI assistant that can:\n    - Search the web for information\n    - Analyze documents and images\n    - Execute Python code\n    - Call external APIs\n    \"\"\"\n)\n\n# Start chat session\nchat = model.start_chat()\n\n# Send message with grounding\nresponse = chat.send_message(\n    \"What are the latest developments in quantum computing?\",\n    generation_config={\n        \"temperature\": 0.3,\n        \"max_output_tokens\": 2048,\n        \"top_p\": 0.95,\n    },\n    safety_settings={\n        \"HARM_CATEGORY_HATE_SPEECH\": \"BLOCK_MEDIUM_AND_ABOVE\",\n        \"HARM_CATEGORY_DANGEROUS_CONTENT\": \"BLOCK_MEDIUM_AND_ABOVE\",\n    },\n    tools=[grounding.Tool(google_search_retrieval=grounding.GoogleSearchRetrieval())]\n)\n\nprint(response.text)\n```\n\n## Agent Patterns\n\n### 1. Production Agent with Agent Builder\n\nBased on `GoogleCloudPlatform\u002Fagent-starter-pack`:\n\n```python\nfrom vertexai.preview import agents\nfrom vertexai.preview.generative_models import Tool, FunctionDeclaration\nimport functions_framework\n\nclass ProductionAgent:\n    \"\"\"\n    Production-ready agent using Vertex AI Agent Builder\n    \"\"\"\n\n    def __init__(self, project_id: str, location: str = \"us-central1\"):\n        self.project_id = project_id\n        self.location = location\n\n        # Initialize agent\n        self.agent = agents.Agent.create(\n            project=project_id,\n            location=location,\n            display_name=\"production-agent\",\n            description=\"Production-ready agent with tools and RAG\",\n            model=\"gemini-1.5-pro-002\",\n            tools=self._create_tools(),\n            system_instruction=self._get_system_instruction()\n        )\n\n    def _create_tools(self):\n        \"\"\"Create function calling tools\"\"\"\n        return [\n            Tool(function_declarations=[\n                FunctionDeclaration(\n                    name=\"search_knowledge_base\",\n                    description=\"Search internal knowledge base\",\n                    parameters={\n                        \"type\": \"object\",\n                        \"properties\": {\n                            \"query\": {\"type\": \"string\"},\n                            \"top_k\": {\"type\": \"integer\", \"default\": 5}\n                        }\n                    }\n                ),\n                FunctionDeclaration(\n                    name=\"execute_sql\",\n                    description=\"Execute SQL query on BigQuery\",\n                    parameters={\n                        \"type\": \"object\",\n                        \"properties\": {\n                            \"query\": {\"type\": \"string\"},\n                            \"dataset\": {\"type\": \"string\"}\n                        }\n                    }\n                ),\n                FunctionDeclaration(\n                    name=\"send_email\",\n                    description=\"Send email notification\",\n                    parameters={\n                        \"type\": \"object\",\n                        \"properties\": {\n                            \"to\": {\"type\": \"string\"},\n                            \"subject\": {\"type\": \"string\"},\n                            \"body\": {\"type\": \"string\"}\n                        }\n                    }\n                )\n            ])\n        ]\n\n    def _get_system_instruction(self):\n        \"\"\"Get system instruction for agent\"\"\"\n        return \"\"\"You are a production AI agent that helps users with:\n        1. Information retrieval from knowledge bases\n        2. Data analysis using BigQuery\n        3. Automated communications\n\n        Always verify user intent before executing critical operations.\n        Provide clear explanations of what you're doing and why.\n        \"\"\"\n\n    async def process_request(self, user_input: str):\n        \"\"\"Process user request\"\"\"\n        session = self.agent.start_session()\n        response = await session.send_message(user_input)\n\n        # Handle function calls\n        if response.function_calls:\n            for func_call in response.function_calls:\n                result = await self._execute_function(\n                    func_call.name,\n                    func_call.args\n                )\n                # Send function result back to model\n                response = await session.send_message(\n                    content=None,\n                    function_responses=[{\n                        \"name\": func_call.name,\n                        \"response\": result\n                    }]\n                )\n\n        return response.text\n\n    async def _execute_function(self, name: str, args: dict):\n        \"\"\"Execute function call\"\"\"\n        if name == \"search_knowledge_base\":\n            return await self._search_kb(args[\"query\"], args.get(\"top_k\", 5))\n        elif name == \"execute_sql\":\n            return await self._execute_bigquery(args[\"query\"], args[\"dataset\"])\n        elif name == \"send_email\":\n            return await self._send_email(args[\"to\"], args[\"subject\"], args[\"body\"])\n\n# Deploy as Cloud Function\n@functions_framework.http\ndef agent_endpoint(request):\n    \"\"\"HTTP Cloud Function for agent\"\"\"\n    agent = ProductionAgent(\n        project_id=\"your-project\",\n        location=\"us-central1\"\n    )\n\n    request_json = request.get_json()\n    response = agent.process_request(request_json[\"message\"])\n\n    return {\"response\": response}\n```\n\n### 2. RAG-Enhanced Agent\n\nBased on `GoogleCloudPlatform\u002Fgenerative-ai\u002Fgemini\u002Fuse-cases\u002Fretrieval-augmented-generation`:\n\n```python\nfrom vertexai.language_models import TextEmbeddingModel\nfrom vertexai.preview import rag\nfrom google.cloud import aiplatform\n\nclass RAGAgent:\n    \"\"\"\n    Agent with Retrieval Augmented Generation using Vertex AI Search\n    \"\"\"\n\n    def __init__(self, project_id: str, corpus_name: str):\n        self.project_id = project_id\n\n        # Create RAG corpus\n        self.corpus = rag.create_corpus(\n            display_name=corpus_name,\n            description=\"Knowledge base for RAG\"\n        )\n\n        # Initialize embedding model\n        self.embedding_model = TextEmbeddingModel.from_pretrained(\n            \"text-embedding-004\"\n        )\n\n        # Initialize Gemini model\n        self.model = GenerativeModel(\"gemini-1.5-pro-002\")\n\n    async def import_documents(self, gcs_uris: list):\n        \"\"\"Import documents into RAG corpus\"\"\"\n        import_job = rag.import_files(\n            corpus_name=self.corpus.name,\n            gcs_uris=gcs_uris,\n            chunk_size=512,\n            chunk_overlap=100\n        )\n\n        # Wait for import to complete\n        import_job.wait()\n\n        return import_job\n\n    async def query_with_rag(self, query: str, similarity_top_k: int = 5):\n        \"\"\"Query with RAG retrieval\"\"\"\n\n        # Retrieve relevant chunks\n        retrieval_response = rag.retrieval_query(\n            rag_resources=[\n                rag.RagResource(\n                    rag_corpus=self.corpus.name,\n                    similarity_top_k=similarity_top_k\n                )\n            ],\n            query=query\n        )\n\n        # Build context from retrieved chunks\n        context = \"\\n\\n\".join([\n            f\"Source: {chunk.source}\\nContent: {chunk.text}\"\n            for chunk in retrieval_response.contexts\n        ])\n\n        # Generate response with context\n        prompt = f\"\"\"Based on the following context, answer the question.\n\nContext:\n{context}\n\nQuestion: {query}\n\nAnswer:\"\"\"\n\n        response = self.model.generate_content(\n            prompt,\n            generation_config={\n                \"temperature\": 0.2,\n                \"max_output_tokens\": 1024,\n            }\n        )\n\n        return {\n            \"answer\": response.text,\n            \"sources\": [chunk.source for chunk in retrieval_response.contexts],\n            \"confidence\": retrieval_response.attribution_score\n        }\n```\n\n### 3. Multi-Modal Agent\n\nBased on `GoogleCloudPlatform\u002Fgenerative-ai\u002Fgemini\u002Fmultimodality`:\n\n```python\nfrom vertexai.generative_models import GenerativeModel, Part\nimport vertexai.preview.generative_models as generative_models\n\nclass MultiModalAgent:\n    \"\"\"\n    Agent that processes text, images, video, and audio\n    \"\"\"\n\n    def __init__(self):\n        self.model = GenerativeModel(\"gemini-1.5-flash-002\")\n\n    async def analyze_image(self, image_path: str, prompt: str):\n        \"\"\"Analyze image with text prompt\"\"\"\n        image = Part.from_uri(\n            uri=f\"gs:\u002F\u002Fyour-bucket\u002F{image_path}\",\n            mime_type=\"image\u002Fjpeg\"\n        )\n\n        response = self.model.generate_content([prompt, image])\n        return response.text\n\n    async def analyze_video(self, video_path: str, prompt: str):\n        \"\"\"Analyze video content\"\"\"\n        video = Part.from_uri(\n            uri=f\"gs:\u002F\u002Fyour-bucket\u002F{video_path}\",\n            mime_type=\"video\u002Fmp4\"\n        )\n\n        response = self.model.generate_content(\n            [prompt, video],\n            generation_config={\n                \"temperature\": 0.4,\n                \"max_output_tokens\": 2048,\n            }\n        )\n        return response.text\n\n    async def analyze_document(self, pdf_path: str):\n        \"\"\"Extract and analyze PDF document\"\"\"\n        document = Part.from_uri(\n            uri=f\"gs:\u002F\u002Fyour-bucket\u002F{pdf_path}\",\n            mime_type=\"application\u002Fpdf\"\n        )\n\n        prompt = \"\"\"Extract all key information from this document:\n        1. Main topics covered\n        2. Key findings or conclusions\n        3. Important data or statistics\n        4. Actionable recommendations\n        \"\"\"\n\n        response = self.model.generate_content([prompt, document])\n        return response.text\n\n    async def generate_code(self, description: str, language: str = \"python\"):\n        \"\"\"Generate code from natural language\"\"\"\n        prompt = f\"\"\"Generate {language} code for the following requirement:\n        {description}\n\n        Requirements:\n        - Include proper error handling\n        - Add comprehensive comments\n        - Follow best practices for {language}\n        - Make it production-ready\n        \"\"\"\n\n        response = self.model.generate_content(\n            prompt,\n            generation_config={\n                \"temperature\": 0.2,\n                \"max_output_tokens\": 4096,\n            }\n        )\n        return response.text\n```\n\n## Deployment Patterns\n\n### 1. Cloud Run Deployment\n\n```yaml\n# cloudbuild.yaml\nsteps:\n  # Build container\n  - name: 'gcr.io\u002Fcloud-builders\u002Fdocker'\n    args: ['build', '-t', 'gcr.io\u002F$PROJECT_ID\u002Fvertex-agent:$COMMIT_SHA', '.']\n\n  # Push to Container Registry\n  - name: 'gcr.io\u002Fcloud-builders\u002Fdocker'\n    args: ['push', 'gcr.io\u002F$PROJECT_ID\u002Fvertex-agent:$COMMIT_SHA']\n\n  # Deploy to Cloud Run\n  - name: 'gcr.io\u002Fgoogle.com\u002Fcloudsdktool\u002Fcloud-sdk'\n    entrypoint: gcloud\n    args:\n      - 'run'\n      - 'deploy'\n      - 'vertex-agent'\n      - '--image'\n      - 'gcr.io\u002F$PROJECT_ID\u002Fvertex-agent:$COMMIT_SHA'\n      - '--region'\n      - 'us-central1'\n      - '--platform'\n      - 'managed'\n      - '--allow-unauthenticated'\n      - '--set-env-vars'\n      - 'GCP_PROJECT=$PROJECT_ID'\n```\n\n```dockerfile\n# Dockerfile\nFROM python:3.11-slim\n\nWORKDIR \u002Fapp\n\n# Install dependencies\nCOPY requirements.txt .\nRUN pip install --no-cache-dir -r requirements.txt\n\n# Copy application\nCOPY . .\n\n# Run as non-root user\nRUN useradd -m -u 1000 agent && chown -R agent:agent \u002Fapp\nUSER agent\n\nEXPOSE 8080\n\nCMD [\"gunicorn\", \"--bind\", \":8080\", \"--workers\", \"1\", \"--threads\", \"8\", \"--timeout\", \"0\", \"main:app\"]\n```\n\n### 2. Vertex AI Endpoint Deployment\n\n```python\nfrom google.cloud import aiplatform\n\ndef deploy_to_vertex_endpoint():\n    \"\"\"Deploy model to Vertex AI Endpoint\"\"\"\n\n    aiplatform.init(project=\"your-project\", location=\"us-central1\")\n\n    # Upload model\n    model = aiplatform.Model.upload(\n        display_name=\"vertex-agent-model\",\n        artifact_uri=\"gs:\u002F\u002Fyour-bucket\u002Fmodel\",\n        serving_container_image_uri=\"us-docker.pkg.dev\u002Fvertex-ai\u002Fprediction\u002Fsklearn-cpu.1-3:latest\"\n    )\n\n    # Create endpoint\n    endpoint = aiplatform.Endpoint.create(\n        display_name=\"vertex-agent-endpoint\",\n    )\n\n    # Deploy model to endpoint\n    endpoint.deploy(\n        model=model,\n        deployed_model_display_name=\"vertex-agent-v1\",\n        machine_type=\"n1-standard-4\",\n        min_replica_count=1,\n        max_replica_count=5,\n        accelerator_type=\"NVIDIA_TESLA_T4\",\n        accelerator_count=1,\n    )\n\n    return endpoint\n```\n\n## Evaluation Framework\n\nBased on `GoogleCloudPlatform\u002Fgenerative-ai\u002Fgemini\u002Fevaluation`:\n\n```python\nfrom vertexai.preview.evaluation import EvalTask, MetricPromptTemplate\nimport pandas as pd\n\nclass AgentEvaluator:\n    \"\"\"\n    Evaluate agent performance using Vertex AI evaluation framework\n    \"\"\"\n\n    def __init__(self):\n        self.eval_dataset = self._load_eval_dataset()\n\n    def _load_eval_dataset(self):\n        \"\"\"Load evaluation dataset\"\"\"\n        return pd.DataFrame([\n            {\n                \"prompt\": \"What is the capital of France?\",\n                \"reference\": \"The capital of France is Paris.\",\n                \"context\": \"France is a country in Western Europe.\"\n            },\n            # Add more test cases\n        ])\n\n    async def evaluate_accuracy(self, agent):\n        \"\"\"Evaluate agent accuracy\"\"\"\n        eval_task = EvalTask(\n            dataset=self.eval_dataset,\n            metrics=[\n                \"rouge_l_sum\",\n                \"bleu\",\n                \"exact_match\",\n                MetricPromptTemplate(\n                    metric=\"custom_factuality\",\n                    metric_prompt_template=\"\"\"Rate the factual accuracy of the response.\n                    Reference: {reference}\n                    Response: {response}\n                    Score (0-1):\"\"\"\n                )\n            ]\n        )\n\n        # Run evaluation\n        results = []\n        for _, row in self.eval_dataset.iterrows():\n            response = await agent.process_request(row[\"prompt\"])\n            results.append({\n                \"prompt\": row[\"prompt\"],\n                \"reference\": row[\"reference\"],\n                \"response\": response\n            })\n\n        eval_result = eval_task.evaluate(\n            model=agent.model,\n            response_column=\"response\"\n        )\n\n        return eval_result.summary_metrics\n```\n\n## Monitoring & Observability\n\n```python\nfrom google.cloud import monitoring_v3\nfrom google.cloud import logging\nimport time\n\nclass AgentMonitor:\n    \"\"\"\n    Monitor agent performance and usage\n    \"\"\"\n\n    def __init__(self, project_id: str):\n        self.project_id = project_id\n        self.monitoring_client = monitoring_v3.MetricServiceClient()\n        self.logging_client = logging.Client()\n        self.logger = self.logging_client.logger(\"vertex-agent\")\n\n    def log_request(self, request_id: str, user_input: str, response: str, latency: float):\n        \"\"\"Log agent request\"\"\"\n        self.logger.log_struct({\n            \"request_id\": request_id,\n            \"timestamp\": time.time(),\n            \"user_input\": user_input,\n            \"response\": response[:500],  # Truncate long responses\n            \"latency_ms\": latency * 1000,\n            \"model\": \"gemini-1.5-pro-002\",\n            \"success\": True\n        })\n\n    def create_custom_metric(self, metric_name: str, value: float):\n        \"\"\"Create custom metric in Cloud Monitoring\"\"\"\n        project_name = f\"projects\u002F{self.project_id}\"\n\n        series = monitoring_v3.TimeSeries()\n        series.metric.type = f\"custom.googleapis.com\u002Fagent\u002F{metric_name}\"\n\n        now = time.time()\n        seconds = int(now)\n        nanos = int((now - seconds) * 10 ** 9)\n        interval = monitoring_v3.TimeInterval(\n            {\"end_time\": {\"seconds\": seconds, \"nanos\": nanos}}\n        )\n        point = monitoring_v3.Point({\n            \"interval\": interval,\n            \"value\": {\"double_value\": value}\n        })\n        series.points = [point]\n\n        self.monitoring_client.create_time_series(\n            name=project_name,\n            time_series=[series]\n        )\n\n    def create_dashboard(self):\n        \"\"\"Create monitoring dashboard\"\"\"\n        # Dashboard configuration\n        dashboard_config = {\n            \"displayName\": \"Vertex Agent Dashboard\",\n            \"widgets\": [\n                {\n                    \"title\": \"Request Latency\",\n                    \"xyChart\": {\n                        \"dataSets\": [{\n                            \"timeSeriesQuery\": {\n                                \"timeSeriesFilter\": {\n                                    \"filter\": 'metric.type=\"custom.googleapis.com\u002Fagent\u002Flatency\"'\n                                }\n                            }\n                        }]\n                    }\n                },\n                {\n                    \"title\": \"Error Rate\",\n                    \"xyChart\": {\n                        \"dataSets\": [{\n                            \"timeSeriesQuery\": {\n                                \"timeSeriesFilter\": {\n                                    \"filter\": 'metric.type=\"custom.googleapis.com\u002Fagent\u002Ferrors\"'\n                                }\n                            }\n                        }]\n                    }\n                }\n            ]\n        }\n        return dashboard_config\n```\n\n## Cost Optimization\n\n```python\nclass CostOptimizedAgent:\n    \"\"\"\n    Cost-optimized agent configuration\n    \"\"\"\n\n    def __init__(self):\n        # Model selection based on task complexity\n        self.models = {\n            \"simple\": \"gemini-1.5-flash-002\",  # Fastest and cheapest\n            \"standard\": \"gemini-1.5-pro-002\",   # Balanced\n            \"complex\": \"gemini-1.5-pro-002\",    # Most capable\n        }\n\n        # Caching for repeated queries\n        self.response_cache = {}\n\n    def select_model(self, query: str) -> str:\n        \"\"\"Select appropriate model based on query complexity\"\"\"\n        # Simple heuristic based on query length and keywords\n        complexity_score = len(query) \u002F 100\n\n        if \"analyze\" in query or \"explain\" in query:\n            complexity_score += 0.3\n        if \"code\" in query or \"implement\" in query:\n            complexity_score += 0.4\n\n        if complexity_score \u003C 0.3:\n            return self.models[\"simple\"]\n        elif complexity_score \u003C 0.7:\n            return self.models[\"standard\"]\n        else:\n            return self.models[\"complex\"]\n\n    async def process_with_caching(self, query: str):\n        \"\"\"Process query with response caching\"\"\"\n        # Check cache first\n        cache_key = hashlib.md5(query.encode()).hexdigest()\n        if cache_key in self.response_cache:\n            return self.response_cache[cache_key]\n\n        # Select optimal model\n        model_name = self.select_model(query)\n        model = GenerativeModel(model_name)\n\n        # Process query\n        response = model.generate_content(\n            query,\n            generation_config={\n                \"temperature\": 0.1,  # Lower temperature for consistency\n                \"max_output_tokens\": 1024,  # Limit output size\n            }\n        )\n\n        # Cache response\n        self.response_cache[cache_key] = response.text\n\n        return response.text\n```\n\n## Integration with Google Cloud Services\n\n### BigQuery Integration\n\n```python\nfrom google.cloud import bigquery\n\nclass BigQueryAgent:\n    \"\"\"Agent with BigQuery data access\"\"\"\n\n    def __init__(self, project_id: str):\n        self.bq_client = bigquery.Client(project=project_id)\n        self.model = GenerativeModel(\"gemini-1.5-pro-002\")\n\n    async def nl2sql(self, natural_language_query: str, dataset: str):\n        \"\"\"Convert natural language to SQL\"\"\"\n\n        # Get table schemas\n        tables = self.bq_client.list_tables(dataset)\n        schema_info = []\n        for table in tables:\n            table_ref = self.bq_client.get_table(table.reference)\n            schema_info.append(f\"Table: {table.table_id}\\nSchema: {table_ref.schema}\")\n\n        prompt = f\"\"\"Convert this natural language query to SQL:\n        Query: {natural_language_query}\n\n        Available tables and schemas:\n        {chr(10).join(schema_info)}\n\n        Return only the SQL query, no explanation.\n        \"\"\"\n\n        response = self.model.generate_content(prompt)\n        sql_query = response.text.strip()\n\n        # Execute query\n        query_job = self.bq_client.query(sql_query)\n        results = query_job.result()\n\n        return {\n            \"sql\": sql_query,\n            \"results\": [dict(row) for row in results],\n            \"total_rows\": results.total_rows\n        }\n```\n\n### Cloud Storage Integration\n\n```python\nfrom google.cloud import storage\n\nclass StorageAgent:\n    \"\"\"Agent with Cloud Storage access\"\"\"\n\n    def __init__(self, bucket_name: str):\n        self.storage_client = storage.Client()\n        self.bucket = self.storage_client.bucket(bucket_name)\n\n    async def process_documents(self, prefix: str):\n        \"\"\"Process all documents in a GCS prefix\"\"\"\n        blobs = self.bucket.list_blobs(prefix=prefix)\n\n        results = []\n        for blob in blobs:\n            if blob.name.endswith(('.pdf', '.txt', '.docx')):\n                # Download and process\n                content = blob.download_as_text()\n                analysis = await self.analyze_document(content)\n                results.append({\n                    \"file\": blob.name,\n                    \"analysis\": analysis\n                })\n\n        return results\n```\n\n## Best Practices\n\n### 1. Security\n\n```python\nfrom google.cloud import secretmanager\n\nclass SecureAgent:\n    \"\"\"Agent with security best practices\"\"\"\n\n    def __init__(self, project_id: str):\n        self.secret_client = secretmanager.SecretManagerServiceClient()\n        self.project_id = project_id\n\n    def get_secret(self, secret_id: str) -> str:\n        \"\"\"Get secret from Secret Manager\"\"\"\n        name = f\"projects\u002F{self.project_id}\u002Fsecrets\u002F{secret_id}\u002Fversions\u002Flatest\"\n        response = self.secret_client.access_secret_version(request={\"name\": name})\n        return response.payload.data.decode(\"UTF-8\")\n\n    def sanitize_input(self, user_input: str) -> str:\n        \"\"\"Sanitize user input\"\"\"\n        # Remove potential injection attempts\n        sanitized = user_input.replace(\"```\", \"\")\n        sanitized = sanitized.replace(\"\u003Cscript>\", \"\")\n        # Add more sanitization as needed\n        return sanitized\n```\n\n### 2. Error Handling\n\n```python\nfrom tenacity import retry, stop_after_attempt, wait_exponential\nimport logging\n\nclass ResilientAgent:\n    \"\"\"Agent with robust error handling\"\"\"\n\n    @retry(\n        stop=stop_after_attempt(3),\n        wait=wait_exponential(multiplier=1, min=4, max=60)\n    )\n    async def process_with_retry(self, request):\n        \"\"\"Process with automatic retry\"\"\"\n        try:\n            response = await self._process(request)\n            return response\n        except Exception as e:\n            logging.error(f\"Processing failed: {e}\")\n            raise\n```\n\n## Examples Repository\n\nComplete working examples from Google Cloud repositories:\n\n1. **Text Generation** - `\u002Fgemini\u002Ffunction-calling\u002F`\n2. **RAG Implementation** - `\u002Fgemini\u002Fuse-cases\u002Fretrieval-augmented-generation\u002F`\n3. **Multi-modal Processing** - `\u002Fgemini\u002Fmultimodality\u002F`\n4. **Agent Builder** - `\u002Fagent-builder\u002F`\n5. **Production Templates** - From `agent-starter-pack`\n\n## Resources\n\n- [Vertex AI Documentation](https:\u002F\u002Fcloud.google.com\u002Fvertex-ai\u002Fdocs)\n- [Gemini API Reference](https:\u002F\u002Fcloud.google.com\u002Fvertex-ai\u002Fgenerative-ai\u002Fdocs\u002Fmodel-reference\u002Fgemini)\n- [Agent Builder Guide](https:\u002F\u002Fcloud.google.com\u002Fgenerative-ai-app-builder\u002Fdocs\u002Fagent-builder)\n- [GitHub: GoogleCloudPlatform\u002Fgenerative-ai](https:\u002F\u002Fgithub.com\u002FGoogleCloudPlatform\u002Fgenerative-ai)\n- [GitHub: GoogleCloudPlatform\u002Fagent-starter-pack](https:\u002F\u002Fgithub.com\u002FGoogleCloudPlatform\u002Fagent-starter-pack)\n\n---\n\n**Version:** 1.0.0\n**Last Updated:** October 2025\n**Author:** Jeremy Longshore\n**Based on:** Official Google Cloud repositories\n**License:** MIT",{"name":5,"license":14,"description":7,"allowed-tools":43},[44,45,46,47,32],"Read","Write","Edit","Grep","main","f2ec4b3b9133d34eeaf9b38e4b0a97e8e5705a7f","benchmarks\u002Ffinal\u002Fskills\u002Fasset1__BbgnsurfTech--vertex-agent-builder",0,"https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard","https:\u002F\u002Fgithub.com\u002FJSGforever","2026-08-29 18:27:56",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add JSGforever\u002Fskillguard --skill vertex-agent-builder",{"tool":61,"command":62},"bunx","bunx skills add JSGforever\u002Fskillguard --skill vertex-agent-builder",{"tool":64,"command":65},"pnpm","pnpm dlx skills add JSGforever\u002Fskillguard --skill vertex-agent-builder","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__BbgnsurfTech--vertex-agent-builder\u002FSKILL.md",true,[],[70,98,108,134,153,172],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":74,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":38},"01M71HY2SNXBA9Q00WZDTZQ31Z","skillguard-codex-scanner","Hybrid deterministic+LLM agent-skill security scanner. Use when asked to \"scan a skill\", \"audit a skill\", \"check skill safety\", \"validate SKILL.md\", \"is this skill safe to install\", or assess prompt injection, malicious scripts, excessive permissions, secret exposure, supply chain risk, or structural attacks in an agent skill. Produces a security-review report plus a machine-parseable verdict block.","GPL-3.0","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fsrc\u002Fskillguard\u002Fstatic_scanner\u002Fskillguard-codex-scanner\u002FSKILL.md",[],[78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97],"scanner","skillguard codex scanner","skillguard","codex","chain","skill security","security-review","review report","structural","secret","prompt injection","security scanner","when","review","malicious","permissions","exposure","audit","scripts","safe",{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":38},"01M71HY0SPKTT3S27BC2HPAC5M","data-exfiltrator","Analyzes data files","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Fsmoke-one-skill\u002Fasset1__cisco-ai-defense--data-exfiltrator\u002FSKILL.md",[],[105,106,107],"data","data exfiltrator","files",{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":74,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":38},"01M71HXVS9EMN44BGDW215FZ72","real-time-collaboration-engine","Build real-time collaborative editing with WebSockets, OT\u002FCRDT conflict resolution, and presence awareness. Implements cursor tracking, optimistic updates, and offline sync. Use for collaborative editors, whiteboards, video editing. Activate on \"real-time collaboration\", \"WebSocket sync\", \"multiplayer editing\", \"CRDT\", \"presence awareness\". NOT for simple chat, request-response APIs, or single-user apps.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__curiositech--real-time-collaboration-engine\u002FSKILL.md",[],[115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,32,130,131,132,133],"time","real time collaboration engine","real time collaboration","collaboration","engine","real time","Video","reliability","video editing","performance","conflict resolution","presence","access","apps","updates","activate","optimizer","react","streaming",{"skillNo":135,"name":136,"nameZh":6,"description":137,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":74,"licenseFileUrl":6,"sourceHtmlUrl":138,"categories":139,"keywords":140,"publishedAt":38},"01M71HXP6CTY4KFN0QVMMN0V7J","react-performance-optimizer","Optimize React apps for 60fps performance. Implements memoization, virtualization, code splitting, bundle optimization. Use for slow renders, large lists, bundle bloat. Activate on \"React performance\", \"slow render\", \"useMemo\", \"bundle size\", \"virtualization\". NOT for backend optimization, non-React frameworks, or premature optimization.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__curiositech--react-performance-optimizer\u002FSKILL.md",[],[124,141,131,132,142,143,144,145,146,147,115,148,149,128,32,150,130,133,151,152],"react performance optimizer","react performance","performance optimizer","app","nextjs","expert","re","render","2025","code","router","strategies",{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":74,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":159,"publishedAt":38},"01M71HXH7QXSQB4QTDZ7SP7YXQ","llm-streaming-response-handler","Build production LLM streaming UIs with Server-Sent Events, real-time token display, cancellation, error recovery. Handles OpenAI\u002FAnthropic\u002FClaude streaming APIs. Use for chatbots, AI assistants, real-time text generation. Activate on \"LLM streaming\", \"SSE\", \"token stream\", \"chat UI\", \"real-time AI\". NOT for batch processing, non-streaming APIs, or WebSocket bidirectional chat.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__curiositech--llm-streaming-response-handler\u002FSKILL.md",[],[160,133,161,162,163,164,124,115,165,166,167,32,130,131,168,132,169,170,171,28],"llm streaming response handler","handler","error","processing","retry","chat ui","error recovery","critical","batch","display","text","server",{"skillNo":173,"name":174,"nameZh":6,"description":175,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":74,"licenseFileUrl":6,"sourceHtmlUrl":176,"categories":177,"keywords":178,"publishedAt":38},"01M71HXCB0E1YRKYW1Y8T0Y106","github-actions-pipeline-builder","Build production CI\u002FCD pipelines with GitHub Actions. Implements matrix builds, caching, deployments, testing, security scanning. Use for automated testing, deployments, release workflows. Activate on \"GitHub Actions\", \"CI\u002FCD\", \"workflow\", \"deployment pipeline\", \"automated testing\". NOT for Jenkins\u002FCircleCI, manual deployments, or non-GitHub repositories.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__curiositech--github-actions-pipeline-builder\u002FSKILL.md",[],[179,180,181,182,183,20,184,122,146,185,186,187,130,152,188,28,189,27,26,190],"github actions pipeline builder","actions","github actions","pipeline builder","github","pipeline","testing","ci","workflows","run","release","git"]