-
Notifications
You must be signed in to change notification settings - Fork 68
feat: add bigframes.bigquery.ai.generate_embedding
#2343
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
google-labs-jules
wants to merge
13
commits into
main
Choose a base branch
from
generate-embedding-impl-11924477578091076513
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+305
−33
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
0d793f9
feat: Implement AI.GENERATE_EMBEDDING wrapper
google-labs-jules[bot] 99bb8ec
Merge remote-tracking branch 'origin/main' into generate-embedding-im…
tswast 9a774ac
update some unit tests
tswast e904d32
Merge branch 'main' into generate-embedding-impl-11924477578091076513
tswast 26201e4
revert move to literals submodule
tswast 7056f4c
fix missing import
tswast fae425d
try again at literals import
tswast 2624a78
fix tests
tswast 93e92d9
fix docs
tswast f09cac6
fix lint and add imports
tswast e0cd6cb
types
tswast fa54cb2
Merge branch 'main' into generate-embedding-impl-11924477578091076513
tswast e8629d2
Merge branch 'main' into generate-embedding-impl-11924477578091076513
sycai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| # Copyright 2026 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 | ||
| # | ||
| # http://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. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import collections.abc | ||
| import json | ||
| from typing import Any, List, Mapping, Union | ||
|
|
||
| import bigframes.core.sql | ||
|
|
||
| STRUCT_VALUES = Union[ | ||
| str, int, float, bool, Mapping[str, str], List[str], Mapping[str, Any] | ||
| ] | ||
| STRUCT_TYPE = Mapping[str, STRUCT_VALUES] | ||
|
|
||
|
|
||
| def struct_literal(struct_options: STRUCT_TYPE) -> str: | ||
| rendered_options = [] | ||
| for option_name, option_value in struct_options.items(): | ||
| if option_name == "model_params": | ||
| json_str = json.dumps(option_value) | ||
| # Escape single quotes for SQL string literal | ||
| sql_json_str = json_str.replace("'", "''") | ||
| rendered_val = f"JSON'{sql_json_str}'" | ||
| elif isinstance(option_value, collections.abc.Mapping): | ||
| struct_body = ", ".join( | ||
| [ | ||
| f"{bigframes.core.sql.simple_literal(v)} AS {k}" | ||
| for k, v in option_value.items() | ||
| ] | ||
| ) | ||
| rendered_val = f"STRUCT({struct_body})" | ||
| elif isinstance(option_value, list): | ||
| rendered_val = ( | ||
| "[" | ||
| + ", ".join( | ||
| [bigframes.core.sql.simple_literal(v) for v in option_value] | ||
| ) | ||
| + "]" | ||
| ) | ||
| elif isinstance(option_value, bool): | ||
| rendered_val = str(option_value).lower() | ||
| else: | ||
| rendered_val = bigframes.core.sql.simple_literal(option_value) | ||
| rendered_options.append(f"{rendered_val} AS {option_name}") | ||
| return f"STRUCT({', '.join(rendered_options)})" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| # 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 | ||
| # | ||
| # http://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. | ||
|
|
||
| from unittest import mock | ||
|
|
||
| import pandas as pd | ||
| import pytest | ||
|
|
||
| import bigframes.bigquery as bbq | ||
| import bigframes.dataframe | ||
| import bigframes.series | ||
| import bigframes.session | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_session(): | ||
| return mock.create_autospec(spec=bigframes.session.Session) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_dataframe(mock_session): | ||
| df = mock.create_autospec(spec=bigframes.dataframe.DataFrame) | ||
| df._session = mock_session | ||
| df.sql = "SELECT * FROM my_table" | ||
| return df | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_series(mock_session): | ||
| series = mock.create_autospec(spec=bigframes.series.Series) | ||
| series._session = mock_session | ||
| # Mock to_frame to return a mock dataframe | ||
| df = mock.create_autospec(spec=bigframes.dataframe.DataFrame) | ||
| df._session = mock_session | ||
| df.sql = "SELECT my_col AS content FROM my_table" | ||
| series.copy.return_value = series | ||
| series.to_frame.return_value = df | ||
| return series | ||
|
|
||
|
|
||
| def test_generate_embedding_with_dataframe(mock_dataframe, mock_session): | ||
| model_name = "project.dataset.model" | ||
|
|
||
| bbq.ai.generate_embedding( | ||
| model_name, | ||
| mock_dataframe, | ||
| output_dimensionality=256, | ||
| ) | ||
|
|
||
| mock_session.read_gbq.assert_called_once() | ||
| query = mock_session.read_gbq.call_args[0][0] | ||
|
|
||
| # Normalize whitespace for comparison | ||
| query = " ".join(query.split()) | ||
|
|
||
| expected_part_1 = "SELECT * FROM AI.GENERATE_EMBEDDING(" | ||
| expected_part_2 = f"MODEL `{model_name}`," | ||
| expected_part_3 = "(SELECT * FROM my_table)," | ||
| expected_part_4 = "STRUCT(256 AS OUTPUT_DIMENSIONALITY)" | ||
|
|
||
| assert expected_part_1 in query | ||
| assert expected_part_2 in query | ||
| assert expected_part_3 in query | ||
| assert expected_part_4 in query | ||
|
|
||
|
|
||
| def test_generate_embedding_with_series(mock_series, mock_session): | ||
| model_name = "project.dataset.model" | ||
|
|
||
| bbq.ai.generate_embedding( | ||
| model_name, mock_series, start_second=0.0, end_second=10.0, interval_seconds=5.0 | ||
| ) | ||
|
|
||
| mock_session.read_gbq.assert_called_once() | ||
| query = mock_session.read_gbq.call_args[0][0] | ||
| query = " ".join(query.split()) | ||
|
|
||
| assert f"MODEL `{model_name}`" in query | ||
| assert "(SELECT my_col AS content FROM my_table)" in query | ||
| assert ( | ||
| "STRUCT(0.0 AS START_SECOND, 10.0 AS END_SECOND, 5.0 AS INTERVAL_SECONDS)" | ||
| in query | ||
| ) | ||
|
|
||
|
|
||
| def test_generate_embedding_defaults(mock_dataframe, mock_session): | ||
| model_name = "project.dataset.model" | ||
|
|
||
| bbq.ai.generate_embedding( | ||
| model_name, | ||
| mock_dataframe, | ||
| ) | ||
|
|
||
| mock_session.read_gbq.assert_called_once() | ||
| query = mock_session.read_gbq.call_args[0][0] | ||
| query = " ".join(query.split()) | ||
|
|
||
| assert f"MODEL `{model_name}`" in query | ||
| assert "STRUCT()" in query | ||
|
|
||
|
|
||
| @mock.patch("bigframes.pandas.read_pandas") | ||
| def test_generate_embedding_with_pandas_dataframe( | ||
| read_pandas_mock, mock_dataframe, mock_session | ||
| ): | ||
| # This tests that pandas input path works and calls read_pandas | ||
| model_name = "project.dataset.model" | ||
|
|
||
| # Mock return value of read_pandas to be a BigFrames DataFrame | ||
| read_pandas_mock.return_value = mock_dataframe | ||
|
|
||
| pandas_df = pd.DataFrame({"content": ["test"]}) | ||
|
|
||
| bbq.ai.generate_embedding( | ||
| model_name, | ||
| pandas_df, | ||
| ) | ||
|
|
||
| read_pandas_mock.assert_called_once() | ||
| # Check that read_pandas was called with something (the pandas df) | ||
| assert read_pandas_mock.call_args[0][0] is pandas_df | ||
|
|
||
| mock_session.read_gbq.assert_called_once() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does it make sense to expose this function as
bbq.ai.generate_embeddingtoo?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch! Done.