bigquery-udfs
Creates, deploys, and troubleshoots BigQuery User-Defined Functions (UDFs) and Remote Functions across SQL, JavaScript, Python, and Cloud Run endpoints
Install / Use
npx skills add google/skills --skill bigquery-udfsInstalls into whichever agent you are using.
SKILL.md
Installable skill definition
Quality Score
Category
OperationsSupported Platforms
Our assessment of bigquery-udfs
bigquery-udfs scores 98/100 on our quality scale, 31st of 756 Operations skills we index (top 5%).
Its SKILL.md is 19 KB long, well organised into 15 sections with 5 code examples: a thorough specification that gives an agent plenty to work with.
With 20,340 GitHub stars, it is one of the more widely adopted skills in the catalogue.
Maintenance, license and trust
- The repository was last updated 39 days ago, so bigquery-udfs is actively maintained.
- It is released under the Apache-2.0 license, a permissive license that allows use, modification and commercial use with attribution.
- Its trust signals score 100/100, with no cautions. These come from repository metadata, not a code audit — read the skill file before letting an agent act on it.
bigquery-udfs compared with similar skills
All 4 of these similar skills score higher than bigquery-udfs; compare them before choosing.
| Skill | Score | Stars | Updated | Format |
|---|---|---|---|---|
| bigquery-udfs (this skill)by google | 98 | 20.3k | 39d ago | SKILL.md |
| claude-memby thedotmack | 100 | 109.0k | today | CLAUDE.md |
| Agent-Reachby Panniantong | 100 | 107.6k | today | CLAUDE.md |
| headroomby headroomlabs-ai | 100 | 78.5k | today | CLAUDE.md |
| Scraplingby D4Vinci | 100 | 91.7k | today | MCP Server |
Frequently asked questions
- How do I install bigquery-udfs?
- Run
npx skills add google/skills --skill bigquery-udfs. The install tabs above show the steps for each supported agent. - Which AI agents does bigquery-udfs work with?
- It is written for Universal, as a SKILL.md file. Other agents that read the same format can often use it too.
- Is bigquery-udfs safe to use?
- It is Apache-2.0-licensed and scores 100/100 on trust signals. Skills are instructions an agent will follow, so read the file before installing it and do not approve commands you do not understand.
- Is bigquery-udfs still maintained?
- The repository was last updated 39 days ago, so bigquery-udfs is actively maintained.
Skill content
View source on GitHubname: bigquery-udfs metadata: version: "1.0.1" category: BigDataAndAnalytics description: >- Creates, deploys, and troubleshoots BigQuery User-Defined Functions (UDFs) and Remote Functions across SQL, JavaScript, Python, and Cloud Run endpoints. Use when writing custom scalar or aggregate functions in BigQuery, installing PyPI packages or Cloud Storage libraries in a Python or JavaScript UDF, or calling Google Cloud and external APIs from a Python UDF (WITH CONNECTION) or Remote Function. Don't use for standard BigQuery table/dataset CRUD (use bigquery-basics), DataFrames client workflows (use bigquery-bigframes), or BigQuery ML models (use bigquery-ai-ml).
BigQuery User-Defined Functions (UDFs)
BigQuery User-Defined Functions (UDFs) extend GoogleSQL with custom logic
written in SQL, JavaScript, managed Python (python-3.11), or hosted externally
as Remote Functions on Cloud Run and Cloud Run functions.
Usage Attribution
MUST READ: Before executing any gcloud, REST API, or MCP command, you
MUST read and follow the instructions in
Usage Attribution.
Choosing the Right UDF Type
Always select the lightest-weight runtime that satisfies the requirement, because BigQuery optimizes native SQL expressions inline while external runtimes incur serialization and container startup overhead:
UDF Type | Connection Required? | When to Use | Key Constraints
:--------------------------------------------- | :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------
SQL UDF (Default) | No | Composable expressions, regex, struct/array manipulation, aggregate functions (CREATE AGGREGATE FUNCTION), or polymorphic ANY TYPE parameters. | Lowest latency; zero external dependencies; supports TEMP or persistent functions.
JavaScript UDF | No | Custom string/JSON logic or bundling .js libraries from Cloud Storage (gs://). | Runs in V8 sandbox; INT64 unsupported as input (pass as FLOAT64 or STRING). Max 32 KB inline code, 1 MB per external resource. Supports TEMP or persistent functions.
Managed Python UDF (Offline) | No | Pure compute using Python 3.11, PyPI wheels (packages=[...]), Cloud Storage .py modules (library=[...]), or vectorized Pandas/PyArrow batches. | Persistent functions only (CREATE TEMP FUNCTION unsupported). Outbound network blocked. Max container size: 4 vCPU / 16 GiB. JSON, RANGE, INTERVAL, GEOGRAPHY unsupported.
Managed Python UDF (WITH CONNECTION) | Yes (CLOUD_RESOURCE) | Invoking Google Cloud APIs (e.g., Cloud Translation, Gemini Enterprise Agent Platform) or online HTTP endpoints directly from Python inside BigQuery containers. | Requires WITH CONNECTION. Outbound traffic restricted to restricted.googleapis.com in VPC-SC perimeters (VPC networks unsupported). Max container size: 4 vCPU / 16 GiB.
Remote Function (REMOTE WITH CONNECTION) | Yes (CLOUD_RESOURCE) | Calling external APIs or microservices when you need non-Python runtimes (Go, Java, Node.js), private VPC network access, GPUs, or custom Cloud Run scaling. | Requires Cloud Run HTTPS endpoint implementing BigQuery JSON batch contract and roles/run.invoker. Max input 5 MB per row; response limit 15 MB (Cloud Run) / 10 MB (1st gen).
Prerequisites & Setup
Ensure the Google Cloud project has an active billing account attached (see BigQuery Pricing):
-
Install and Authenticate Google Cloud SDK: Install the Google Cloud SDK and authenticate:
gcloud auth loginPass
--project={project_id}and--region={region}(or--locationforbq) explicitly on each command instead of runninggcloud config set, which persists beyond the task. Default tous-central1when the user has not specified a region (see BigQuery Locations). -
Enable Required APIs:
- For SQL, JavaScript, and offline Python UDFs:
bigquery.googleapis.com - Additionally for Python UDFs calling APIs (
WITH CONNECTION) and Remote Functions:bigqueryconnection.googleapis.com(andrun.googleapis.comfor Remote Functions)
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-udfs)" \ gcloud services enable bigquery.googleapis.com \ bigqueryconnection.googleapis.com \ run.googleapis.com --quiet - For SQL, JavaScript, and offline Python UDFs:
-
Verify Required IAM Roles:
- All UDFs:
roles/bigquery.dataEditoron the dataset androles/bigquery.jobUseron the project. - When using
WITH CONNECTION(API-calling Python UDFs & Remote Functions):- UDF Creator:
roles/bigquery.connectionAdminon the project (plusresourcemanager.projects.setIamPolicy, e.g.,roles/resourcemanager.projectIamAdmin, when granting project-level IAM roles to the connection service account viaGRANT ... ON PROJECT). - UDF Caller:
roles/bigquery.connectionUseron the connection.
- UDF Creator:
- All UDFs:
Core Implementation Patterns
1. SQL UDFs (Scalar & Templated)
Use CREATE OR REPLACE FUNCTION for persistent UDFs or CREATE TEMP FUNCTION
for query-scoped functions. Use ANY TYPE for polymorphic parameters:
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.normalize_phone`(
raw_phone STRING,
country_code ANY TYPE
)
RETURNS STRING
AS (
CONCAT('+', CAST(country_code AS STRING), '-', REGEXP_REPLACE(raw_phone, r'[^0-9]', ''))
);
See SQL and JavaScript UDFs for aggregate UDFs
(CREATE AGGREGATE FUNCTION) and JavaScript Cloud Storage library loading.
2. JavaScript UDFs
Use raw triple-quoted strings (r"""...""") to avoid escaping backslashes:
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.extract_url_query_keys`(
url_str STRING
)
RETURNS ARRAY<STRING>
DETERMINISTIC
LANGUAGE js
OPTIONS (
library = ['gs://{bucket_name}/libs/uri-parser.js']
)
AS r"""
if (!url_str) return [];
try {
return URIParser.getQueryKeys(url_str);
} catch (err) {
return [];
}
""";
3. Managed Python UDFs (With and Without Connection)
Python UDFs must be persistent (do not use TEMP), specify runtime_version = 'python-3.11', and define an entry_point. numpy, pandas, and pyarrow
are pre-installed in the python-3.11 base image.
BigQuery defaults to container_memory = '512Mi', container_cpu = 1.0, and
container_request_concurrency = 80. Omit these options when the defaults are
sufficient, and configure them explicitly only when a workload requires custom
container sizing or concurrency (see Python UDFs).
Top-level Python statements (import, helper functions, classes, and def {entry_point}(...)) inside AS r'''...''' must have zero leading
indentation (flush to the left margin). Indenting top-level Python definitions
to align with surrounding SQL causes an IndentationError when BigQuery loads
the container module.
A. Offline / Vectorized Python UDF (No Connection Needed)
Omit WITH CONNECTION when the UDF only performs computation or uses PyPI
packages (packages=[...]) / Cloud Storage libraries (library=['gs://...']).
To vectorize execution over batches of rows, annotate the parameter with
pd.DataFrame (or pyarrow.RecordBatch) and return a pd.Series:
[!WARNING] Vectorized operations must be row-independent: BigQuery calls vectorized UDFs on arbitrary row batches (up to
max_batching_rows). Do NOT compute global column statistics (such as z-scores, dataset mean/std, or rank) acrossdf, because each batch only sees an arbitrary slice of rows. Use SQL window functions ((val - AVG(val) OVER()) / NULLIF(STDDEV(val) OVER(), 0)) for dataset-wide statistics. Vectorized Python UDFs should perform row-independent calculations (e.g. geometric distances or multi-column math).
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.vectorized_distance`(
x1 FLOAT64, y1 FLOAT64, x2 FLOAT64, y2 FLOAT64
)
RETURNS FLOAT64
LANGUAGE python
OPTIONS (
runtime_version = 'python-3.11',
entry_point = 'compute_distance'
)
AS r'''
import numpy as np
import pandas as pd
def compute_distance(df: pd.DataFrame) -> pd.Series:
return pd.Series(
np.hypot(df['x2'] - df['x1'], df['y2'] - df['y1']),
index=df.index,
)
''';
B. Online Python UDF Calling an External / Cloud API (WITH CONNECTION)
Include WITH CONNECTION only when the Python code makes outbound network
or API calls at runtime.
Always configure explicit timeouts, logging, and prescriptive exception handling
in the try...except block:
- Transient errors only →
NULL: Catch retryable exceptions (google.api_core.exceptions.TooManyRequests,ServiceUnavailable,DeadlineExceeded,InternalServerError, andRetryError), log them withlogging.warning, and returnNoneso a transient blip does not abort the query. Do not catch the base classGoogleAPICallErrorhere: it also matchesPermissionDenied,Unauthenticated, andInvalidArgument. - Fatal errors → raise: Let auth, permission, and invalid-argument errors
propagate (or log and re-raise as
RuntimeError) so they surface as a user error on the query instead of silently producingNULLs. - Never log row values: Anyone with Cloud Logging access can read UDF logs
regardless of BigQuery table permissions. Log exception types and messages,
not input or output data. Logs are only emitted when the session sets
SET @@udf.properties = JSON '{"enableDebugOutput": true}';. - Set a per-request
timeout:Retry(timeout=...)only caps the total retry duration; also passtimeout=on each client call.
-
Create a Cloud Resource Connection and Retrieve its Service Account:
bq mk --connection --connection_type=CLOUD_RESOURCE \ --location={region} --project_id={project_id} {connection_id} bq show --connection {project_id}.{region}.{connection_id} -
Grant Permissions to the Connection Service Account: Grant
roles/serviceusage.serviceUsageConsumeron{project_id}plus the required API role (e.g.,roles/cloudtranslate.user) on the target project. RunningGRANT ... ON PROJECTmodifies the project's IAM policy and requiresresourcemanager.projects.setIamPolicy(for example,roles/resourcemanager.projectIamAdmin); confirm with the user before running project-level IAM grants. The DCLconnection:grantee takes the connection path ([project_id.]location.connection_id), not the service account email; BigQuery resolves the connection's service account automatically (use"serviceAccount:{connection_sa_email}"to grant by email instead):GRANT `roles/serviceusage.serviceUsageConsumer` ON PROJECT `{project_id}` TO "connection:{project_id}.{region}.{connection_id}"; GRANT `roles/cloudtranslate.use
Truncated for display — read the full file on GitHub.
Related Skills
claude-mem
109.0kPersistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
Agent-Reach
107.6kGive your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.
headroom
78.5kCompress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Scrapling
91.7k🕷️ The BEST Web Scraping framework that handles everything from a single request to a full-scale crawl! Don't be shy, join here: https://discord.gg/EMgGbDceNQ and follow here for daily tips and tricks: https://x.com/Scrapling_dev
Languages
Trust signals
From repository metadata: license, adoption, age and documentation. Not a code audit — see the Safety scan above for what the skill file itself contains.
