bigquery-data-science 0.7.0__py3-none-any.whl
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.
- bigquery_data_science/__init__.py +58 -0
- bigquery_data_science/_skills/PLANS.md +76 -0
- bigquery_data_science/_skills/bigquery-ai/SKILL.md +66 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_agg.md +528 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_classify.md +450 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_count_tokens.md +180 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_detect_anomalies.md +322 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_embed.md +425 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_evaluate.md +368 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_forecast.md +437 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_generate.md +693 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_generate_bool.md +248 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_generate_double.md +254 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_generate_embedding.md +402 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_generate_int.md +252 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_generate_table.md +447 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_generate_text.md +356 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_if.md +373 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_key_drivers.md +331 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_parse_document.md +416 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_predict.md +559 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_score.md +310 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_search.md +465 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ai_similarity.md +371 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/catalog_search.md +951 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/content_analysis.md +284 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/content_moderation.md +369 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/data_enrichment.md +426 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/document_intelligence.md +470 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/document_rag.md +453 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/image_deduplication.md +770 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/log_analysis.md +668 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/metric_diagnostics.md +568 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ml_annotate_image.md +680 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ml_generate_embedding.md +217 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ml_generate_text.md +223 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ml_process_document.md +392 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ml_transcribe.md +815 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ml_translate.md +600 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/ml_understand_text.md +673 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/multimodal_analysis.md +266 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/rag_pipeline.md +593 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/semantic_search.md +510 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/tabular_prediction.md +485 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/time_series_intelligence.md +489 -0
- bigquery_data_science/_skills/bigquery-ai/narrative/vector_search.md +672 -0
- bigquery_data_science/_skills/bigquery-ai/reference/augmented-analytics.md +77 -0
- bigquery_data_science/_skills/bigquery-ai/reference/cloud-ai-service-models.md +88 -0
- bigquery_data_science/_skills/bigquery-ai/reference/document-processing.md +95 -0
- bigquery_data_science/_skills/bigquery-ai/reference/embeddings-and-search.md +166 -0
- bigquery_data_science/_skills/bigquery-ai/reference/general-purpose-generation.md +87 -0
- bigquery_data_science/_skills/bigquery-ai/reference/managed-functions.md +72 -0
- bigquery_data_science/_skills/bigquery-ai/reference/predictive-ai.md +113 -0
- bigquery_data_science/_skills/bigquery-ai/reference/workflows.md +56 -0
- bigquery_data_science/_skills/bigquery-ai/skill.manifest.json +109 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/INDEX.md +71 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aiagg.md +67 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aicausal_effect-covered-in-bigquery-ml.md +17 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aiclassify.md +72 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aicount_tokens.md +53 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aidetect_anomalies.md +63 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aiembed.md +85 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aievaluate.md +114 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aiforecast.md +123 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aigenerate.md +69 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aigenerate_bool.md +53 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aigenerate_double.md +45 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aigenerate_embedding.md +108 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aigenerate_int.md +45 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aigenerate_table.md +64 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aigenerate_text.md +167 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aiif.md +56 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aikey_drivers.md +76 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aiparse_document.md +91 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aipredict.md +74 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aiscore.md +52 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aisearch.md +66 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/aisimilarity.md +79 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/choosing-between-these-and-the-ai-functions.md +11 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/hybrid-search-capability.md +165 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/mlannotate_image.md +24 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/mlgenerate_embedding.md +34 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/mlgenerate_text.md +65 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/mlprocess_document.md +125 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/mltranscribe.md +26 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/mltranslate.md +27 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/mlunderstand_text.md +32 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/multimodal-input-patterns-by-function.md +128 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/object-tables.md +109 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/objectref-and-objectrefruntime-schema-reference.md +50 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/objfetch_metadata.md +49 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/objget_access_url.md +66 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/objget_read_url.md +40 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/objlist.md +34 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/objmake_ref.md +58 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/per-row-failures-and-the-retry-pattern.md +19 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/setup-apis-connection-roles.md +39 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/two-input-shapes.md +22 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/vector_search.md +78 -0
- bigquery_data_science/_skills/bigquery-ai/syntax/what-the-five-have-in-common.md +27 -0
- bigquery_data_science/_skills/bigquery-data-science/SKILL.md +69 -0
- bigquery_data_science/_skills/bigquery-data-science/reference/namespace-matrix.md +112 -0
- bigquery_data_science/_skills/bigquery-data-science/skill.manifest.json +13 -0
- bigquery_data_science/_skills/bigquery-ml/SKILL.md +70 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/airflow_with_kfp.md +379 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/anomaly_fraud_detection.md +195 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/arima_plus.md +635 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/arima_plus_xreg.md +453 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/autoencoder.md +470 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/automl_classifier.md +291 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/automl_regressor.md +274 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/boosted_tree_classifier.md +449 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/boosted_tree_regressor.md +400 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/bucketizing.md +201 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/causal_effect.md +773 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/churn_retention.md +271 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/cloud_workflows.md +370 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/composer_airflow.md +475 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/contribution_analysis.md +346 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/cross_validation.md +185 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/customer_segmentation.md +233 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/dataform.md +372 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/dbt.md +283 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/difference_in_differences.md +280 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/distance.md +195 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/dnn_classifier.md +326 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/dnn_regressor.md +308 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/embeddings_classification.md +426 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/encoding.md +238 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/ensembling.md +278 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/evaluation.md +445 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/exploration.md +779 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/export.md +321 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/feature_engineering.md +280 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/feature_store.md +652 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/feature_store_workflow.md +426 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/ga4_churn_prediction.md +285 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/hierarchical_forecasting.md +441 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/image.md +791 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/imported.md +426 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/kmeans.md +348 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/linear_regression.md +372 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/logistic_regression.md +390 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/matrix_factorization.md +404 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/model_monitoring.md +609 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/pca.md +357 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/price_elasticity_dml.md +286 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/propensity_score_matching.md +350 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/random_forest_classifier.md +445 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/random_forest_regressor.md +409 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/recommendation.md +281 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/regression_based_forecasting.md +491 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/remote.md +428 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/scalers.md +325 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/scheduled_queries.md +284 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/sql_scripting.md +243 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/survival_analysis.md +363 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/synthetic_control.md +221 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/text.md +215 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/time_series.md +669 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/transform_only.md +273 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/uplift_cate.md +241 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/vertex_kfp.md +360 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/wide_and_deep_classifier.md +316 -0
- bigquery_data_science/_skills/bigquery-ml/narrative/wide_and_deep_regressor.md +298 -0
- bigquery_data_science/_skills/bigquery-ml/reference/classification.md +80 -0
- bigquery_data_science/_skills/bigquery-ml/reference/model-management.md +90 -0
- bigquery_data_science/_skills/bigquery-ml/reference/preprocessing-functions.md +234 -0
- bigquery_data_science/_skills/bigquery-ml/reference/regression.md +79 -0
- bigquery_data_science/_skills/bigquery-ml/reference/unsupervised-and-specialized.md +101 -0
- bigquery_data_science/_skills/bigquery-ml/reference/workflows-and-pipelines.md +111 -0
- bigquery_data_science/_skills/bigquery-ml/skill.manifest.json +177 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/1-model_type-catalog.md +28 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/2-task-mlevaluate-metric-columns.md +26 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/3-capability-matrix-per-model-type.md +21 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/4-explainability-weights-functions.md +14 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/5-connection-matrix.md +11 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/6-which-model-free-function-no-create-model-no-connection.md +15 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/7-point-in-time-feature-retrieval-which-of-the-two.md +11 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/INDEX.md +111 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/aicausal_effect.md +85 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/arima_plus-forecasting-lifecycle-functions.md +14 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/arima_plus-univariate-time-series-forecasting.md +132 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/arima_plus_xreg-multivariate-time-series-with-external-regressors.md +103 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/autoencoder.md +102 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/automl_classifier-automl_regressor.md +88 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/boosted_tree_classifier-boosted_tree_regressor.md +117 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/contribution_analysis.md +113 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/dnn_classifier-dnn_regressor.md +107 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/dnn_linear_combined_classifier-dnn_linear_combined_regressor-wide-and-deep.md +98 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/explainability-functions-mlexplain_predict-mlglobal_explain-mlfeature_importance.md +7 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/exploratory-data-analysis-mldescribe_data-mlcorrelation.md +11 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/export-model.md +92 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/feature-engineering-standalone-preprocessing-functions.md +13 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/image-preprocessing-functions-mldecode_image-mlresize_image-mlconvert_image_type-mlconvert_color_space.md +63 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/imported-models-tensorflow-tensorflow_lite-onnx-xgboost.md +36 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/kmeans.md +87 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/linear_reg-logistic_reg-generalized-linear-models.md +101 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/matrix_factorization.md +162 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mladvanced_weights.md +76 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlarima_coefficients.md +30 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlarima_evaluate.md +49 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlbag_of_words.md +47 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlbucketize.md +47 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlcentroids.md +46 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlconfusion_matrix.md +56 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlconvert_color_space.md +53 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlconvert_image_type.md +39 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlcorrelation.md +78 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mldecode_image.md +44 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mldescribe_data.md +74 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mldetect_anomalies.md +86 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mldistance.md +48 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlentity_features_at_time.md +56 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlevaluate.md +72 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlexplain_forecast.md +50 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlexplain_predict.md +66 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlfeature_cross.md +46 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlfeature_importance.md +47 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlfeature_info.md +50 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlfeatures_at_time.md +51 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlforecast.md +76 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlgenerate_embedding-from-a-bqml-pca-autoencoder-matrix_factorization-model.md +64 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlglobal_explain.md +63 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlhash_bucketize.md +47 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlholiday_info.md +46 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlimputer.md +46 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mllp_norm.md +47 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlmetrics.md +80 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlngrams.md +37 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlone_hot_encoder-mlmulti_hot_encoder-mllabel_encoder.md +67 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlpolynomial_expand.md +47 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlpredict.md +67 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlprincipal_component_info.md +42 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlprincipal_components.md +40 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlquantile_bucketize.md +43 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlrecommend.md +60 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlreconstruction_loss.md +48 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlresize_image.md +45 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlroc_curve.md +63 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mltf_idf.md +37 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mltfdv_describe.md +34 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mltfdv_validate.md +48 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mltraining_info.md +78 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mltransform-applying-a-saved-transform.md +52 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mltranspose-not-a-function-pointer.md +32 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mltrial_info.md +60 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlvalidate_data_drift.md +99 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlvalidate_data_skew.md +50 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/mlweights.md +84 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/model-free-time-series-decomposition-mltrend-mlseasonality-mldetect_change_points.md +100 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/model-introspection-mlfeature_info-mltraining_info-mltrial_info.md +7 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/model-monitoring-data-validation.md +23 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/numerical-scalers-mlstandard_scaler-mlmin_max_scaler-mlmax_abs_scaler-mlrobust_scaler-mlnormalizer.md +77 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/onnx.md +55 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/pca.md +91 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/point-in-time-feature-retrieval-mlfeatures_at_time-mlentity_features_at_time.md +25 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/quick-comparison.md +14 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/random_forest_classifier-random_forest_regressor.md +123 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/remote-remote-model-over-a-vertex-ai-endpoint-the-mechanism.md +87 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/tensorflow.md +48 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/tensorflow_lite.md +29 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/text-preprocessing-functions-mlngrams-mltf_idf-mlbag_of_words.md +18 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/timesfm-built-in-foundation-forecaster-see-bigquery-ai.md +28 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/transform_only.md +91 -0
- bigquery_data_science/_skills/bigquery-ml/syntax/xgboost.md +72 -0
- bigquery_data_science/_skills/pinned-models.json +28 -0
- bigquery_data_science/catalog.py +1107 -0
- bigquery_data_science/cli.py +786 -0
- bigquery_data_science/installer.py +282 -0
- bigquery_data_science/mcp_server.py +317 -0
- bigquery_data_science/tooling/__init__.py +15 -0
- bigquery_data_science/tooling/convert_notebook.py +176 -0
- bigquery_data_science/tooling/link_policy.py +247 -0
- bigquery_data_science/tooling/manifest.py +152 -0
- bigquery_data_science/tooling/markdown_anchors.py +84 -0
- bigquery_data_science/tooling/narrative_drift.py +163 -0
- bigquery_data_science/tooling/pinned_models.py +216 -0
- bigquery_data_science/tooling/reference_structure.py +85 -0
- bigquery_data_science/tooling/sync_syntax.py +407 -0
- bigquery_data_science/tooling/validate.py +208 -0
- bigquery_data_science-0.7.0.dist-info/METADATA +306 -0
- bigquery_data_science-0.7.0.dist-info/RECORD +286 -0
- bigquery_data_science-0.7.0.dist-info/WHEEL +4 -0
- bigquery_data_science-0.7.0.dist-info/entry_points.txt +5 -0
- bigquery_data_science-0.7.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
> **Source (`statmike/bigquery-data-science`):** **Notebook:** [`bigquery-ai/functions/ai_classify/ai_classify.ipynb`](https://github.com/statmike/bigquery-data-science/blob/main/bigquery-ai/functions/ai_classify/ai_classify.ipynb) · **SQL:** [`bigquery-ai/functions/ai_classify/ai_classify.sql`](https://github.com/statmike/bigquery-data-science/blob/main/bigquery-ai/functions/ai_classify/ai_classify.sql)
|
|
2
|
+
|
|
3
|
+
# AI.CLASSIFY — BigQuery AI Functions
|
|
4
|
+
|
|
5
|
+
`AI.CLASSIFY` is a managed scalar function that classifies inputs into categories you provide. It supports single-label and multi-label classification with optional category descriptions.
|
|
6
|
+
|
|
7
|
+
**When to use it:**
|
|
8
|
+
- You have a fixed set of categories and want to classify text or images
|
|
9
|
+
- You need multi-label classification (items can belong to multiple categories)
|
|
10
|
+
- You want BigQuery to auto-optimize classification prompts
|
|
11
|
+
- You want to guide classification with few-shot `examples` (pairs of input → expected category)
|
|
12
|
+
- You want cost-optimized classification at scale: `optimization_mode => 'MINIMIZE_COST'` with `embeddings` trains a local distilled model (~3,000 row minimum, single-label only)
|
|
13
|
+
|
|
14
|
+
**Alternatives:**
|
|
15
|
+
- `functions/ai_generate` (`AI.GENERATE`) — Full control with output_schema for custom classification logic
|
|
16
|
+
- `functions/ai_if` (`AI.IF`) — Boolean classification (yes/no)
|
|
17
|
+
- `functions/ai_score` (`AI.SCORE`) — Numeric scoring instead of categorical
|
|
18
|
+
|
|
19
|
+
**Featured in:** `workflows/content_analysis` (Content Analysis Pipeline) | `workflows/document_intelligence` (Document Intelligence) | `workflows/content_moderation` (Content Moderation) | `workflows/log_analysis` (Log Analysis)
|
|
20
|
+
|
|
21
|
+
**Multimodal:** Supports document, image, and video input via `reference/unstructured-data-infrastructure.md#objectref-and-objectrefruntime-schema-reference` (ObjectRef). Pass a STRUCT input with `ObjectRef` fields to classify documents, images, or video.
|
|
22
|
+
|
|
23
|
+
**References:** `RESOURCES.md` (Full syntax reference) | [Official documentation](https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-ai-classify) | `setup` (Setup guide)
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
## Setup
|
|
27
|
+
|
|
28
|
+
Set your project and location, authenticate, and create a temporary dataset for this notebook.
|
|
29
|
+
|
|
30
|
+
> This function doesn't require a connection or model for SQL usage — it uses end-user credentials automatically. The [multimodal examples](#examples--multimodal-with-objectref) and BigFrames section add a connection for GCS and Vertex AI access. See the `setup` (Setup Reference) for details.
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
PROJECT_ID = 'statmike-mlops-349915' # <-- Replace with your project ID
|
|
34
|
+
LOCATION = 'US' # BigQuery dataset location
|
|
35
|
+
DATASET_ID = 'bq_ai_functions' # Shared dataset across all notebooks
|
|
36
|
+
CONNECTION_ID = 'bq_ai_functions' # Shared connection (used by multimodal examples and BigFrames)
|
|
37
|
+
BUCKET = PROJECT_ID # GCS bucket (same name as project)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### Environment
|
|
41
|
+
|
|
42
|
+
> **Already set up the project environment?** The cell below is a no-op — packages are already in your kernel. See the `setup` (Setup Reference) for details.
|
|
43
|
+
>
|
|
44
|
+
> **Running standalone** (Colab, Colab Enterprise, Vertex AI Workbench)? The cell below installs required packages into your current kernel.
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from google.cloud import bigquery
|
|
48
|
+
import pandas as pd
|
|
49
|
+
|
|
50
|
+
client = bigquery.Client(project=PROJECT_ID)
|
|
51
|
+
pd.set_option('display.max_colwidth', None)
|
|
52
|
+
|
|
53
|
+
# Create the shared dataset (idempotent)
|
|
54
|
+
dataset_ref = bigquery.DatasetReference(PROJECT_ID, DATASET_ID)
|
|
55
|
+
dataset = bigquery.Dataset(dataset_ref)
|
|
56
|
+
dataset.location = LOCATION
|
|
57
|
+
client.create_dataset(dataset, exists_ok=True)
|
|
58
|
+
print(f'Dataset {PROJECT_ID}.{DATASET_ID} ready')
|
|
59
|
+
|
|
60
|
+
# Register %%bigquery cell magic (auto-loaded in Colab, needed elsewhere)
|
|
61
|
+
%load_ext bigquery_magics
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
## Examples — SQL
|
|
66
|
+
|
|
67
|
+
Progressive examples from simplest to most advanced. Each cell adds one new concept.
|
|
68
|
+
|
|
69
|
+
### 1. Simple classification
|
|
70
|
+
|
|
71
|
+
`AI.CLASSIFY` takes an input and an array of categories. Returns the best-matching category as STRING.
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
query = """
|
|
75
|
+
SELECT
|
|
76
|
+
review,
|
|
77
|
+
AI.CLASSIFY(
|
|
78
|
+
review,
|
|
79
|
+
['positive', 'negative', 'neutral']
|
|
80
|
+
) AS sentiment
|
|
81
|
+
FROM UNNEST([
|
|
82
|
+
'Amazing product, exceeded expectations!',
|
|
83
|
+
'Terrible quality, fell apart immediately.',
|
|
84
|
+
'It works as expected. Nothing special.'
|
|
85
|
+
]) AS review
|
|
86
|
+
"""
|
|
87
|
+
client.query(query).to_dataframe()
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### 2. Categories with descriptions
|
|
91
|
+
|
|
92
|
+
Provide descriptions to guide the model. Use `STRUCT` pairs: `(category, description)`.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
query = """
|
|
96
|
+
SELECT
|
|
97
|
+
ticket,
|
|
98
|
+
AI.CLASSIFY(
|
|
99
|
+
ticket,
|
|
100
|
+
[('billing', 'Issues with charges, invoices, or payments'),
|
|
101
|
+
('technical', 'Product bugs, errors, or how-to questions'),
|
|
102
|
+
('shipping', 'Delivery, tracking, or logistics issues'),
|
|
103
|
+
('other', 'Anything not matching the above categories')]
|
|
104
|
+
) AS category
|
|
105
|
+
FROM UNNEST([
|
|
106
|
+
'I was charged twice for my subscription.',
|
|
107
|
+
'The app crashes when I try to upload files.',
|
|
108
|
+
'My package has been in transit for 3 weeks.',
|
|
109
|
+
'Can I get a gift card for my friend?'
|
|
110
|
+
]) AS ticket
|
|
111
|
+
"""
|
|
112
|
+
client.query(query).to_dataframe()
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### 3. Multi-label classification
|
|
116
|
+
|
|
117
|
+
Set `output_mode => 'multi'` to allow items to belong to multiple categories. Returns `ARRAY<STRING>`.
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
query = """
|
|
121
|
+
SELECT
|
|
122
|
+
article,
|
|
123
|
+
AI.CLASSIFY(
|
|
124
|
+
article,
|
|
125
|
+
['technology', 'business', 'science', 'politics', 'health'],
|
|
126
|
+
output_mode => 'multi'
|
|
127
|
+
) AS categories
|
|
128
|
+
FROM UNNEST([
|
|
129
|
+
'New AI regulations proposed by the EU could reshape the tech industry.',
|
|
130
|
+
'Scientists develop a cheaper solar panel that could boost clean energy stocks.',
|
|
131
|
+
'Study shows regular exercise reduces risk of cognitive decline.'
|
|
132
|
+
]) AS article
|
|
133
|
+
"""
|
|
134
|
+
client.query(query).to_dataframe()
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### 4. Single-label with array output
|
|
138
|
+
|
|
139
|
+
`output_mode => 'single'` returns an `ARRAY<STRING>` of length 1 — useful when you need consistent array output type.
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
query = """
|
|
143
|
+
SELECT
|
|
144
|
+
email,
|
|
145
|
+
AI.CLASSIFY(
|
|
146
|
+
email,
|
|
147
|
+
['spam', 'promotional', 'personal', 'work'],
|
|
148
|
+
output_mode => 'single'
|
|
149
|
+
) AS category
|
|
150
|
+
FROM UNNEST([
|
|
151
|
+
'You have won a million dollars! Click here NOW!',
|
|
152
|
+
'Sale: 50% off all items this weekend only.',
|
|
153
|
+
'Hey, are we still meeting for dinner tonight?',
|
|
154
|
+
'Please review the Q3 budget spreadsheet by Friday.'
|
|
155
|
+
]) AS email
|
|
156
|
+
"""
|
|
157
|
+
client.query(query).to_dataframe()
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### 5. Specifying an endpoint
|
|
161
|
+
|
|
162
|
+
Override the auto-selected model.
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
query = """
|
|
166
|
+
SELECT
|
|
167
|
+
product,
|
|
168
|
+
AI.CLASSIFY(
|
|
169
|
+
product,
|
|
170
|
+
['Electronics', 'Clothing', 'Home & Kitchen', 'Sports', 'Books'],
|
|
171
|
+
endpoint => 'gemini-2.5-flash'
|
|
172
|
+
) AS category
|
|
173
|
+
FROM UNNEST([
|
|
174
|
+
'Wireless noise-cancelling headphones',
|
|
175
|
+
'Organic cotton t-shirt',
|
|
176
|
+
'Stainless steel cooking pot set',
|
|
177
|
+
'Yoga mat with carrying strap',
|
|
178
|
+
'Data engineering textbook'
|
|
179
|
+
]) AS product
|
|
180
|
+
"""
|
|
181
|
+
client.query(query).to_dataframe()
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
### 6. Few-shot examples
|
|
185
|
+
|
|
186
|
+
The `examples` parameter provides input→category pairs that guide the model. For single-label mode, each example is a `STRUCT<STRING, STRING>`. This is useful when category boundaries are ambiguous or domain-specific.
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
query = """
|
|
190
|
+
SELECT
|
|
191
|
+
message,
|
|
192
|
+
AI.CLASSIFY(
|
|
193
|
+
message,
|
|
194
|
+
['urgent', 'normal', 'low'],
|
|
195
|
+
examples => [
|
|
196
|
+
('Server is down and customers cannot checkout', 'urgent'),
|
|
197
|
+
('Update the logo on the about page', 'low'),
|
|
198
|
+
('Add validation to the signup form', 'normal'),
|
|
199
|
+
('Database backup failed overnight', 'urgent')
|
|
200
|
+
]
|
|
201
|
+
) AS priority
|
|
202
|
+
FROM UNNEST([
|
|
203
|
+
'Payment processing is returning 500 errors for all users.',
|
|
204
|
+
'Can we change the font size on the footer?',
|
|
205
|
+
'The search feature should support filters.',
|
|
206
|
+
'SSL certificate expires in 2 hours.'
|
|
207
|
+
]) AS message
|
|
208
|
+
"""
|
|
209
|
+
client.query(query).to_dataframe()
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
### 7. Error ratio control
|
|
213
|
+
|
|
214
|
+
By default, `AI.CLASSIFY` returns NULL for rows where the model call fails and continues the query. Set `max_error_ratio` (0.0–1.0) to fail the entire query when the error rate exceeds your threshold.
|
|
215
|
+
|
|
216
|
+
```python
|
|
217
|
+
query = """
|
|
218
|
+
SELECT
|
|
219
|
+
fruit,
|
|
220
|
+
AI.CLASSIFY(
|
|
221
|
+
fruit,
|
|
222
|
+
['citrus', 'berry', 'tropical', 'stone fruit'],
|
|
223
|
+
max_error_ratio => 0.0
|
|
224
|
+
) AS category
|
|
225
|
+
FROM UNNEST(['Orange', 'Blueberry', 'Mango', 'Peach', 'Lemon']) AS fruit
|
|
226
|
+
"""
|
|
227
|
+
client.query(query).to_dataframe()
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
### Optimized mode: `optimization_mode` and `embeddings` (Preview)
|
|
231
|
+
|
|
232
|
+
For large-scale classification (≥3,000 rows), `AI.CLASSIFY` supports an optimized mode that trains a local distilled model using embeddings:
|
|
233
|
+
|
|
234
|
+
```sql
|
|
235
|
+
SELECT
|
|
236
|
+
ticket,
|
|
237
|
+
AI.CLASSIFY(
|
|
238
|
+
ticket,
|
|
239
|
+
['billing', 'technical', 'shipping', 'other'],
|
|
240
|
+
embeddings => AI.EMBED(ticket),
|
|
241
|
+
optimization_mode => 'MINIMIZE_COST'
|
|
242
|
+
) AS category
|
|
243
|
+
FROM `my_dataset.support_tickets` -- needs ~3,000+ rows
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
- `optimization_mode => 'MINIMIZE_COST'` (default when `embeddings` provided) — trains a local model, dramatically reducing Gemini calls
|
|
247
|
+
- `optimization_mode => 'MAXIMIZE_QUALITY'` — always uses the remote LLM (ignores embeddings)
|
|
248
|
+
- `embeddings` can be generated on-the-fly with `AI.EMBED(...)` or pre-materialized
|
|
249
|
+
- **Single-label only** — `output_mode => 'multi'` is not supported in optimized mode
|
|
250
|
+
- Not demoed here because the minimum ~3,000 row requirement exceeds our example data size
|
|
251
|
+
|
|
252
|
+
---
|
|
253
|
+
## Examples — Multimodal with ObjectRef
|
|
254
|
+
|
|
255
|
+
`AI.CLASSIFY` can classify documents, images, and video stored in Cloud Storage. Create an **object table** to reference GCS files and pass its `ref` column — an `ObjectRef` — straight to the function.
|
|
256
|
+
|
|
257
|
+
```
|
|
258
|
+
Object table (GCS URIs + connection)
|
|
259
|
+
→ ref column (ObjectRef)
|
|
260
|
+
→ AI.CLASSIFY(ref, categories)
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
`EXTERNAL_OBJECT_TRANSFORM(TABLE t, ['SIGNED_URL'])` rewrites that column into a signed `ObjectRefRuntime`. It is worth reaching for when something downstream needs a fetchable URL — a display link, delegated access, an explicit TTL — but `AI.CLASSIFY` does not need it. See the `reference/unstructured-data-infrastructure.md#objectref-and-objectrefruntime-schema-reference` (ObjectRef reference) for details.
|
|
264
|
+
|
|
265
|
+
### Multimodal setup — connection, documents, and object table
|
|
266
|
+
|
|
267
|
+
ObjectRef requires a `setup` (Cloud resource connection) to access GCS. The cells below create a connection, upload sample documents, and create an object table.
|
|
268
|
+
|
|
269
|
+
```python
|
|
270
|
+
import subprocess as _sp
|
|
271
|
+
|
|
272
|
+
# Create the connection (idempotent — succeeds even if it already exists)
|
|
273
|
+
_sp.run(
|
|
274
|
+
['bq', 'mk', '--connection', '--location', LOCATION,
|
|
275
|
+
'--connection_type', 'CLOUD_RESOURCE',
|
|
276
|
+
'--project_id', PROJECT_ID, CONNECTION_ID],
|
|
277
|
+
capture_output=True, text=True
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
# Get the connection's service account
|
|
281
|
+
import json as _json
|
|
282
|
+
_conn = _sp.run(
|
|
283
|
+
['bq', 'show', '--connection', '--format=json',
|
|
284
|
+
f'{PROJECT_ID}.{LOCATION}.{CONNECTION_ID}'],
|
|
285
|
+
capture_output=True, text=True
|
|
286
|
+
)
|
|
287
|
+
sa = _json.loads(_conn.stdout)['cloudResource']['serviceAccountId']
|
|
288
|
+
print(f'Connection SA: {sa}')
|
|
289
|
+
|
|
290
|
+
# Grant GCS read access (needed for ObjectRef to read documents)
|
|
291
|
+
_sp.run(
|
|
292
|
+
['gcloud', 'projects', 'add-iam-policy-binding', PROJECT_ID,
|
|
293
|
+
f'--member=serviceAccount:{sa}', '--role=roles/storage.objectViewer', '--quiet'],
|
|
294
|
+
capture_output=True, text=True
|
|
295
|
+
)
|
|
296
|
+
print('Granted roles/storage.objectViewer')
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
```python
|
|
300
|
+
from google.cloud import storage as _storage
|
|
301
|
+
from pathlib import Path
|
|
302
|
+
|
|
303
|
+
_gcs = _storage.Client(project=PROJECT_ID)
|
|
304
|
+
_bucket = _gcs.bucket(BUCKET)
|
|
305
|
+
_prefix = 'bq_ai_functions/ai_classify'
|
|
306
|
+
|
|
307
|
+
# Find the data directory (works from repo checkout or notebook directory)
|
|
308
|
+
_data = Path('../../data/documents')
|
|
309
|
+
if not _data.exists():
|
|
310
|
+
_data = Path('data/documents')
|
|
311
|
+
|
|
312
|
+
# Upload one invoice and one receipt
|
|
313
|
+
for subdir, filename in [('invoices', 'invoice_001.pdf'), ('receipts', 'receipt_001.pdf')]:
|
|
314
|
+
blob = _bucket.blob(f'{_prefix}/{filename}')
|
|
315
|
+
if not blob.exists():
|
|
316
|
+
blob.upload_from_filename(str(_data / subdir / filename))
|
|
317
|
+
print(f'Uploaded {filename} → gs://{BUCKET}/{_prefix}/{filename}')
|
|
318
|
+
else:
|
|
319
|
+
print(f'Already exists: gs://{BUCKET}/{_prefix}/{filename}')
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
```python
|
|
323
|
+
# Create an object table pointing to the uploaded documents
|
|
324
|
+
client.query(f"""
|
|
325
|
+
CREATE OR REPLACE EXTERNAL TABLE `{PROJECT_ID}.{DATASET_ID}.ai_classify_docs`
|
|
326
|
+
WITH CONNECTION `{PROJECT_ID}.{LOCATION}.{CONNECTION_ID}`
|
|
327
|
+
OPTIONS (
|
|
328
|
+
object_metadata = 'SIMPLE',
|
|
329
|
+
uris = ['gs://{BUCKET}/bq_ai_functions/ai_classify/*.pdf']
|
|
330
|
+
)
|
|
331
|
+
""").result()
|
|
332
|
+
print('Object table ai_classify_docs ready')
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
### 8. Classify a document
|
|
336
|
+
|
|
337
|
+
Pass the object table's `ref` column directly to `AI.CLASSIFY`.
|
|
338
|
+
|
|
339
|
+
```python
|
|
340
|
+
query = f"""
|
|
341
|
+
SELECT
|
|
342
|
+
uri,
|
|
343
|
+
AI.CLASSIFY(
|
|
344
|
+
docs.ref,
|
|
345
|
+
['invoice', 'receipt', 'contract', 'report']
|
|
346
|
+
) AS document_type
|
|
347
|
+
FROM
|
|
348
|
+
`{PROJECT_ID}.{DATASET_ID}.ai_classify_docs` AS docs
|
|
349
|
+
"""
|
|
350
|
+
client.query(query).to_dataframe()
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
### 9. Classify documents with category descriptions
|
|
354
|
+
|
|
355
|
+
Add descriptions to guide the model when distinguishing between similar document types.
|
|
356
|
+
|
|
357
|
+
```python
|
|
358
|
+
query = f"""
|
|
359
|
+
SELECT
|
|
360
|
+
uri,
|
|
361
|
+
AI.CLASSIFY(
|
|
362
|
+
docs.ref,
|
|
363
|
+
[('invoice', 'A bill for goods or services with line items, totals, and payment terms'),
|
|
364
|
+
('receipt', 'A proof of purchase showing items bought and amount paid'),
|
|
365
|
+
('contract', 'A legal agreement between parties with terms and conditions'),
|
|
366
|
+
('report', 'An analytical document with findings, data, or recommendations')]
|
|
367
|
+
) AS document_type
|
|
368
|
+
FROM
|
|
369
|
+
`{PROJECT_ID}.{DATASET_ID}.ai_classify_docs` AS docs
|
|
370
|
+
"""
|
|
371
|
+
client.query(query).to_dataframe()
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
---
|
|
375
|
+
## Examples — `%%bigquery` Magics
|
|
376
|
+
|
|
377
|
+
The same examples using IPython magic commands. Magics let you write SQL directly in notebook cells without Python string wrapping.
|
|
378
|
+
|
|
379
|
+
Key patterns:
|
|
380
|
+
- `%%bigquery` — run SQL, display results inline
|
|
381
|
+
- `%%bigquery df` — run SQL, capture results into a pandas DataFrame
|
|
382
|
+
|
|
383
|
+
### Single-label classification
|
|
384
|
+
|
|
385
|
+
```sql
|
|
386
|
+
%%bigquery --project {PROJECT_ID}
|
|
387
|
+
|
|
388
|
+
SELECT
|
|
389
|
+
review,
|
|
390
|
+
AI.CLASSIFY(
|
|
391
|
+
review,
|
|
392
|
+
['positive', 'negative', 'neutral']
|
|
393
|
+
) AS sentiment
|
|
394
|
+
FROM UNNEST([
|
|
395
|
+
'Love it!', 'Terrible.', 'It was okay.', 'Best purchase ever!'
|
|
396
|
+
]) AS review
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
### Multi-label classification
|
|
400
|
+
|
|
401
|
+
```sql
|
|
402
|
+
%%bigquery df_classified --project {PROJECT_ID}
|
|
403
|
+
|
|
404
|
+
SELECT
|
|
405
|
+
article,
|
|
406
|
+
AI.CLASSIFY(
|
|
407
|
+
article,
|
|
408
|
+
['technology', 'business', 'science', 'health'],
|
|
409
|
+
output_mode => 'multi'
|
|
410
|
+
) AS categories
|
|
411
|
+
FROM UNNEST([
|
|
412
|
+
'AI regulations could reshape tech industry profits.',
|
|
413
|
+
'New drug shows promise in clinical trials for rare disease.'
|
|
414
|
+
]) AS article
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
```python
|
|
418
|
+
df_classified
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
---
|
|
422
|
+
## Examples — BigFrames
|
|
423
|
+
|
|
424
|
+
BigFrames wraps `AI.CLASSIFY` via `bbq.ai.classify()`. It returns a Series of STRING directly.
|
|
425
|
+
|
|
426
|
+
**Key patterns:**
|
|
427
|
+
- Takes `categories` as a list/tuple
|
|
428
|
+
- Returns STRING directly (single label)
|
|
429
|
+
- Example: `bbq.ai.classify(df["text"], ["positive", "negative", "neutral"])`
|
|
430
|
+
|
|
431
|
+
```python
|
|
432
|
+
import bigframes.pandas as bpd
|
|
433
|
+
import bigframes.bigquery as bbq
|
|
434
|
+
|
|
435
|
+
bpd.close_session() # Reset session to apply connection settings
|
|
436
|
+
bpd.options.bigquery.project = PROJECT_ID
|
|
437
|
+
bpd.options.bigquery.location = LOCATION
|
|
438
|
+
bpd.options.bigquery.bq_connection = f'{PROJECT_ID}.{LOCATION}.{CONNECTION_ID}'
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
### Classification
|
|
442
|
+
|
|
443
|
+
```python
|
|
444
|
+
df = bpd.DataFrame({'review': [
|
|
445
|
+
'Amazing product!', 'Terrible quality.', 'Pretty good.', 'Awful experience.'
|
|
446
|
+
]})
|
|
447
|
+
|
|
448
|
+
df['sentiment'] = bbq.ai.classify(df['review'], ['positive', 'negative', 'neutral'])
|
|
449
|
+
df.to_pandas()
|
|
450
|
+
```
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
> **Source (`statmike/bigquery-data-science`):** **Notebook:** [`bigquery-ai/functions/ai_count_tokens/ai_count_tokens.ipynb`](https://github.com/statmike/bigquery-data-science/blob/main/bigquery-ai/functions/ai_count_tokens/ai_count_tokens.ipynb) · **SQL:** [`bigquery-ai/functions/ai_count_tokens/ai_count_tokens.sql`](https://github.com/statmike/bigquery-data-science/blob/main/bigquery-ai/functions/ai_count_tokens/ai_count_tokens.sql)
|
|
2
|
+
|
|
3
|
+
# AI.COUNT_TOKENS — BigQuery AI Functions
|
|
4
|
+
|
|
5
|
+
`AI.COUNT_TOKENS` is a **utility scalar function** that estimates the number of **input tokens** in a text prompt. Token counting happens inside BigQuery and **incurs no Vertex AI charges** — so you can use it freely to size prompts and estimate cost *before* calling the paid generative functions.
|
|
6
|
+
|
|
7
|
+
**When to use it:**
|
|
8
|
+
- Estimate the cost of an `AI.GENERATE` / `AI.GENERATE_TABLE` job before running it
|
|
9
|
+
- Check prompts against a model's input token limit
|
|
10
|
+
- Compare prompt sizes across rows, templates, or models
|
|
11
|
+
|
|
12
|
+
**Alternatives / companions:**
|
|
13
|
+
- `functions/ai_generate` (`AI.GENERATE`) — the generation function whose default model this uses when no `endpoint` is given
|
|
14
|
+
- Actual per-query token usage (input + thinking + output) appears in the **Job information** tab of the Query results pane
|
|
15
|
+
|
|
16
|
+
**Note:** `AI.COUNT_TOKENS` counts **input** tokens only — not thinking or output tokens.
|
|
17
|
+
|
|
18
|
+
**Text only (Preview):** the input must be a `STRING` — multimodal/ObjectRef prompts are not accepted (verified 2026-07-17), so `full_response` always reports `modality: "TEXT"`. This is a Preview function; multimodal support should be re-evaluated at GA.
|
|
19
|
+
|
|
20
|
+
**References:** `RESOURCES.md` (Full syntax reference) | [Official documentation](https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-ai-count-tokens) | `setup` (Setup guide)
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
## Setup
|
|
24
|
+
|
|
25
|
+
Set your project and location, and authenticate.
|
|
26
|
+
|
|
27
|
+
> `AI.COUNT_TOKENS` needs no connection and no model — it uses your end-user credentials and counts tokens inside BigQuery. See the `setup` (Setup Reference) for details.
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
PROJECT_ID = 'statmike-mlops-349915' # <-- Replace with your project ID
|
|
31
|
+
LOCATION = 'US' # BigQuery dataset location
|
|
32
|
+
DATASET_ID = 'bq_ai_functions' # Shared dataset across all notebooks
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### Environment
|
|
36
|
+
|
|
37
|
+
> **Already set up the project environment?** The cell below is a no-op — packages are already in your kernel. See the `setup` (Setup Reference) for details.
|
|
38
|
+
>
|
|
39
|
+
> **Running standalone** (Colab, Colab Enterprise, Vertex AI Workbench)? The cell below installs required packages into your current kernel.
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from google.cloud import bigquery
|
|
43
|
+
import pandas as pd
|
|
44
|
+
|
|
45
|
+
client = bigquery.Client(project=PROJECT_ID)
|
|
46
|
+
pd.set_option('display.max_colwidth', None)
|
|
47
|
+
|
|
48
|
+
# Register %%bigquery cell magic (auto-loaded in Colab, needed elsewhere)
|
|
49
|
+
%load_ext bigquery_magics
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
## Examples — SQL
|
|
54
|
+
|
|
55
|
+
Progressive examples from simplest to most advanced. `AI.COUNT_TOKENS(INPUT [, endpoint => ENDPOINT])` returns a `STRUCT<result INT64, full_response JSON>`.
|
|
56
|
+
|
|
57
|
+
### 1. Simplest call — count tokens in a literal string
|
|
58
|
+
|
|
59
|
+
`.result` is the integer token count. Token count isn't the same as word count.
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
query = """
|
|
63
|
+
SELECT AI.COUNT_TOKENS("Token count isn't always equal to word count.").result AS num_tokens
|
|
64
|
+
"""
|
|
65
|
+
client.query(query).to_dataframe()
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 2. Understand the full output — `result` + `full_response`
|
|
69
|
+
|
|
70
|
+
`AI.COUNT_TOKENS` returns a `STRUCT` with two fields. Use `.*` to see both, and use `JSON_*` extractors to pull apart `full_response`:
|
|
71
|
+
|
|
72
|
+
- **`result`** (INT64) — the total input token count
|
|
73
|
+
- **`full_response`** (JSON) — `totalTokens` plus a `promptTokensDetails` array giving the token count per input `modality` (always `TEXT` for this text-only function)
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
query = """
|
|
77
|
+
SELECT
|
|
78
|
+
ct.result AS num_tokens,
|
|
79
|
+
ct.full_response AS full_response,
|
|
80
|
+
INT64(ct.full_response.totalTokens) AS total_tokens,
|
|
81
|
+
STRING(ct.full_response.promptTokensDetails[0].modality) AS modality,
|
|
82
|
+
INT64(ct.full_response.promptTokensDetails[0].tokenCount) AS modality_token_count
|
|
83
|
+
FROM (
|
|
84
|
+
SELECT AI.COUNT_TOKENS('Summarize the quarterly earnings report.') AS ct
|
|
85
|
+
)
|
|
86
|
+
"""
|
|
87
|
+
client.query(query).to_dataframe()
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### 3. Count tokens over a table column
|
|
91
|
+
|
|
92
|
+
Apply it per row to real text — here, public IMDB movie reviews.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
query = """
|
|
96
|
+
SELECT
|
|
97
|
+
review,
|
|
98
|
+
AI.COUNT_TOKENS(review).result AS num_tokens
|
|
99
|
+
FROM `bigquery-public-data.imdb.reviews`
|
|
100
|
+
LIMIT 5
|
|
101
|
+
"""
|
|
102
|
+
client.query(query).to_dataframe()
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### 4. Specify a model endpoint
|
|
106
|
+
|
|
107
|
+
`endpoint` selects which model's tokenizer rules to use. If omitted, the default model used by `AI.GENERATE` is used.
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
query = """
|
|
111
|
+
SELECT
|
|
112
|
+
review,
|
|
113
|
+
AI.COUNT_TOKENS(review, endpoint => 'gemini-2.5-pro').result AS num_tokens
|
|
114
|
+
FROM `bigquery-public-data.imdb.reviews`
|
|
115
|
+
LIMIT 5
|
|
116
|
+
"""
|
|
117
|
+
client.query(query).to_dataframe()
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### 5. Estimate cost/size before a batch AI job
|
|
121
|
+
|
|
122
|
+
Because counting is free, aggregate token counts across a column to size a workload *before* running the paid generation functions over it.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
query = """
|
|
126
|
+
WITH counts AS (
|
|
127
|
+
SELECT AI.COUNT_TOKENS(review).result AS tokens
|
|
128
|
+
FROM `bigquery-public-data.imdb.reviews`
|
|
129
|
+
LIMIT 100
|
|
130
|
+
)
|
|
131
|
+
SELECT
|
|
132
|
+
COUNT(*) AS num_documents,
|
|
133
|
+
SUM(tokens) AS total_input_tokens,
|
|
134
|
+
ROUND(AVG(tokens), 1) AS avg_tokens_per_doc,
|
|
135
|
+
MAX(tokens) AS max_tokens
|
|
136
|
+
FROM counts
|
|
137
|
+
"""
|
|
138
|
+
client.query(query).to_dataframe()
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
---
|
|
142
|
+
## Examples — `%%bigquery` Magics
|
|
143
|
+
|
|
144
|
+
The same call using IPython magics — SQL directly in the cell.
|
|
145
|
+
|
|
146
|
+
### Count tokens with `%%bigquery`
|
|
147
|
+
|
|
148
|
+
```sql
|
|
149
|
+
%%bigquery --project {PROJECT_ID}
|
|
150
|
+
|
|
151
|
+
SELECT
|
|
152
|
+
review,
|
|
153
|
+
AI.COUNT_TOKENS(review).result AS num_tokens
|
|
154
|
+
FROM `bigquery-public-data.imdb.reviews`
|
|
155
|
+
LIMIT 5
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
## Examples — BigFrames
|
|
160
|
+
|
|
161
|
+
There is no native BigFrames API for `AI.COUNT_TOKENS` yet. Use `session.read_gbq_query()` to run the SQL and return a BigFrames DataFrame.
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
import bigframes.pandas as bpd
|
|
165
|
+
|
|
166
|
+
bpd.close_session() # Reset session to apply project/location settings
|
|
167
|
+
bpd.options.bigquery.project = PROJECT_ID
|
|
168
|
+
bpd.options.bigquery.location = LOCATION
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
query = f"""
|
|
173
|
+
SELECT
|
|
174
|
+
review,
|
|
175
|
+
AI.COUNT_TOKENS(review).result AS num_tokens
|
|
176
|
+
FROM `bigquery-public-data.imdb.reviews`
|
|
177
|
+
LIMIT 5
|
|
178
|
+
"""
|
|
179
|
+
bpd.read_gbq_query(query)
|
|
180
|
+
```
|