This repository was archived by the owner on Apr 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathsemantics.py
More file actions
1169 lines (952 loc) · 45.5 KB
/
semantics.py
File metadata and controls
1169 lines (952 loc) · 45.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2024 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.
import re
import typing
from typing import List, Optional
import warnings
import numpy as np
from bigframes import dtypes, exceptions
from bigframes.core import guid
from bigframes.core.logging import log_adapter
@log_adapter.class_logger
class Semantics:
def __init__(self, df) -> None:
import bigframes # Import in the function body to avoid circular imports.
import bigframes.dataframe
if not bigframes.options.experiments.semantic_operators:
raise NotImplementedError()
self._df: bigframes.dataframe.DataFrame = df
def agg(
self,
instruction: str,
model,
cluster_column: typing.Optional[str] = None,
max_agg_rows: int = 10,
ground_with_google_search: bool = False,
):
"""
Performs an aggregation over all rows of the table.
This method recursively aggregates the input data to produce partial answers
in parallel, until a single answer remains.
**Examples:**
>>> import bigframes.pandas as bpd
>>> bpd.options.experiments.semantic_operators = True
>>> bpd.options.compute.semantic_ops_confirmation_threshold = 25
>>> import bigframes.ml.llm as llm
>>> model = llm.GeminiTextGenerator(model_name="gemini-2.0-flash-001") # doctest: +SKIP
>>> df = bpd.DataFrame(
... {
... "Movies": [
... "Titanic",
... "The Wolf of Wall Street",
... "Inception",
... ],
... "Year": [1997, 2013, 2010],
... })
>>> df.semantics.agg( # doctest: +SKIP
... "Find the first name shared by all actors in {Movies}. One word answer.",
... model=model,
... )
0 Leonardo
<BLANKLINE>
Name: Movies, dtype: string
Args:
instruction (str):
An instruction on how to map the data. This value must contain
column references by name enclosed in braces.
For example, to reference a column named "movies", use "{movies}" in the
instruction, like: "Find actor names shared by all {movies}."
model (bigframes.ml.llm.GeminiTextGenerator):
A GeminiTextGenerator provided by the Bigframes ML package.
cluster_column (Optional[str], default None):
If set, aggregates each cluster before performing aggregations across
clusters. Clustering based on semantic similarity can improve accuracy
of the sementic aggregations.
max_agg_rows (int, default 10):
The maxinum number of rows to be aggregated at a time.
ground_with_google_search (bool, default False):
Enables Grounding with Google Search for the GeminiTextGenerator model.
When set to True, the model incorporates relevant information from Google
Search results into its responses, enhancing their accuracy and factualness.
Note: Using this feature may impact billing costs. Refer to the pricing
page for details: https://cloud.google.com/vertex-ai/generative-ai/pricing#google_models
The default is `False`.
Returns:
bigframes.dataframe.DataFrame: A new DataFrame with the aggregated answers.
Raises:
NotImplementedError: when the semantic operator experiment is off.
ValueError: when the instruction refers to a non-existing column, or when
more than one columns are referred to.
"""
import bigframes.bigquery as bbq
import bigframes.dataframe
import bigframes.series
self._validate_model(model)
columns = self._parse_columns(instruction)
if max_agg_rows <= 1:
raise ValueError(
f"Invalid value for `max_agg_rows`: {max_agg_rows}."
"It must be greater than 1."
)
work_estimate = len(self._df) * int(max_agg_rows / (max_agg_rows - 1))
self._confirm_operation(work_estimate)
df: bigframes.dataframe.DataFrame = self._df.copy()
for column in columns:
if column not in self._df.columns:
raise ValueError(f"Column {column} not found.")
if df[column].dtype != dtypes.STRING_DTYPE:
df[column] = df[column].astype(dtypes.STRING_DTYPE)
if len(columns) > 1:
raise NotImplementedError(
"Semantic aggregations are limited to a single column."
)
column = columns[0]
if ground_with_google_search:
msg = exceptions.format_message(
"Enables Grounding with Google Search may impact billing cost. See pricing "
"details: https://cloud.google.com/vertex-ai/generative-ai/pricing#google_models"
)
warnings.warn(msg, category=UserWarning)
user_instruction = self._format_instruction(instruction, columns)
num_cluster = 1
if cluster_column is not None:
if cluster_column not in df.columns:
raise ValueError(f"Cluster column `{cluster_column}` not found.")
if df[cluster_column].dtype != dtypes.INT_DTYPE:
raise TypeError(
"Cluster column must be an integer type, not "
f"{type(df[cluster_column])}"
)
num_cluster = df[cluster_column].unique().shape[0]
df = df.sort_values(cluster_column)
else:
cluster_column = guid.generate_guid("pid")
df[cluster_column] = 0
aggregation_group_id = guid.generate_guid("agg")
group_row_index = guid.generate_guid("gid")
llm_prompt = guid.generate_guid("prompt")
df = (
df.reset_index(drop=True)
.reset_index()
.rename(columns={"index": aggregation_group_id})
)
output_instruction = (
"Answer user instructions using the provided context from various sources. "
"Combine all relevant information into a single, concise, well-structured response. "
f"Instruction: {user_instruction}.\n\n"
)
while len(df) > 1:
df[group_row_index] = (df[aggregation_group_id] % max_agg_rows + 1).astype(
dtypes.STRING_DTYPE
)
df[aggregation_group_id] = (df[aggregation_group_id] / max_agg_rows).astype(
dtypes.INT_DTYPE
)
df[llm_prompt] = "\t\nSource #" + df[group_row_index] + ": " + df[column]
if len(df) > num_cluster:
# Aggregate within each partition
agg_df = bbq.array_agg(
df.groupby(by=[cluster_column, aggregation_group_id])
)
else:
# Aggregate cross partitions
agg_df = bbq.array_agg(df.groupby(by=[aggregation_group_id]))
agg_df[cluster_column] = agg_df[cluster_column].list[0]
# Skip if the aggregated group only has a single item
single_row_df: bigframes.series.Series = bbq.array_to_string(
agg_df[agg_df[group_row_index].list.len() <= 1][column],
delimiter="",
)
prompt_s: bigframes.series.Series = bbq.array_to_string(
agg_df[agg_df[group_row_index].list.len() > 1][llm_prompt],
delimiter="",
)
prompt_s = output_instruction + prompt_s # type:ignore
# Run model
predict_df = typing.cast(
bigframes.dataframe.DataFrame,
model.predict(
prompt_s,
temperature=0.0,
ground_with_google_search=ground_with_google_search,
),
)
agg_df[column] = predict_df["ml_generate_text_llm_result"].combine_first(
single_row_df
)
agg_df = agg_df.reset_index()
df = agg_df[[aggregation_group_id, cluster_column, column]]
return df[column]
def cluster_by(
self,
column: str,
output_column: str,
model,
n_clusters: int = 5,
):
"""
Clusters data based on the semantic similarity of text within a specified column.
This method leverages a language model to generate text embeddings for each value in
the given column. These embeddings capture the semantic meaning of the text.
The data is then grouped into `n` clusters using the k-means clustering algorithm,
which groups data points based on the similarity of their embeddings.
**Examples:**
>>> import bigframes.pandas as bpd
>>> bpd.options.experiments.semantic_operators = True
>>> bpd.options.compute.semantic_ops_confirmation_threshold = 25
>>> import bigframes.ml.llm as llm
>>> model = llm.TextEmbeddingGenerator(model_name="text-embedding-005")
>>> df = bpd.DataFrame({
... "Product": ["Smartphone", "Laptop", "T-shirt", "Jeans"],
... })
>>> df.semantics.cluster_by("Product", "Cluster ID", model, n_clusters=2) # doctest: +SKIP
Product Cluster ID
0 Smartphone 2
1 Laptop 2
2 T-shirt 1
3 Jeans 1
<BLANKLINE>
[4 rows x 2 columns]
Args:
column (str):
An column name to perform the similarity clustering.
output_column (str):
An output column to store the clustering ID.
model (bigframes.ml.llm.TextEmbeddingGenerator):
A TextEmbeddingGenerator provided by Bigframes ML package.
n_clusters (int, default 5):
Default 5. Number of clusters to be detected.
Returns:
bigframes.dataframe.DataFrame: A new DataFrame with the clustering output column.
Raises:
NotImplementedError: when the semantic operator experiment is off.
ValueError: when the column refers to a non-existing column.
"""
import bigframes.dataframe
import bigframes.ml.cluster as cluster
import bigframes.ml.llm as llm
if not isinstance(model, llm.TextEmbeddingGenerator):
raise TypeError(f"Expect a text embedding model, but got: {type(model)}")
if column not in self._df.columns:
raise ValueError(f"Column {column} not found.")
if n_clusters <= 1:
raise ValueError(
f"Invalid value for `n_clusters`: {n_clusters}."
"It must be greater than 1."
)
self._confirm_operation(len(self._df))
df: bigframes.dataframe.DataFrame = self._df.copy()
embeddings_df = model.predict(df[column])
cluster_model = cluster.KMeans(n_clusters=n_clusters)
cluster_model.fit(embeddings_df[["ml_generate_embedding_result"]])
clustered_result = cluster_model.predict(embeddings_df)
df[output_column] = clustered_result["CENTROID_ID"]
return df
def filter(self, instruction: str, model, ground_with_google_search: bool = False):
"""
Filters the DataFrame with the semantics of the user instruction.
**Examples:**
>>> import bigframes.pandas as bpd
>>> bpd.options.experiments.semantic_operators = True
>>> bpd.options.compute.semantic_ops_confirmation_threshold = 25
>>> import bigframes.ml.llm as llm
>>> model = llm.GeminiTextGenerator(model_name="gemini-2.0-flash-001") # doctest: +SKIP
>>> df = bpd.DataFrame({"country": ["USA", "Germany"], "city": ["Seattle", "Berlin"]})
>>> df.semantics.filter("{city} is the capital of {country}", model) # doctest: +SKIP
country city
1 Germany Berlin
<BLANKLINE>
[1 rows x 2 columns]
Args:
instruction (str):
An instruction on how to filter the data. This value must contain
column references by name, which should be wrapped in a pair of braces.
For example, if you have a column "food", you can refer to this column
in the instructions like:
"The {food} is healthy."
model (bigframes.ml.llm.GeminiTextGenerator):
A GeminiTextGenerator provided by Bigframes ML package.
ground_with_google_search (bool, default False):
Enables Grounding with Google Search for the GeminiTextGenerator model.
When set to True, the model incorporates relevant information from Google
Search results into its responses, enhancing their accuracy and factualness.
Note: Using this feature may impact billing costs. Refer to the pricing
page for details: https://cloud.google.com/vertex-ai/generative-ai/pricing#google_models
The default is `False`.
Returns:
bigframes.pandas.DataFrame: DataFrame filtered by the instruction.
Raises:
NotImplementedError: when the semantic operator experiment is off.
ValueError: when the instruction refers to a non-existing column, or when no
columns are referred to.
"""
import bigframes.dataframe
import bigframes.series
self._validate_model(model)
columns = self._parse_columns(instruction)
for column in columns:
if column not in self._df.columns:
raise ValueError(f"Column {column} not found.")
if ground_with_google_search:
msg = exceptions.format_message(
"Enables Grounding with Google Search may impact billing cost. See pricing "
"details: https://cloud.google.com/vertex-ai/generative-ai/pricing#google_models"
)
warnings.warn(msg, category=UserWarning)
self._confirm_operation(len(self._df))
df: bigframes.dataframe.DataFrame = self._df[columns].copy()
has_blob_column = False
for column in columns:
if df[column].dtype == dtypes.OBJ_REF_DTYPE:
# Don't cast ObjectRef columns to string
has_blob_column = True
continue
if df[column].dtype != dtypes.STRING_DTYPE:
df[column] = df[column].astype(dtypes.STRING_DTYPE)
user_instruction = self._format_instruction(instruction, columns)
output_instruction = "Based on the provided context, reply to the following claim by only True or False:"
if has_blob_column:
results = typing.cast(
bigframes.dataframe.DataFrame,
model.predict(
df,
prompt=self._make_multimodel_prompt(
df, columns, user_instruction, output_instruction
),
temperature=0.0,
ground_with_google_search=ground_with_google_search,
),
)
else:
results = typing.cast(
bigframes.dataframe.DataFrame,
model.predict(
self._make_text_prompt(
df, columns, user_instruction, output_instruction
),
temperature=0.0,
ground_with_google_search=ground_with_google_search,
),
)
return self._df[
results["ml_generate_text_llm_result"].str.lower().str.contains("true")
]
def map(
self,
instruction: str,
output_column: str,
model,
ground_with_google_search: bool = False,
):
"""
Maps the DataFrame with the semantics of the user instruction.
**Examples:**
>>> import bigframes.pandas as bpd
>>> bpd.options.experiments.semantic_operators = True
>>> bpd.options.compute.semantic_ops_confirmation_threshold = 25
>>> import bigframes.ml.llm as llm
>>> model = llm.GeminiTextGenerator(model_name="gemini-2.0-flash-001") # doctest: +SKIP
>>> df = bpd.DataFrame({"ingredient_1": ["Burger Bun", "Soy Bean"], "ingredient_2": ["Beef Patty", "Bittern"]})
>>> df.semantics.map("What is the food made from {ingredient_1} and {ingredient_2}? One word only.", output_column="food", model=model) # doctest: +SKIP
ingredient_1 ingredient_2 food
0 Burger Bun Beef Patty Burger
<BLANKLINE>
1 Soy Bean Bittern Tofu
<BLANKLINE>
<BLANKLINE>
[2 rows x 3 columns]
Args:
instruction (str):
An instruction on how to map the data. This value must contain
column references by name, which should be wrapped in a pair of braces.
For example, if you have a column "food", you can refer to this column
in the instructions like:
"Get the ingredients of {food}."
output_column (str):
The column name of the mapping result.
model (bigframes.ml.llm.GeminiTextGenerator):
A GeminiTextGenerator provided by Bigframes ML package.
ground_with_google_search (bool, default False):
Enables Grounding with Google Search for the GeminiTextGenerator model.
When set to True, the model incorporates relevant information from Google
Search results into its responses, enhancing their accuracy and factualness.
Note: Using this feature may impact billing costs. Refer to the pricing
page for details: https://cloud.google.com/vertex-ai/generative-ai/pricing#google_models
The default is `False`.
Returns:
bigframes.pandas.DataFrame: DataFrame with attached mapping results.
Raises:
NotImplementedError: when the semantic operator experiment is off.
ValueError: when the instruction refers to a non-existing column, or when no
columns are referred to.
"""
import bigframes.dataframe
import bigframes.series
self._validate_model(model)
columns = self._parse_columns(instruction)
for column in columns:
if column not in self._df.columns:
raise ValueError(f"Column {column} not found.")
if ground_with_google_search:
msg = exceptions.format_message(
"Enables Grounding with Google Search may impact billing cost. See pricing "
"details: https://cloud.google.com/vertex-ai/generative-ai/pricing#google_models"
)
warnings.warn(msg, category=UserWarning)
self._confirm_operation(len(self._df))
df: bigframes.dataframe.DataFrame = self._df[columns].copy()
has_blob_column = False
for column in columns:
if df[column].dtype == dtypes.OBJ_REF_DTYPE:
# Don't cast ObjectRef columns to string
has_blob_column = True
continue
if df[column].dtype != dtypes.STRING_DTYPE:
df[column] = df[column].astype(dtypes.STRING_DTYPE)
user_instruction = self._format_instruction(instruction, columns)
output_instruction = (
"Based on the provided contenxt, answer the following instruction:"
)
if has_blob_column:
results = typing.cast(
bigframes.series.Series,
model.predict(
df,
prompt=self._make_multimodel_prompt(
df, columns, user_instruction, output_instruction
),
temperature=0.0,
ground_with_google_search=ground_with_google_search,
)["ml_generate_text_llm_result"],
)
else:
results = typing.cast(
bigframes.series.Series,
model.predict(
self._make_text_prompt(
df, columns, user_instruction, output_instruction
),
temperature=0.0,
ground_with_google_search=ground_with_google_search,
)["ml_generate_text_llm_result"],
)
from bigframes.core.reshape.api import concat
return concat([self._df, results.rename(output_column)], axis=1)
def join(
self,
other,
instruction: str,
model,
ground_with_google_search: bool = False,
):
"""
Joines two dataframes by applying the instruction over each pair of rows from
the left and right table.
**Examples:**
>>> import bigframes.pandas as bpd
>>> bpd.options.experiments.semantic_operators = True
>>> bpd.options.compute.semantic_ops_confirmation_threshold = 25
>>> import bigframes.ml.llm as llm
>>> model = llm.GeminiTextGenerator(model_name="gemini-2.0-flash-001") # doctest: +SKIP
>>> cities = bpd.DataFrame({'city': ['Seattle', 'Ottawa', 'Berlin', 'Shanghai', 'New Delhi']})
>>> continents = bpd.DataFrame({'continent': ['North America', 'Africa', 'Asia']})
>>> cities.semantics.join(continents, "{city} is in {continent}", model) # doctest: +SKIP
city continent
0 Seattle North America
1 Ottawa North America
2 Shanghai Asia
3 New Delhi Asia
<BLANKLINE>
[4 rows x 2 columns]
Args:
other (bigframes.pandas.DataFrame):
The other dataframe.
instruction (str):
An instruction on how left and right rows can be joined. This value must contain
column references by name. which should be wrapped in a pair of braces.
For example: "The {city} belongs to the {country}".
For column names that are shared between two dataframes, you need to add "left."
and "right." prefix for differentiation. This is especially important when you do
self joins. For example: "The {left.employee_name} reports to {right.employee_name}"
For unique column names, this prefix is optional.
model (bigframes.ml.llm.GeminiTextGenerator):
A GeminiTextGenerator provided by Bigframes ML package.
max_rows (int, default 1000):
The maximum number of rows allowed to be sent to the model per call. If the result is too large, the method
call will end early with an error.
ground_with_google_search (bool, default False):
Enables Grounding with Google Search for the GeminiTextGenerator model.
When set to True, the model incorporates relevant information from Google
Search results into its responses, enhancing their accuracy and factualness.
Note: Using this feature may impact billing costs. Refer to the pricing
page for details: https://cloud.google.com/vertex-ai/generative-ai/pricing#google_models
The default is `False`.
Returns:
bigframes.pandas.DataFrame: The joined dataframe.
Raises:
ValueError if the amount of data that will be sent for LLM processing is larger than max_rows.
"""
self._validate_model(model)
columns = self._parse_columns(instruction)
if ground_with_google_search:
msg = exceptions.format_message(
"Enables Grounding with Google Search may impact billing cost. See pricing "
"details: https://cloud.google.com/vertex-ai/generative-ai/pricing#google_models"
)
warnings.warn(msg, category=UserWarning)
work_estimate = len(self._df) * len(other)
self._confirm_operation(work_estimate)
left_columns = []
right_columns = []
for col in columns:
if col in self._df.columns and col in other.columns:
raise ValueError(f"Ambiguous column reference: {col}")
elif col in self._df.columns:
left_columns.append(col)
elif col in other.columns:
right_columns.append(col)
elif col.startswith("left."):
original_col_name = col[len("left.") :]
if (
original_col_name in self._df.columns
and original_col_name in other.columns
):
left_columns.append(col)
elif original_col_name in self._df.columns:
left_columns.append(col)
instruction = instruction.replace(col, original_col_name)
else:
raise ValueError(f"Column {col} not found")
elif col.startswith("right."):
original_col_name = col[len("right.") :]
if (
original_col_name in self._df.columns
and original_col_name in other.columns
):
right_columns.append(col)
elif original_col_name in other.columns:
right_columns.append(col)
instruction = instruction.replace(col, original_col_name)
else:
raise ValueError(f"Column {col} not found")
else:
raise ValueError(f"Column {col} not found")
if not left_columns:
raise ValueError("No left column references.")
if not right_columns:
raise ValueError("No right column references.")
# Update column references to be compatible with internal naming scheme.
# That is, "left.col" -> "col_left" and "right.col" -> "col_right"
instruction = re.sub(r"(?<!{){left\.(\w+)}(?!})", r"{\1_left}", instruction)
instruction = re.sub(r"(?<!{){right\.(\w+)}(?!})", r"{\1_right}", instruction)
joined_df = self._df.merge(other, how="cross", suffixes=("_left", "_right"))
return joined_df.semantics.filter(
instruction, model, ground_with_google_search=ground_with_google_search
).reset_index(drop=True)
def search(
self,
search_column: str,
query: str,
top_k: int,
model,
score_column: Optional[str] = None,
):
"""
Performs semantic search on the DataFrame.
** Examples: **
>>> import bigframes.pandas as bpd
>>> import bigframes
>>> bigframes.options.experiments.semantic_operators = True
>>> bpd.options.compute.semantic_ops_confirmation_threshold = 25
>>> import bigframes.ml.llm as llm
>>> model = llm.TextEmbeddingGenerator(model_name="text-embedding-005") # doctest: +SKIP
>>> df = bpd.DataFrame({"creatures": ["salmon", "sea urchin", "frog", "chimpanzee"]})
>>> df.semantics.search("creatures", "monkey", top_k=1, model=model, score_column='distance') # doctest: +SKIP
creatures distance
3 chimpanzee 0.635844
<BLANKLINE>
[1 rows x 2 columns]
Args:
search_column:
The name of the column to search from.
query (str):
The search query.
top_k (int):
The number of nearest neighbors to return.
model (TextEmbeddingGenerator):
A TextEmbeddingGenerator provided by Bigframes ML package.
score_column (Optional[str], default None):
The name of the the additional column containning the similarity scores. If None,
this column won't be attached to the result.
Returns:
DataFrame: the DataFrame with the search result.
Raises:
ValueError: when the search_column is not found from the the data frame.
TypeError: when the provided model is not TextEmbeddingGenerator.
"""
if search_column not in self._df.columns:
raise ValueError(f"Column `{search_column}` not found")
self._confirm_operation(len(self._df))
import bigframes.ml.llm as llm
if not isinstance(model, llm.TextEmbeddingGenerator):
raise TypeError(f"Expect a text embedding model, but got: {type(model)}")
if top_k < 1:
raise ValueError("top_k must be an integer greater than or equal to 1.")
embedded_df = model.predict(self._df[search_column])
embedded_table = embedded_df.reset_index().to_gbq()
import bigframes.pandas as bpd
embedding_result_column = "ml_generate_embedding_result"
query_df = model.predict(bpd.DataFrame({"query_id": [query]})).rename(
columns={"content": "query_id", embedding_result_column: "embedding"}
)
import bigframes.bigquery as bbq
search_result = (
bbq.vector_search(
base_table=embedded_table,
column_to_search=embedding_result_column,
query=query_df,
top_k=top_k,
)
.rename(columns={"content": search_column})
.set_index("index")
)
search_result.index.name = self._df.index.name
if score_column is not None:
search_result = search_result.rename(columns={"distance": score_column})[
[search_column, score_column]
]
else:
search_result = search_result[[search_column]]
import bigframes.dataframe
return typing.cast(bigframes.dataframe.DataFrame, search_result)
def top_k(
self,
instruction: str,
model,
k: int = 10,
ground_with_google_search: bool = False,
):
"""
Ranks each tuple and returns the k best according to the instruction.
This method employs a quick select algorithm to efficiently compare the pivot
with all other items. By leveraging an LLM (Large Language Model), it then
identifies the top 'k' best answers from these comparisons.
**Examples:**
>>> import bigframes.pandas as bpd
>>> bpd.options.experiments.semantic_operators = True
>>> bpd.options.compute.semantic_ops_confirmation_threshold = 25
>>> import bigframes.ml.llm as llm
>>> model = llm.GeminiTextGenerator(model_name="gemini-2.0-flash-001") # doctest: +SKIP
>>> df = bpd.DataFrame(
... {
... "Animals": ["Dog", "Bird", "Cat", "Horse"],
... "Sounds": ["Woof", "Chirp", "Meow", "Neigh"],
... })
>>> df.semantics.top_k("{Animals} are more popular as pets", model=model, k=2) # doctest: +SKIP
Animals Sounds
0 Dog Woof
2 Cat Meow
<BLANKLINE>
[2 rows x 2 columns]
Args:
instruction (str):
An instruction on how to map the data. This value must contain
column references by name enclosed in braces.
For example, to reference a column named "Animals", use "{Animals}" in the
instruction, like: "{Animals} are more popular as pets"
model (bigframes.ml.llm.GeminiTextGenerator):
A GeminiTextGenerator provided by the Bigframes ML package.
k (int, default 10):
The number of rows to return.
ground_with_google_search (bool, default False):
Enables Grounding with Google Search for the GeminiTextGenerator model.
When set to True, the model incorporates relevant information from Google
Search results into its responses, enhancing their accuracy and factualness.
Note: Using this feature may impact billing costs. Refer to the pricing
page for details: https://cloud.google.com/vertex-ai/generative-ai/pricing#google_models
The default is `False`.
Returns:
bigframes.dataframe.DataFrame: A new DataFrame with the top k rows.
Raises:
NotImplementedError: when the semantic operator experiment is off.
ValueError: when the instruction refers to a non-existing column, or when no
columns are referred to.
"""
import bigframes.dataframe
import bigframes.series
self._validate_model(model)
columns = self._parse_columns(instruction)
for column in columns:
if column not in self._df.columns:
raise ValueError(f"Column {column} not found.")
if len(columns) > 1:
raise NotImplementedError("Semantic top K are limited to a single column.")
if ground_with_google_search:
msg = exceptions.format_message(
"Enables Grounding with Google Search may impact billing cost. See pricing "
"details: https://cloud.google.com/vertex-ai/generative-ai/pricing#google_models"
)
warnings.warn(msg, category=UserWarning)
work_estimate = int(len(self._df) * (len(self._df) - 1) / 2)
self._confirm_operation(work_estimate)
df: bigframes.dataframe.DataFrame = self._df[columns].copy()
column = columns[0]
if df[column].dtype != dtypes.STRING_DTYPE:
df[column] = df[column].astype(dtypes.STRING_DTYPE)
# `index` is reserved for the `reset_index` below.
if column == "index":
raise ValueError(
"Column name 'index' is reserved. Please choose a different name."
)
if k < 1:
raise ValueError("k must be an integer greater than or equal to 1.")
user_instruction = self._format_instruction(instruction, columns)
n = df.shape[0]
if k >= n:
return df
# Create a unique index and duplicate it as the "index" column. This workaround
# is needed for the select search algorithm due to unimplemented bigFrame methods.
df = df.reset_index().rename(columns={"index": "old_index"}).reset_index()
# Initialize a status column to track the selection status of each item.
# - None: Unknown/not yet processed
# - 1.0: Selected as part of the top-k items
# - -1.0: Excluded from the top-k items
status_column = guid.generate_guid("status")
df[status_column] = bigframes.series.Series(
None, dtype=dtypes.FLOAT_DTYPE, session=df._session
)
num_selected = 0
while num_selected < k:
df, num_new_selected = self._topk_partition(
df,
column,
status_column,
user_instruction,
model,
k - num_selected,
ground_with_google_search,
)
num_selected += num_new_selected
result_df: bigframes.dataframe.DataFrame = self._df.copy()
return result_df[df.set_index("old_index")[status_column] > 0.0]
@staticmethod
def _topk_partition(
df,
column: str,
status_column: str,
user_instruction: str,
model,
k: int,
ground_with_google_search: bool,
):
output_instruction = (
"Given a question and two documents, choose the document that best answers "
"the question. Respond with 'Document 1' or 'Document 2'. You must choose "
"one, even if neither is ideal. "
)
# Random pivot selection for improved average quickselect performance.
pending_df = df[df[status_column].isna()]
pivot_iloc = np.random.randint(0, pending_df.shape[0])
pivot_index = pending_df.iloc[pivot_iloc]["index"]
pivot_df = pending_df[pending_df["index"] == pivot_index]
# Build a prompt to compare the pivot item's relevance to other pending items.
prompt_s = pending_df[pending_df["index"] != pivot_index][column]
prompt_s = (
f"{output_instruction}\n\nQuestion: {user_instruction}\n"
+ f"\nDocument 1: {column} "
+ pivot_df.iloc[0][column]
+ f"\nDocument 2: {column} "
+ prompt_s # type:ignore
)
import bigframes.dataframe
predict_df = typing.cast(
bigframes.dataframe.DataFrame,
model.predict(
prompt_s,
temperature=0.0,
ground_with_google_search=ground_with_google_search,
),
)
marks = predict_df["ml_generate_text_llm_result"].str.contains("2")
more_relavant: bigframes.dataframe.DataFrame = df[marks]
less_relavent: bigframes.dataframe.DataFrame = df[~marks]
num_more_relavant = more_relavant.shape[0]
if k < num_more_relavant:
less_relavent[status_column] = -1.0
pivot_df[status_column] = -1.0
df = df.combine_first(less_relavent).combine_first(pivot_df)
return df, 0
else: # k >= num_more_relavant
more_relavant[status_column] = 1.0
df = df.combine_first(more_relavant)
if k >= num_more_relavant + 1:
pivot_df[status_column] = 1.0
df = df.combine_first(pivot_df)
return df, num_more_relavant + 1
else:
return df, num_more_relavant
def sim_join(
self,
other,
left_on: str,
right_on: str,
model,
top_k: int = 3,
score_column: Optional[str] = None,
max_rows: int = 1000,
):
"""
Joins two dataframes based on the similarity of the specified columns.
This method uses BigQuery's VECTOR_SEARCH function to match rows on the left side with the rows that have
nearest embedding vectors on the right. In the worst case scenario, the complexity is around O(M * N * log K).
Therefore, this is a potentially expensive operation.
** Examples: **
>>> import bigframes.pandas as bpd
>>> bpd.options.experiments.semantic_operators = True
>>> bpd.options.compute.semantic_ops_confirmation_threshold = 25