|
26 | 26 | from bigframes import clients, dataframe, dtypes |
27 | 27 | from bigframes import pandas as bpd |
28 | 28 | from bigframes import series, session |
| 29 | +from bigframes.bigquery._operations import utils as bq_utils |
29 | 30 | from bigframes.core import convert |
30 | 31 | from bigframes.core.logging import log_adapter |
31 | 32 | import bigframes.core.sql.literals |
@@ -391,7 +392,7 @@ def generate_double( |
391 | 392 |
|
392 | 393 | @log_adapter.method_logger(custom_base_name="bigquery_ai") |
393 | 394 | def generate_embedding( |
394 | | - model_name: str, |
| 395 | + model: Union[bigframes.ml.base.BaseEstimator, str, pd.Series], |
395 | 396 | data: Union[dataframe.DataFrame, series.Series, pd.DataFrame, pd.Series], |
396 | 397 | *, |
397 | 398 | output_dimensionality: Optional[int] = None, |
@@ -415,9 +416,8 @@ def generate_embedding( |
415 | 416 | ... ) # doctest: +SKIP |
416 | 417 |
|
417 | 418 | Args: |
418 | | - model_name (str): |
419 | | - The name of a remote model from Vertex AI, such as the |
420 | | - multimodalembedding@001 model. |
| 419 | + model (bigframes.ml.base.BaseEstimator or str): |
| 420 | + The model to use for text embedding. |
421 | 421 | data (bigframes.pandas.DataFrame or bigframes.pandas.Series): |
422 | 422 | The data to generate embeddings for. If a Series is provided, it is |
423 | 423 | treated as the 'content' column. If a DataFrame is provided, it |
@@ -454,20 +454,9 @@ def generate_embedding( |
454 | 454 | <https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-ai-generate-embedding#output>`_ |
455 | 455 | for details. |
456 | 456 | """ |
457 | | - if isinstance(data, (pd.DataFrame, pd.Series)): |
458 | | - data = bpd.read_pandas(data) |
459 | | - |
460 | | - if isinstance(data, series.Series): |
461 | | - data = data.copy() |
462 | | - data.name = "content" |
463 | | - data_df = data.to_frame() |
464 | | - elif isinstance(data, dataframe.DataFrame): |
465 | | - data_df = data |
466 | | - else: |
467 | | - raise ValueError(f"Unsupported data type: {type(data)}") |
468 | | - |
469 | | - # We need to get the SQL for the input data to pass as a subquery to the TVF |
470 | | - source_sql = data_df.sql |
| 457 | + data = _to_dataframe(data, series_rename="content") |
| 458 | + model_name, session = bq_utils.get_model_name_and_session(model, data) |
| 459 | + table_sql = bq_utils.to_sql(data) |
471 | 460 |
|
472 | 461 | struct_fields: Dict[str, bigframes.core.sql.literals.STRUCT_VALUES] = {} |
473 | 462 | if output_dimensionality is not None: |
@@ -488,12 +477,128 @@ def generate_embedding( |
488 | 477 | SELECT * |
489 | 478 | FROM AI.GENERATE_EMBEDDING( |
490 | 479 | MODEL `{model_name}`, |
491 | | - ({source_sql}), |
492 | | - {bigframes.core.sql.literals.struct_literal(struct_fields)}) |
| 480 | + ({table_sql}), |
| 481 | + {bigframes.core.sql.literals.struct_literal(struct_fields)} |
493 | 482 | ) |
494 | 483 | """ |
495 | 484 |
|
496 | | - return data_df._session.read_gbq(query) |
| 485 | + if session is None: |
| 486 | + return bpd.read_gbq_query(query) |
| 487 | + else: |
| 488 | + return session.read_gbq_query(query) |
| 489 | + |
| 490 | + |
| 491 | +@log_adapter.method_logger(custom_base_name="bigquery_ai") |
| 492 | +def generate_text( |
| 493 | + model: Union[bigframes.ml.base.BaseEstimator, str, pd.Series], |
| 494 | + data: Union[dataframe.DataFrame, series.Series, pd.DataFrame, pd.Series], |
| 495 | + *, |
| 496 | + temperature: Optional[float] = None, |
| 497 | + max_output_tokens: Optional[int] = None, |
| 498 | + top_k: Optional[int] = None, |
| 499 | + top_p: Optional[float] = None, |
| 500 | + stop_sequences: Optional[List[str]] = None, |
| 501 | + ground_with_google_search: Optional[bool] = None, |
| 502 | + request_type: Optional[str] = None, |
| 503 | +) -> dataframe.DataFrame: |
| 504 | + """ |
| 505 | + Generates text using a BigQuery ML model. |
| 506 | +
|
| 507 | + See the `BigQuery ML GENERATE_TEXT function syntax |
| 508 | + <https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-generate-text>`_ |
| 509 | + for additional reference. |
| 510 | +
|
| 511 | + **Examples:** |
| 512 | +
|
| 513 | + >>> import bigframes.pandas as bpd |
| 514 | + >>> import bigframes.bigquery as bbq |
| 515 | + >>> df = bpd.DataFrame({"prompt": ["write a poem about apples"]}) |
| 516 | + >>> bbq.ai.generate_text( |
| 517 | + ... "project.dataset.model_name", |
| 518 | + ... df |
| 519 | + ... ) # doctest: +SKIP |
| 520 | +
|
| 521 | + Args: |
| 522 | + model (bigframes.ml.base.BaseEstimator or str): |
| 523 | + The model to use for text generation. |
| 524 | + data (bigframes.pandas.DataFrame or bigframes.pandas.Series): |
| 525 | + The data to generate embeddings for. If a Series is provided, it is |
| 526 | + treated as the 'content' column. If a DataFrame is provided, it |
| 527 | + must contain a 'content' column, or you must rename the column you |
| 528 | + wish to embed to 'content'. |
| 529 | + temperature (float, optional): |
| 530 | + A FLOAT64 value that is used for sampling promiscuity. The value |
| 531 | + must be in the range ``[0.0, 1.0]``. A lower temperature works well |
| 532 | + for prompts that expect a more deterministic and less open-ended |
| 533 | + or creative response, while a higher temperature can lead to more |
| 534 | + diverse or creative results. A temperature of ``0`` is |
| 535 | + deterministic, meaning that the highest probability response is |
| 536 | + always selected. |
| 537 | + max_output_tokens (int, optional): |
| 538 | + An INT64 value that sets the maximum number of tokens in the |
| 539 | + generated text. |
| 540 | + top_k (int, optional): |
| 541 | + An INT64 value that changes how the model selects tokens for |
| 542 | + output. A ``top_k`` of ``1`` means the next selected token is the |
| 543 | + most probable among all tokens in the model's vocabulary. A |
| 544 | + ``top_k`` of ``3`` means that the next token is selected from |
| 545 | + among the three most probable tokens by using temperature. The |
| 546 | + default value is ``40``. |
| 547 | + top_p (float, optional): |
| 548 | + A FLOAT64 value that changes how the model selects tokens for |
| 549 | + output. Tokens are selected from most probable to least probable |
| 550 | + until the sum of their probabilities equals the ``top_p`` value. |
| 551 | + For example, if tokens A, B, and C have a probability of 0.3, 0.2, |
| 552 | + and 0.1 and the ``top_p`` value is ``0.5``, then the model will |
| 553 | + select either A or B as the next token by using temperature. The |
| 554 | + default value is ``0.95``. |
| 555 | + stop_sequences (List[str], optional): |
| 556 | + An ARRAY<STRING> value that contains the stop sequences for the model. |
| 557 | + ground_with_google_search (bool, optional): |
| 558 | + A BOOL value that determines whether to ground the model with Google Search. |
| 559 | + request_type (str, optional): |
| 560 | + A STRING value that contains the request type for the model. |
| 561 | +
|
| 562 | + Returns: |
| 563 | + bigframes.pandas.DataFrame: |
| 564 | + The generated text. |
| 565 | + """ |
| 566 | + data = _to_dataframe(data, series_rename="prompt") |
| 567 | + model_name, session = bq_utils.get_model_name_and_session(model, data) |
| 568 | + table_sql = bq_utils.to_sql(data) |
| 569 | + |
| 570 | + struct_fields: Dict[ |
| 571 | + str, |
| 572 | + Union[str, int, float, bool, Mapping[str, str], List[str], Mapping[str, Any]], |
| 573 | + ] = {} |
| 574 | + if temperature is not None: |
| 575 | + struct_fields["TEMPERATURE"] = temperature |
| 576 | + if max_output_tokens is not None: |
| 577 | + struct_fields["MAX_OUTPUT_TOKENS"] = max_output_tokens |
| 578 | + if top_k is not None: |
| 579 | + struct_fields["TOP_K"] = top_k |
| 580 | + if top_p is not None: |
| 581 | + struct_fields["TOP_P"] = top_p |
| 582 | + if stop_sequences is not None: |
| 583 | + struct_fields["STEP_SEQUENCES"] = stop_sequences |
| 584 | + if ground_with_google_search is not None: |
| 585 | + struct_fields["GROUND_WITH_GOOGLE_SEARCH"] = ground_with_google_search |
| 586 | + if request_type is not None: |
| 587 | + struct_fields["REQUEST_TYPE"] = request_type |
| 588 | + |
| 589 | + query = f""" |
| 590 | + SELECT * |
| 591 | + FROM AI.GENERATE_TEXT( |
| 592 | + MODEL `{model_name}`, |
| 593 | + ({table_sql}), |
| 594 | + {bigframes.core.sql.literals.struct_literal(struct_fields)} |
| 595 | + ) |
| 596 | + """ |
| 597 | + |
| 598 | + if session is None: |
| 599 | + return bpd.read_gbq_query(query) |
| 600 | + else: |
| 601 | + return session.read_gbq_query(query) |
497 | 602 |
|
498 | 603 |
|
499 | 604 | @log_adapter.method_logger(custom_base_name="bigquery_ai") |
@@ -811,3 +916,20 @@ def _resolve_connection_id(series: series.Series, connection_id: str | None): |
811 | 916 | series._session._project, |
812 | 917 | series._session._location, |
813 | 918 | ) |
| 919 | + |
| 920 | + |
| 921 | +def _to_dataframe( |
| 922 | + data: Union[dataframe.DataFrame, series.Series, pd.DataFrame, pd.Series], |
| 923 | + series_rename: str, |
| 924 | +) -> dataframe.DataFrame: |
| 925 | + if isinstance(data, (pd.DataFrame, pd.Series)): |
| 926 | + data = bpd.read_pandas(data) |
| 927 | + |
| 928 | + if isinstance(data, series.Series): |
| 929 | + data = data.copy() |
| 930 | + data.name = series_rename |
| 931 | + return data.to_frame() |
| 932 | + elif isinstance(data, dataframe.DataFrame): |
| 933 | + return data |
| 934 | + |
| 935 | + raise ValueError(f"Unsupported data type: {type(data)}") |