# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
BigQuery DataFrames (BigFrames) AI Functions#
Run in Colab
|
|
|
This notebook provides a brief introduction to AI functions in BigQuery Dataframes.
Preparation#
First, set up your BigFrames environment:
import bigframes.pandas as bpd
PROJECT_ID = "" # Your project ID here
bpd.options.bigquery.project = PROJECT_ID
bpd.options.bigquery.ordering_mode = "partial"
bpd.options.display.progress_bar = None
ai.generate#
The ai.generate function lets you analyze any combination of text and unstructured data from BigQuery. You can mix BigFrames or Pandas series with string literals as your prompt in the form of a tuple. You are also allowed to provide only a series. Here is an example:
import bigframes.bigquery as bbq
ingredients1 = bpd.Series(["Lettuce", "Sausage"])
ingredients2 = bpd.Series(["Cucumber", "Long Bread"])
prompt = ("What's the food made from ", ingredients1, " and ", ingredients2, " One word only")
bbq.ai.generate(prompt)
/usr/local/google/home/sycai/src/python-bigquery-dataframes/bigframes/core/global_session.py:103: DefaultLocationWarning: No explicit location is set, so using location US for the session.
_global_session = bigframes.session.connect(
0 {'result': 'Salad\n', 'full_response': '{"cand...
1 {'result': 'Sausageroll\n', 'full_response': '...
dtype: struct<result: string, full_response: extension<dbjson<JSONArrowType>>, status: string>[pyarrow]
The function returns a series of structs. The 'result' field holds the answer, while more metadata can be found in the 'full_response' field. The 'status' field tells you whether LLM made a successful response for that specific row.
You can also include additional model parameters into your function call, as long as they conform to the structure of generateContent request body format. In the next example, you use maxOutputTokens to limit the length of the generated content.
model_params = {
"generationConfig": {"maxOutputTokens": 2}
}
ingredients1 = bpd.Series(["Lettuce", "Sausage"])
ingredients2 = bpd.Series(["Cucumber", "Long Bread"])
prompt = ("What's the food made from ", ingredients1, " and ", ingredients2)
bbq.ai.generate(prompt, model_params=model_params).struct.field("result")
0 Lettuce
1 The food
Name: result, dtype: string
The answers are cut short as expected.
In addition to ai.generate, you can use ai.generate_bool, ai.generate_int, and ai.generate_double for other output types.
ai.if_#
ai.if_ generates a series of booleans. It’s a handy tool for joining and filtering your data, not only because it directly returns boolean values, but also because it provides more optimization during data processing. Here is an example of using ai.if_:
creatures = bpd.DataFrame({"creature": ["Cat", "Salmon"]})
categories = bpd.DataFrame({"category": ["mammal", "fish"]})
joined_df = creatures.merge(categories, how="cross")
condition = bbq.ai.if_((joined_df["creature"], " is a ", joined_df["category"]))
# Filter our dataframe
joined_df = joined_df[condition]
joined_df
| creature | category | |
|---|---|---|
| 0 | Cat | mammal |
| 1 | Salmon | fish |
2 rows × 2 columns
ai.score#
ai.score ranks your input based on the prompt and assigns a double value (i.e. a score) to each item. You can then sort your data based on their scores. For example:
df = bpd.DataFrame({'animals': ['tiger', 'spider', 'blue whale']})
df['relative_weight'] = bbq.ai.score(("Rank the relative weight of ", df['animals'], " on the scale from 1 to 10"))
df.sort_values(by='relative_weight')
| animals | relative_weight | |
|---|---|---|
| 1 | spider | 1.0 |
| 0 | tiger | 8.0 |
| 2 | blue whale | 10.0 |
3 rows × 2 columns
ai.classify#
ai.classify categories your inputs into the specified categories.
df = bpd.DataFrame({'animal': ['tiger', 'spider', 'blue whale', 'salmon']})
df['category'] = bbq.ai.classify(df['animal'], categories=['mammal', 'fish', 'anthropod'])
df
| animal | category | |
|---|---|---|
| 0 | tiger | mammal |
| 1 | spider | anthropod |
| 2 | blue whale | mammal |
| 3 | salmon | fish |
4 rows × 2 columns
Note that this function can only return the values that are provided in the categories argument. If your categories do not cover all cases, your may get wrong answers:
df = bpd.DataFrame({'animal': ['tiger', 'spider']})
df['category'] = bbq.ai.classify(df['animal'], categories=['mammal', 'fish']) # Spider belongs to neither category
df
| animal | category | |
|---|---|---|
| 0 | tiger | mammal |
| 1 | spider | mammal |
2 rows × 2 columns
Run in Colab