SQL, 객체 테이블, BigQuery DataFrames를 사용하여 멀티모달 데이터 분석

이 튜토리얼에서는 SQL 쿼리, AI.GENERATE 함수, AI.EMBED 함수, BigQuery DataFrames를 사용하여 Cymbal 애완동물 가게 공개 데이터 세트의 멀티모달 데이터를 분석하는 방법을 보여줍니다.

AI.GENERATE 함수를 사용하면 정형 데이터와 비정형 데이터의 모든 조합을 분석할 수 있고, AI.EMBED 함수를 사용하면 BigQuery의 텍스트 또는 이미지 데이터에서 임베딩을 만들 수 있습니다.

VECTOR_SEARCH 함수를 사용하여 유사한 이미지를 찾습니다. VECTOR_SEARCH 함수를 사용하면 임베딩에 대한 시맨틱 검색 또는 하이브리드 검색을 실행하여 유사한 항목을 찾을 수 있습니다.

이 튜토리얼에서는 ObjectRef 값을 저장하는 영구 객체 테이블을 사용합니다.

목표

  • ObjectRef 값을 사용하여 BigQuery 테이블에 구조화된 데이터와 함께 이미지 데이터를 저장합니다.
  • AI.GENERATE 함수를 사용하여 데이터를 보강합니다.
  • AI.EMBED 함수를 사용하여 이미지 데이터를 기반으로 임베딩을 생성합니다.
  • VECTOR_SEARCH 함수를 사용하여 유사한 이미지를 찾습니다.
  • ObjectRef 값의 배열을 사용하여 사용자 매뉴얼을 요약합니다.

비용

이 문서에서는 비용이 청구될 수 있는 Google Cloud구성요소를 사용합니다.

  • BigQuery: you incur costs for the data that you process in BigQuery.
  • Cloud Storage: you incur costs for reading the objects stored in Cloud Storage.
  • Gemini Enterprise Agent Platform: you incur costs for calls to Agent Platform models.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용하세요.

Google Cloud 신규 사용자는 무료 체험판을 사용할 수 있습니다.

비용에 대한 자세한 내용은 다음 가격 책정 페이지를 참고하세요.

시작하기 전에

  1. Google Cloud 콘솔의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트를 선택하거나 만드는 데 필요한 역할

    • 프로젝트 선택: 프로젝트를 선택하는 데는 특정 IAM 역할이 필요하지 않습니다. 역할이 부여된 프로젝트를 선택하면 됩니다.
    • 프로젝트 만들기: 프로젝트를 만들려면 resourcemanager.projects.create 권한이 포함된 프로젝트 생성자 역할(roles/resourcemanager.projectCreator)이 필요합니다. 역할 부여 방법 알아보기

    프로젝트 선택기로 이동

  2. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  3. BigQuery, BigQuery Connection, Cloud Storage, Agent Platform API API를 사용 설정합니다.

    API 사용 설정에 필요한 역할

    API를 사용 설정하려면 serviceusage.services.enable 권한이 필요합니다. 프로젝트를 만든 경우 소유자 역할 (roles/owner)을 통해 이 권한이 이미 있을 수 있습니다. 그렇지 않으면 서비스 사용량 관리자 역할 (roles/serviceusage.serviceUsageAdmin)을 통해 이 권한을 얻을 수 있습니다. 역할을 부여하는 방법 알아보기

    API 사용 설정

필요한 역할

이 튜토리얼을 완료하는 데 필요한 권한을 얻으려면 관리자에게 다음의 IAM 역할을 부여해 달라고 요청하세요.

역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

데이터 세트, 테이블, 모델, 연결 만들기

이 섹션에서는 이 튜토리얼에서 사용되는 데이터 세트, 연결, 테이블, 모델을 만듭니다.

데이터 세트 만들기

다음 중 하나를 선택하여 이 튜토리얼에서 만드는 객체를 포함할 BigQuery 데이터 세트를 만듭니다.

콘솔

  1. Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 왼쪽 창에서 탐색기를 클릭합니다.

    강조 표시된 탐색기 창 버튼

    왼쪽 창이 표시되지 않으면 왼쪽 창 펼치기를 클릭하여 창을 엽니다.

  3. 탐색기에서 프로젝트를 펼친 다음 데이터 세트를 클릭합니다.

  4. 데이터 세트 페이지에서 데이터 세트 만들기를 클릭합니다.

  5. 데이터 세트 만들기 페이지에서 다음을 수행합니다.

    1. 데이터 세트 IDcymbal_pets를 입력합니다.

    2. 데이터 위치미국을 선택합니다.

    3. 나머지 기본 설정은 그대로 두고 데이터 세트 만들기를 클릭합니다.

SQL

CREATE SCHEMA을 사용합니다.

  1. Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 쿼리 편집기에서 다음 문을 입력합니다.

    CREATE SCHEMA PROJECT_ID.cymbal_pets
      OPTIONS (
        description = 'Dataset for BigQuery ML tutorial',
        location = 'US');

    PROJECT_ID를 프로젝트 ID로 바꿉니다.

  3. 실행을 클릭합니다.

쿼리를 실행하는 방법에 대한 자세한 내용은 대화형 쿼리 실행을 참조하세요.

다음과 유사한 확인 메시지가 표시됩니다. The dataset named cymbal_pets was created.

연결 만들기

클라우드 리소스 연결을 만들고 연결의 서비스 계정을 가져옵니다. BigQuery는 연결을 사용하여 Cloud Storage의 객체에 액세스합니다.

  1. 왼쪽 창에서 탐색기를 클릭합니다.

    강조 표시된 탐색기 창 버튼

  2. 탐색기 창에서 연결을 클릭합니다.

  3. 연결 페이지에서 연결 만들기를 클릭합니다.

  4. 외부 데이터 소스 페이지에서 다음을 수행합니다.

    1. 연결 유형으로 Vertex AI 원격 모델, 원격 함수, Lakehouse, Spanner (Cloud 리소스)를 선택합니다.

    2. 연결 ID 필드에 cymbal_conn을 입력합니다.

    3. 나머지 설정은 그대로 두고 연결 만들기를 클릭합니다.

  5. 연결 페이지에서 cymbal_conn를 클릭합니다.

  6. 연결 정보 창에서 서비스 계정 ID 값을 복사합니다. 다음 단계에 필요합니다.

Agent Platform 모델을 사용할 수 있는 권한 부여

Agent Platform에서 원격 모델에 액세스하려면 연결의 서비스 계정에 Agent Platform 사용자 역할을 부여합니다. 이전에 만들었거나 선택한 것과 동일한 프로젝트에서 이 역할을 부여해야 합니다. 다른 프로젝트에서 역할을 부여하면 bqcx-1234567890-abcd@gcp-sa-bigquery-condel.iam.gserviceaccount.com does not have the permission to access resource 오류가 발생합니다.

서비스 계정에 Agent Platform 모델을 사용할 수 있는 액세스 권한을 부여하려면 다음 단계를 따르세요.

  1. IAM 및 관리자 페이지로 이동합니다.

    IAM 및 관리자로 이동

  2. 액세스 권한 부여를 클릭합니다.

  3. 액세스 권한 부여 대화상자에서 다음을 수행합니다.

    1. 새 주 구성원 필드에 앞에서 복사한 서비스 계정 ID를 입력합니다.

    2. 역할 선택 필드에서 Agent Platform 사용자를 선택하거나 검색합니다.

    3. 저장을 클릭합니다.

products 테이블 만들기

Cymbal pets 제품 정보가 포함된 표준 테이블을 만들려면 다음 단계에 따라 Cloud Storage에서 데이터를 로드하세요.

  1. Google Cloud 콘솔에서 Studio 페이지로 이동합니다.

    Studio로 이동

  2. products 테이블을 만들려면 다음 옵션 중 하나를 선택합니다.

    SQL

    이 명령어를 쿼리 편집기에 붙여넣고 실행을 클릭합니다.

    LOAD DATA OVERWRITE cymbal_pets.products
    FROM
      FILES(
        format = 'avro',
        uris = [
          'gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/tables/products/products_*.avro']);

    다음과 유사한 확인 메시지가 표시됩니다. Data was successfully loaded into managed table.

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    import bigframes.bigquery as bbq
    import bigframes.pandas as bpd
    
    bbq.load_data(
        "cymbal_pets.products",
        write_disposition="OVERWRITE",
        from_files_options={
            "format": "avro",
            "uris": [
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/tables/products/products_*.avro"
            ],
        },
    )
    import bigframes.bigquery as bbq
    import bigframes.pandas as bpd
    
    bbq.load_data(
        "cymbal_pets.products",
        write_disposition="OVERWRITE",
        from_files_options={
            "format": "avro",
            "uris": [
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/tables/products/products_*.avro"
            ],
        },
    )

product_images 테이블 만들기

Cymbal pets 제품 이미지가 포함된 객체 테이블 (product_images)을 만들려면 다음 옵션 중 하나를 선택합니다.



* { SQL }

  Paste this command into the query editor, and then click
  <span class="material-icons" aria-hidden="true">play_circle</span>
  **Run**:

  <pre class="lang-googlesql notranslate prettyprint devsite-click-to-copy">
  CREATE OR REPLACE EXTERNAL TABLE cymbal_pets.product_images
    WITH CONNECTION `us.cymbal_conn`
    OPTIONS (
      object_metadata = 'SIMPLE',
      uris = ['gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/*.png'],
      max_staleness = INTERVAL 30 MINUTE,
      metadata_cache_mode = AUTOMATIC);
  </pre>

  You receive a confirmation message similar to the following: `This
  statement created a new table named product_images.`

* { BigQuery DataFrames }

      

Before trying this sample, follow the BigQuery DataFrames setup instructions in the BigQuery quickstart using BigQuery DataFrames. For more information, see the BigQuery DataFrames reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up ADC for a local development environment.

bbq.create_external_table(
    "cymbal_pets.product_images",
    replace=True,
    connection_name="us.cymbal_conn",
    options={
        "object_metadata": "SIMPLE",
        "uris": [
            "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/*.png"
        ],
    },
)
bbq.create_external_table(
    "cymbal_pets.product_images",
    replace=True,
    connection_name="us.cymbal_conn",
    options={
        "object_metadata": "SIMPLE",
        "uris": [
            "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/*.png"
        ],
    },
)

모델 만들기

이 튜토리얼의 SQL 안내에서는 모델을 만들 필요가 없는 AI 함수를 호출하는 방법을 보여줍니다. BigQuery DataFrames 안내를 따르는 경우 이 옵션을 선택하여 Gemini 모델과 멀티모달 임베딩 모델을 나타내는 원격 모델을 만듭니다.

SQL

이 단계를 건너뛸 수 있습니다.

BigQuery DataFrames

이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

gemini_model = bbq.ml.create_model(
    "cymbal_pets.gemini",
    replace=True,
    connection_name="us.cymbal_conn",
    options={"endpoint": "gemini-3.5-flash"},
)
gemini_model = bbq.ml.create_model(
    "cymbal_pets.gemini",
    replace=True,
    connection_name="us.cymbal_conn",
    options={"endpoint": "gemini-3.5-flash"},
)

embedding_model = bbq.ml.create_model(
    "cymbal_pets.embedding_model",
    replace=True,
    connection_name="us.cymbal_conn",
    options={"endpoint": "gemini-embedding-2"},
)
embedding_model = bbq.ml.create_model(
    "cymbal_pets.embedding_model",
    replace=True,
    connection_name="us.cymbal_conn",
    options={"endpoint": "gemini-embedding-2"},
)

멀티모달 데이터로 products_mm 테이블 만들기

product_images 객체 테이블의 제품 이미지로 채워진 image 열이 포함된 products_mm 테이블을 만듭니다. 생성된 image 열은 ObjectRef 값을 사용하여 BigQuery 표준 테이블에 구조화된 데이터와 함께 이미지 데이터를 저장하는 STRUCT 열입니다.

ObjectRef 값은 멀티모달 분석을 위해 Cloud Storage 객체를 참조하는 사전 정의된 스키마가 있는 STRUCT 유형입니다. ObjectRef 값은 OBJ 함수, AI 함수 또는 Python 사용자 정의 함수로 처리할 수 있습니다.

products_mm 테이블을 만들고 채우려면 다음 단계를 따르세요.

  1. products_mm 테이블을 만들려면 다음 옵션 중 하나를 선택합니다.

    SQL

    이 명령어를 쿼리 편집기에 붙여넣고 실행을 클릭합니다.

    CREATE OR REPLACE TABLE cymbal_pets.products_mm
    AS
    SELECT products.* EXCEPT (uri), ot.ref AS image FROM cymbal_pets.products
    INNER JOIN cymbal_pets.product_images ot
    ON ot.uri = products.uri;

    다음과 유사한 확인 메시지가 표시됩니다. This statement created a new table named products_mm.

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_images = bpd.read_gbq("SELECT * FROM cymbal_pets.product_images")
    df_products = bpd.read_gbq("cymbal_pets.products")
    
    df_products_mm = df_images.merge(df_products, on="uri").drop(columns="uri")
    df_products_mm = df_products_mm.rename(columns={"ref": "image"})
    df_images = bpd.read_gbq("SELECT * FROM cymbal_pets.product_images")
    df_products = bpd.read_gbq("cymbal_pets.products")
    
    df_products_mm = df_images.merge(df_products, on="uri").drop(columns="uri")
    df_products_mm = df_products_mm.rename(columns={"ref": "image"})

  2. image 열 데이터를 보려면 다음 옵션 중 하나를 선택합니다.

    SQL

    이 명령어를 쿼리 편집기에 붙여넣고 실행을 클릭합니다.

    SELECT product_name, image
    FROM cymbal_pets.products_mm

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_products_mm[["product_name", "image"]]
    df_products_mm[["product_name", "image"]]

    결과는 다음과 유사합니다.

    +--------------------------------+--------------------------------------+---------------+-------------------------------+------------------------------------------------+
    | product_name                   | image.uri                            | image.version | image.authorizer              | image.details                                  |
    +--------------------------------+--------------------------------------+---------------+-------------------------------+------------------------------------------------+
    |  AquaClear Aquarium Background | gs://cloud-samples-data/bigquery/    | 1234567891011 | myproject.region.myconnection | {"gcs_metadata":{"content_type":"image/png",   |
    |                                | tutorials/cymbal-pets/images/        |               |                               | "md5_hash":"494f63b9b137975ff3e7a11b060edb1d", |
    |                                | aquaclear-aquarium-background.png    |               |                               | "size":1282805,"updated":1742492680017000}}    |
    +--------------------------------+--------------------------------------+---------------+-------------------------------+------------------------------------------------+
    |  AquaClear Aquarium            | gs://cloud-samples-data/bigquery/    | 2345678910112 | myproject.region.myconnection | {"gcs_metadata":{"content_type":"image/png",   |
    |  Gravel Vacuum                 | tutorials/cymbal-pets/images/        |               |                               | "md5_hash":"b7bfc2e2641a77a402a1937bcf0003fd", |
    |                                | aquaclear-aquarium-gravel-vacuum.png |               |                               | "size":820254,"updated":1742492682411000}}     |
    +--------------------------------+--------------------------------------+---------------+-------------------------------+------------------------------------------------+
    | ...                            | ...                                  | ...           |                               | ...                                            |
    +--------------------------------+--------------------------------------+---------------+-------------------------------+------------------------------------------------+
    

제품 정보 생성

AI.GENERATE 함수를 사용하여 반려동물 용품점 제품에 대한 다음 데이터를 생성합니다.

  • products_mm 테이블에 image_description 열을 추가합니다.
  • products_mm 테이블의 animal_type, search_keywords, subcategory 열을 채웁니다.
  • 각 제품 브랜드의 설명과 해당 브랜드의 제품 수를 반환하는 쿼리를 실행합니다. 브랜드 설명은 제품 이미지를 비롯해 해당 브랜드의 모든 제품에 대한 제품 정보를 분석하여 생성됩니다.

AI.GENERATE 함수를 사용하면 지정한 맞춤 스키마에 따라 텍스트 또는 구조화된 출력을 생성할 수 있습니다. 이 함수는 Gemini 모델에 요청을 전송하여 작동하며, 생성된 데이터, 전체 모델 응답, 상태가 포함된 구조체를 반환합니다.

제품 데이터를 생성하려면 다음 단계를 따르세요.

  1. AI.GENERATE를 사용하여 제품 정보를 생성하려면 다음 옵션 중 하나를 선택하세요.

    SQL

    image_description 열을 만들고 채우려면 다음을 쿼리 편집기에 붙여넣은 다음 실행을 클릭합니다.

    -- Add the column to the existing table
    ALTER TABLE bqml_tutorial.products_mm
    ADD COLUMN IF NOT EXISTS image_description STRING;
    
    -- Populate the new column using the AI.GENERATE function
    UPDATE bqml_tutorial.products_mm
    SET image_description = AI.GENERATE(
    ('Describe the following image: ', image),
    endpoint => 'gemini-3.5-flash'
    ).result
    WHERE image_description IS NULL;

    다음과 유사한 확인 메시지가 표시됩니다. This statement altered the table named products_mm.

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_products_mm["url"] = bbq.obj.get_access_url(
        df_products_mm["image"], "R"
    ).to_frame()
    df_products_mm["prompt0"] = "Can you describe the following image?"
    
    df_products_mm["prompt"] = bbq.struct(df_products_mm[["prompt0", "url"]])
    df_products_mm = bbq.ai.generate_table(
        gemini_model, df_products_mm, output_schema={"image_description": "STRING"}
    )
    
    df_products_mm = df_products_mm[
        [
            "product_id",
            "product_name",
            "brand",
            "category",
            "subcategory",
            "animal_type",
            "search_keywords",
            "price",
            "description",
            "inventory_level",
            "supplier_id",
            "average_rating",
            "image",
            "image_description",
        ]
    ]
    df_products_mm["url"] = bbq.obj.get_access_url(
        df_products_mm["image"], "R"
    ).to_frame()
    df_products_mm["prompt0"] = "Can you describe the following image?"
    
    df_products_mm["prompt"] = bbq.struct(df_products_mm[["prompt0", "url"]])
    df_products_mm = bbq.ai.generate_table(
        gemini_model, df_products_mm, output_schema={"image_description": "STRING"}
    )
    
    df_products_mm = df_products_mm[
        [
            "product_id",
            "product_name",
            "brand",
            "category",
            "subcategory",
            "animal_type",
            "search_keywords",
            "price",
            "description",
            "inventory_level",
            "supplier_id",
            "average_rating",
            "image",
            "image_description",
        ]
    ]

  2. image_description 열의 내용을 보려면 다음을 쿼리 편집기에 붙여넣고 실행을 클릭합니다.

    SELECT product_name, image_description
    FROM cymbal_pets.products_mm;

    결과는 다음과 유사합니다.

    +--------------------------------+-------------------------------------+
    | product_name                   | image_description                   |
    +--------------------------------+-------------------------------------+
    |  AquaClear Aquarium Background | The image shows a colorful coral    |
    |                                | reef backdrop. The background is a  |
    |                                | blue ocean with a bright light...   |
    |                                |                                     |
    |                                |                                     |
    +--------------------------------+-------------------------------------+
    |  AquaClear Aquarium            | The image shows a long, clear       |
    |  Gravel Vacuum                 | plastic tube with a green hose      |
    |                                | attached to one end. The tube...    |
    |                                |                                     |
    |                                |                                     |
    +--------------------------------+-------------------------------------+
    | ...                            | ...                                 |
    +--------------------------------+-------------------------------------+
    
  3. 생성된 데이터로 animal_type, search_keywords, subcategory 열을 업데이트하려면 다음 옵션 중 하나를 선택하세요.

    SQL

    쿼리 편집기에 다음을 붙여넣고 실행을 클릭합니다.

    UPDATE cymbal_pets.products_mm t
    SET
    animal_type = r.animal_type,
    search_keywords = SPLIT(r.search_keywords, ','),
    subcategory = r.subcategory
    FROM (
    SELECT
      product_id,
      g.* EXCEPT(full_response, status)
    FROM bqml_tutorial.products_mm,
    UNNEST([AI.GENERATE(
      ('For the image and description of a pet product, concisely generate the following metadata: 1) animal_type and 2) 5 SEO search keywords (comma separated), and 3) product subcategory. ', image, description),
      endpoint => 'gemini-3.5-flash',
      output_schema => 'animal_type STRING, search_keywords STRING, subcategory STRING'
    )]) AS g
    ) r
    WHERE t.product_id = r.product_id;

    다음과 유사한 확인 메시지가 표시됩니다. This statement modified 205 rows in products_mm.

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_prompt = bbq.obj.get_access_url(df_products_mm["image"], "R").to_frame()
    df_prompt[
        "prompt0"
    ] = "For the image of a pet product, concisely generate the following metadata: 1) animal_type and 2) 5 SEO search keywords, and 3) product subcategory."
    
    df_products_mm["prompt"] = bbq.struct(df_prompt[["prompt0", "image"]])
    
    df_products_mm = df_products_mm.drop(
        columns=["animal_type", "search_keywords", "subcategory"]
    )
    df_products_mm = bbq.ai.generate_table(
        gemini_model,
        df_products_mm,
        output_schema="animal_type STRING, search_keywords ARRAY<STRING>, subcategory STRING",
    )
    df_prompt = bbq.obj.get_access_url(df_products_mm["image"], "R").to_frame()
    df_prompt[
        "prompt0"
    ] = "For the image of a pet product, concisely generate the following metadata: 1) animal_type and 2) 5 SEO search keywords, and 3) product subcategory."
    
    df_products_mm["prompt"] = bbq.struct(df_prompt[["prompt0", "image"]])
    
    df_products_mm = df_products_mm.drop(
        columns=["animal_type", "search_keywords", "subcategory"]
    )
    df_products_mm = bbq.ai.generate_table(
        gemini_model,
        df_products_mm,
        output_schema="animal_type STRING, search_keywords ARRAY<STRING>, subcategory STRING",
    )

  4. 생성된 데이터를 보려면 다음 옵션 중 하나를 선택하세요.

    SQL

    쿼리 편집기에 다음을 붙여넣고 실행을 클릭합니다.

    SELECT
    product_name,
    image_description,
    animal_type,
    search_keywords,
    subcategory,
    FROM cymbal_pets.products_mm;

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_products_mm[
        [
            "product_name",
            "image_description",
            "animal_type",
            "search_keywords",
            "subcategory",
        ]
    ]
    df_products_mm[
        [
            "product_name",
            "image_description",
            "animal_type",
            "search_keywords",
            "subcategory",
        ]
    ]

    결과는 다음과 유사합니다.

    +--------------------------------+-------------------------------------+-------------+------------------------+------------------+
    | product_name                   | image_description                   | animal_type | search_keywords        | subcategory      |
    +--------------------------------+-------------------------------------+-------------+------------------------+------------------+
    |  AquaClear Aquarium Background | The image shows a colorful coral    | fish        | aquarium background    | aquarium decor   |
    |                                | reef backdrop. The background is a  |             | fish tank backdrop     |                  |
    |                                | blue ocean with a bright light...   |             | coral reef decor       |                  |
    |                                |                                     |             | underwater scenery     |                  |
    |                                |                                     |             | aquarium decoration    |                  |
    +--------------------------------+-------------------------------------+-------------+------------------------+------------------+
    |  AquaClear Aquarium            | The image shows a long, clear       | fish        | aquarium gravel vacuum | aquarium         |
    |  Gravel Vacuum                 | plastic tube with a green hose      |             | aquarium cleaning      | cleaning         |
    |                                | attached to one end. The tube...    |             | aquarium maintenance   |                  |
    |                                |                                     |             | fish tank cleaning     |                  |
    |                                |                                     |             | gravel siphon          |                  |
    +--------------------------------+-------------------------------------+-------------+------------------------+------------------+
    | ...                            | ...                                 | ...         |  ...                   | ...              |
    +--------------------------------+-------------------------------------+-------------+------------------------+------------------+
    
  5. 각 제품 브랜드의 설명과 해당 브랜드의 제품 수를 생성하려면 다음 옵션 중 하나를 선택하세요.

    SQL

    쿼리 편집기에 다음을 붙여넣고 실행을 클릭합니다.

    SELECT
    brand,
    COUNT(*) AS cnt,
    AI.GENERATE(('Use the images and text to give one concise brand description ',
                'for a website brand page. Return the description only.',
                  ARRAY_AGG(image LIMIT 10), ARRAY_AGG(description), ARRAY_AGG(category),
                  ARRAY_AGG(subcategory)),
                endpoint => 'gemini-2.5-pro').result AS brand_description
    FROM
    cymbal_pets.products_mm
    GROUP BY brand
    ORDER BY cnt DESC;

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_agg = df_products_mm[
        ["image", "description", "category", "subcategory", "brand"]
    ]
    df_agg["image"] = bbq.obj.get_access_url(df_products_mm["image"], "R")
    df_agg = bbq.array_agg(df_agg.groupby(by=["brand"]))
    
    df_agg["cnt"] = bbq.array_length(df_agg["image"])
    
    df_prompt = df_agg[["image", "description", "category", "subcategory"]]
    df_prompt[
        "prompt0"
    ] = "Use the images and text to give one concise brand description for a website brand page. Return the description only. "
    
    df_agg["prompt"] = bbq.struct(
        df_prompt[["prompt0", "image", "description", "category", "subcategory"]]
    )
    
    df_agg = df_agg.reset_index()
    
    df_agg = bbq.ai.generate_table(
        gemini_model, df_agg, output_schema={"brand_description": "STRING"}
    )
    df_agg[["brand", "brand_description", "cnt"]]
    df_agg = df_products_mm[
        ["image", "description", "category", "subcategory", "brand"]
    ]
    df_agg["image"] = bbq.obj.get_access_url(df_products_mm["image"], "R")
    df_agg = bbq.array_agg(df_agg.groupby(by=["brand"]))
    
    df_agg["cnt"] = bbq.array_length(df_agg["image"])
    
    df_prompt = df_agg[["image", "description", "category", "subcategory"]]
    df_prompt[
        "prompt0"
    ] = "Use the images and text to give one concise brand description for a website brand page. Return the description only. "
    
    df_agg["prompt"] = bbq.struct(
        df_prompt[["prompt0", "image", "description", "category", "subcategory"]]
    )
    
    df_agg = df_agg.reset_index()
    
    df_agg = bbq.ai.generate_table(
        gemini_model, df_agg, output_schema={"brand_description": "STRING"}
    )
    df_agg[["brand", "brand_description", "cnt"]]

    결과는 다음과 유사합니다.

    +--------------+-------------------------------------+-----+
    | brand        | brand_description                   | cnt |
    +--------------+-------------------------------------+-----+
    |  AquaClear   | AquaClear is a brand of aquarium    | 33  |
    |              | and pond care products that offer   |     |
    |              | a wide range of solutions for...    |     |
    +--------------+-------------------------------------+-----+
    |  Ocean       | Ocean Bites is a brand of cat food  | 28  |
    |  Bites       | that offers a variety of recipes    |     |
    |              | and formulas to meet the specific.. |     |
    +--------------+-------------------------------------+-----+
    |  ...         | ...                                 |...  |
    +--------------+-------------------------------------+-----+
    

이미지 데이터에서 임베딩을 생성한 다음 임베딩을 사용하여 벡터 검색을 통해 유사한 이미지를 반환합니다.

프로덕션 시나리오에서는 벡터 검색을 실행하기 전에 벡터 색인을 만드는 것이 좋습니다. 벡터 색인을 사용하면 벡터 검색을 더 빠르게 수행하고 더 근사한 결과를 반환하지만 재현율이 감소합니다.

임베딩을 만들고 벡터 검색을 실행하려면 다음 단계를 따르세요.

  1. products_embeddings 테이블을 만들려면 다음 옵션 중 하나를 선택합니다.

    SQL

    쿼리 편집기에 다음을 붙여넣고 실행을 클릭합니다.

    CREATE OR REPLACE TABLE cymbal_pets.products_embedding
    AS (
    SELECT
      product_id,
      AI.EMBED(image, endpoint => 'gemini-embedding-2').result AS embedding,
      image
    FROM cymbal_pets.products_mm
    );

    다음과 유사한 확인 메시지가 표시됩니다. This statement created a new table named products_embedding.

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_products_mm["content"] = bbq.obj.get_access_url(df_products_mm["image"], "R")
    df_embed = bbq.ai.generate_embedding(
        embedding_model, df_products_mm[["content", "product_id"]]
    )
    
    df_embed.to_gbq("cymbal_pets.products_embedding", if_exists="replace")
    df_products_mm["content"] = bbq.obj.get_access_url(df_products_mm["image"], "R")
    df_embed = bbq.ai.generate_embedding(
        embedding_model, df_products_mm[["content", "product_id"]]
    )
    
    df_embed.to_gbq("cymbal_pets.products_embedding", if_exists="replace")

  2. 지정된 입력 이미지와 유사한 제품 이미지를 반환하는 벡터 검색을 실행하려면 다음 옵션 중 하나를 선택하세요.

    SQL

    쿼리 편집기에 다음을 붙여넣고 실행을 클릭합니다.

    SELECT *
    FROM
    VECTOR_SEARCH(
      TABLE cymbal_pets.products_embedding,
      'embedding',
      query_value => AI.EMBED(
                      OBJ.MAKE_REF('gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/cozy-naps-cat-scratching-post-with-condo.png'),
                      endpoint => 'gemini-embedding-2').result);

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_image = bpd.DataFrame(
        {
            "uri": [
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/cozy-naps-cat-scratching-post-with-condo.png"
            ]
        }
    ).cache()
    df_image["image"] = bbq.obj.make_ref(df_image["uri"], "us.cymbal_conn")
    df_search = bbq.ai.generate_embedding(
        embedding_model,
        bbq.obj.get_access_url(bbq.obj.fetch_metadata(df_image["image"]), "R"),
    )
    
    search_result = bbq.vector_search(
        "cymbal_pets.products_embedding", "embedding", df_search["embedding"]
    )
    search_result
    df_image = bpd.DataFrame(
        {
            "uri": [
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/cozy-naps-cat-scratching-post-with-condo.png"
            ]
        }
    ).cache()
    df_image["image"] = bbq.obj.make_ref(df_image["uri"], "us.cymbal_conn")
    df_search = bbq.ai.generate_embedding(
        embedding_model,
        bbq.obj.get_access_url(bbq.obj.fetch_metadata(df_image["image"]), "R"),
    )
    
    search_result = bbq.vector_search(
        "cymbal_pets.products_embedding", "embedding", df_search["embedding"]
    )
    search_result

    결과는 다음과 유사합니다.

    +-----------------+-----------------+----------------+----------------------------------------------+--------------------+-------------------------------+------------------------------------------------+----------------+
    | query.embedding | base.product_id | base.embedding | base.image.uri                               | base.image.version | base.image.authorizer         | base.image.details                             | distance       |
    +-----------------+-----------------+----------------+----------------------------------------------+--------------------+-------------------------------+------------------------------------------------+----------------+
    | -0.0112330541   | 181             | -0.0112330541  | gs://cloud-samples-data/bigquery/            | 12345678910        | myproject.region.myconnection | {"gcs_metadata":{"content_type":               | 0.0            |
    | 0.0142525584    |                 |  0.0142525584  | tutorials/cymbal-pets/images/                |                    |                               | "image/png","md5_hash":"21234567hst16555w60j", |                |
    | 0.0135886827    |                 |  0.0135886827  | cozy-naps-cat-scratching-post-with-condo.png |                    |                               | "size":828318,"updated":1742492688982000}}     |                |
    | 0.0149955815    |                 |  0.0149955815  |                                              |                    |                               |                                                |                |
    | ...             |                 |  ...           |                                              |                    |                               |                                                |                |
    |                 |                 |                |                                              |                    |                               |                                                |                |
    |                 |                 |                |                                              |                    |                               |                                                |                |
    +-----------------+-----------------+----------------+----------------------------------------------+--------------------+-------------------------------+------------------------------------------------+----------------+
    | -0.0112330541   | 187             | -0.0190353896  | gs://cloud-samples-data/bigquery/            | 23456789101        | myproject.region.myconnection | {"gcs_metadata":{"content_type":               | 0.4216330832.. |
    | 0.0142525584    |                 |  0.0116206668  | tutorials/cymbal-pets/images/                |                    |                               | "image/png","md5_hash":"7328728fhakd9937djo4", |                |
    | 0.0135886827    |                 |  0.0136198215  | cozy-naps-cat-scratching-post-with-bed.png   |                    |                               | "size":860113,"updated":1742492688774000}}     |                |
    | 0.0149955815    |                 |  0.0173457414  |                                              |                    |                               |                                                |                |
    | ...             |                 |  ...           |                                              |                    |                               |                                                |                |
    |                 |                 |                |                                              |                    |                               |                                                |                |
    |                 |                 |                |                                              |                    |                               |                                                |                |
    +-----------------+-----------------+----------------+----------------------------------------------+--------------------+-------------------------------+------------------------------------------------+----------------+
    | ...             | ...             | ...            | ...                                          | ...                | ...                           | ...                                            | ...            |
    +-----------------+-----------------+----------------+----------------------------------------------+--------------------+-------------------------------+------------------------------------------------+----------------+
    

ObjectRef 값의 배열을 사용하여 순서가 지정된 멀티모달 데이터 처리

이 섹션에서는 ObjectRef 값의 배열을 사용하여 순서가 지정된 멀티모달 데이터를 처리하여 사용자 매뉴얼을 요약하는 방법을 보여줍니다. BigQuery는 배열을 사용하여 여러 비정형 파일을 동시에 분석할 수 있습니다.

다음 작업을 완료합니다.

  1. Crittercuisine Pro 5000 제품 설명서의 PDF 파일과 해당 설명서의 각 페이지에 대한 PDF 파일이 모두 포함되도록 product_manuals 테이블을 만듭니다.

  2. 매뉴얼을 청크에 매핑하는 표를 만듭니다. 전체 매뉴얼과 매뉴얼 페이지는 각각 ObjectRef 열에 저장됩니다.

  3. ObjectRef 값의 배열을 함께 분석하여 생성된 단일 값을 반환합니다.

  4. ObjectRef 값의 배열을 별도로 분석하고 각 배열 값에 대해 생성된 값을 반환합니다.

ObjectRef 값을 사용하여 순서가 지정된 멀티모달 데이터를 처리하려면 다음 단계를 따르세요.

  1. product_manuals 테이블을 만들려면 다음 옵션 중 하나를 선택합니다.

    SQL

    쿼리 편집기에 다음을 붙여넣고 실행을 클릭합니다.

    CREATE OR REPLACE EXTERNAL TABLE `cymbal_pets.product_manuals`
    WITH CONNECTION `us.cymbal_conn`
    OPTIONS (
      object_metadata = 'SIMPLE',
      uris = [
          'gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/documents/*.pdf',
          'gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/document_chunks/*.pdf']);

    다음과 유사한 확인 메시지가 표시됩니다. This statement created a new table named product_manuals.

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    bbq.create_external_table(
        "cymbal_pets.product_manuals_all",
        replace=True,
        connection_name="us.cymbal_conn",
        options={
            "object_metadata": "SIMPLE",
            "uris": [
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/documents/*.pdf",
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/document_chunks/*.pdf",
            ],
        },
    )
    bbq.create_external_table(
        "cymbal_pets.product_manuals_all",
        replace=True,
        connection_name="us.cymbal_conn",
        options={
            "object_metadata": "SIMPLE",
            "uris": [
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/documents/*.pdf",
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/document_chunks/*.pdf",
            ],
        },
    )

  2. map_manual_to_chunks 테이블에 PDF 데이터를 쓰려면 다음 옵션 중 하나를 선택합니다.

    SQL

    쿼리 편집기에 다음을 붙여넣고 실행을 클릭합니다.

    -- Extract the file and chunks into a single table.
    -- Store the chunks in the chunks column as array of ObjectRefs (ordered by page number)
    CREATE OR REPLACE TABLE cymbal_pets.map_manual_to_chunks
    AS
    SELECT ARRAY_AGG(m1.ref)[0] manual, ARRAY_AGG(m2.ref ORDER BY m2.ref.uri) chunks
    FROM cymbal_pets.product_manuals m1
    JOIN cymbal_pets.product_manuals m2
    ON
      REGEXP_EXTRACT(m1.uri, r'.*/([^.]*).[^/]+')
      = REGEXP_EXTRACT(m2.uri, r'.*/([^.]*)_page[0-9]+.[^/]+')
    GROUP BY m1.uri;

    다음과 유사한 확인 메시지가 표시됩니다. This statement created a new table named map_manual_to_chunks.

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df1 = bpd.read_gbq("SELECT * FROM cymbal_pets.product_manuals_all").sort_values(
        "uri"
    )
    df2 = df1.copy()
    df1["name"] = df1["uri"].str.extract(r".*/([^.]*).[^/]+")
    df2["name"] = df2["uri"].str.extract(r".*/([^.]*)_page[0-9]+.[^/]+")
    df_manuals_all = df1.merge(df2, on="name")
    df_manuals_agg = (
        bbq.array_agg(df_manuals_all[["ref_x", "uri_x"]].groupby("uri_x"))["ref_x"]
        .str[0]
        .to_frame()
    )
    df_manuals_agg["chunks"] = bbq.array_agg(
        df_manuals_all[["ref_y", "uri_x"]].groupby("uri_x")
    )["ref_y"]
    df1 = bpd.read_gbq("SELECT * FROM cymbal_pets.product_manuals_all").sort_values(
        "uri"
    )
    df2 = df1.copy()
    df1["name"] = df1["uri"].str.extract(r".*/([^.]*).[^/]+")
    df2["name"] = df2["uri"].str.extract(r".*/([^.]*)_page[0-9]+.[^/]+")
    df_manuals_all = df1.merge(df2, on="name")
    df_manuals_agg = (
        bbq.array_agg(df_manuals_all[["ref_x", "uri_x"]].groupby("uri_x"))["ref_x"]
        .str[0]
        .to_frame()
    )
    df_manuals_agg["chunks"] = bbq.array_agg(
        df_manuals_all[["ref_y", "uri_x"]].groupby("uri_x")
    )["ref_y"]

  3. map_manual_to_chunks 테이블에서 PDF 데이터를 보려면 다음 옵션 중 하나를 선택합니다.

    SQL

    쿼리 편집기에 다음을 붙여넣고 실행을 클릭합니다.

    SELECT *
    FROM cymbal_pets.map_manual_to_chunks;

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_manuals_agg
    df_manuals_agg

    결과는 다음과 유사합니다.

    +-------------------------------------+--------------------------------+-----------------------------------+------------------------------------------------------+-------------------------------------------+---------------------------------+------------------------------------+-------------------------------------------------------+
    | manual.uri                          | manual.version                 | manual.authorizer                 | manual.details                                       | chunks.uri                                | chunks.version                  | chunks.authorizer                  | chunks.details                                        |
    +-------------------------------------+--------------------------------+-----------------------------------+------------------------------------------------------+-------------------------------------------+---------------------------------+------------------------------------+-------------------------------------------------------+
    | gs://cloud-samples-data/bigquery/   | 1742492785900455               | myproject.region.myconnection     | {"gcs_metadata":{"content_type":"application/pef",   | gs://cloud-samples-data/bigquery/         | 1745875761227129                | myproject.region.myconnection      | {"gcs_metadata":{"content_type":"application/pdf",    |
    | tutorials/cymbal-pets/documents/    |                                |                                   | "md5_hash":"c9032b037693d15a33210d638c763d0e",       | tutorials/cymbal-pets/documents/          |                                 |                                    | "md5_hash":"5a1116cce4978ec1b094d8e8b49a1d7c",        |
    | crittercuisine_5000_user_manual.pdf |                                |                                   | "size":566105,"updated":1742492785941000}}           | crittercuisine_5000_user_manual_page1.pdf |                                 |                                    | "size":504583,"updated":1745875761266000}}            |
    |                                     |                                |                                   |                                                      +-------------------------------------------+---------------------------------+------------------------------------+-------------------------------------------------------+
    |                                     |                                |                                   |                                                      | crittercuisine_5000_user_manual_page1.pdf | 1745875760613874                | myproject.region.myconnection      | {"gcs_metadata":{"content_type":"application/pdf",    |
    |                                     |                                |                                   |                                                      | tutorials/cymbal-pets/documents/          |                                 |                                    | "md5_hash":"94d03ec65d28b173bc87eac7e587b325",        |
    |                                     |                                |                                   |                                                      | crittercuisine_5000_user_manual_page2.pdf |                                 |                                    | "size":94622,"updated":1745875760649000}}             |
    |                                     |                                |                                   |                                                      +-------------------------------------------+---------------------------------+------------------------------------+-------------------------------------------------------+
    |                                     |                                |                                   |                                                      | ...                                       | ...                             |  ...                               | ...                                                   |
    +-------------------------------------+--------------------------------+-----------------------------------+------------------------------------------------------+-------------------------------------------+---------------------------------+------------------------------------+-------------------------------------------------------+
    
  4. ObjectRef 값 배열 분석을 기반으로 Gemini 모델에서 단일 응답을 생성하려면 다음 옵션 중 하나를 선택하세요.

    SQL

    쿼리 편집기에 다음을 붙여넣고 실행을 클릭합니다.

    SELECT
    AI.GENERATE((
      '''Can you provide a page by page summary for the first 3 pages of the attached manual?
      Only write one line for each page. The pages are provided in serial order''',
      chunks),
      endpoint => 'gemini-3.5-flash').result AS Response,
    FROM cymbal_pets.map_manual_to_chunks;

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_manuals_agg["chunks_url"] = bbq.array_agg(
        bbq.obj.get_access_url(df_manuals_agg.explode("chunks")["chunks"], "R").groupby(
            "uri_x"
        )
    )
    df_manuals_agg[
        "prompt0"
    ] = "Can you provide a page by page summary for the first 3 pages of the attached manual? Only write one line for each page. The pages are provided in serial order"
    df_manuals_agg["prompt"] = bbq.struct(df_manuals_agg[["prompt0", "chunks_url"]])
    
    result = bbq.ai.generate_text(gemini_model, df_manuals_agg["prompt"])["result"]
    result
    df_manuals_agg["chunks_url"] = bbq.array_agg(
        bbq.obj.get_access_url(df_manuals_agg.explode("chunks")["chunks"], "R").groupby(
            "uri_x"
        )
    )
    df_manuals_agg[
        "prompt0"
    ] = "Can you provide a page by page summary for the first 3 pages of the attached manual? Only write one line for each page. The pages are provided in serial order"
    df_manuals_agg["prompt"] = bbq.struct(df_manuals_agg[["prompt0", "chunks_url"]])
    
    result = bbq.ai.generate_text(gemini_model, df_manuals_agg["prompt"])["result"]
    result

    결과는 다음과 유사합니다.

    +---------------------------------------------------------------------------+
    | Response                                                                  |
    +---------------------------------------------------------------------------+
    | Here is a one-line summary for each of the first 3 pages:                 |
    |                                                                           |
    | Page 1 introduces the CritterCuisine Pro 5000 automatic pet feeder and    |
    | presents the initial part of the manual's Table of Contents.              |
    | Page 2 lists the items included with the feeder and details important     |
    | safety precautions for its use.                                           |
    | Page 3 describes the feeder's key features, provides assembly and initial |
    | setup instructions, and begins the programming guide with clock setting.  |
    +---------------------------------------------------------------------------+
    
  5. ObjectRef 값 배열 분석을 기반으로 Gemini 모델에서 여러 응답을 생성하려면 다음 옵션 중 하나를 선택하세요.

    SQL

    쿼리 편집기에 다음을 붙여넣고 실행을 클릭합니다.

    WITH results AS (
    SELECT
      AI.GENERATE((
        '''Can you provide a page by page summary for the first 3 pages of the attached manual?
        Only write one line for each page. The pages are provided in serial order''',
        chunks),
        endpoint => 'gemini-3.5-flash',
        output_schema =>  'page1_summary STRING, page2_summary STRING, page3_summary STRING').*
    FROM cymbal_pets.map_manual_to_chunks)
    SELECT page1_summary, page2_summary, page3_summary
    FROM results;

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    result = bbq.ai.generate_table(
        gemini_model,
        df_manuals_agg["prompt"],
        output_schema={
            "page1_summary": "STRING",
            "page2_summary": "STRING",
            "page3_summary": "STRING",
        },
    )[["page1_summary", "page2_summary", "page3_summary"]]
    result
    result = bbq.ai.generate_table(
        gemini_model,
        df_manuals_agg["prompt"],
        output_schema={
            "page1_summary": "STRING",
            "page2_summary": "STRING",
            "page3_summary": "STRING",
        },
    )[["page1_summary", "page2_summary", "page3_summary"]]
    result

    결과는 다음과 유사합니다.

    +-----------------------------------------------+-------------------------------------------+----------------------------------------------------+
    | page1_summary                                 | page2_summary                             | page3_summary                                      |
    +-----------------------------------------------+-------------------------------------------+----------------------------------------------------+
    | This manual provides an overview of the       | This section explains how to program      | This page covers connecting the feeder to Wi-Fi    |
    | CritterCuisine Pro 5000 automatic pet feeder, | the feeder's clock, set feeding           | using the CritterCuisine Connect app,  remote      |
    | including its features, safety precautions,   | schedules, copy and delete meal settings, | feeding, managing feeding schedules, viewing       |
    | assembly instructions, and initial setup.     | manually feed your pet, record            | feeding logs, receiving low food alerts,           |
    |                                               | a voice message, and understand           | updating firmware, creating multiple pet profiles, |
    |                                               | the low food level indicator.             | sharing access with other users, and cleaning      |
    |                                               |                                           | and maintaining the feeder.                        |
    +-----------------------------------------------+-------------------------------------------+----------------------------------------------------+
    

삭제

이 튜토리얼에서 사용된 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 리소스가 포함된 프로젝트를 삭제하거나 프로젝트를 유지하고 개별 리소스를 삭제하세요.

  1. Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.

또는 프로젝트를 유지하고 이 튜토리얼에서 사용한 리소스를 삭제하려면 다음 단계를 따르세요.

  1. BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 왼쪽 창에서 프로젝트를 펼친 다음 데이터 세트를 클릭합니다.

  3. bqml_tutorial 데이터 세트의 경우 작업 열기 > 삭제를 클릭합니다.

  4. 데이터 세트 삭제 대화상자에서 삭제를 클릭하여 확인합니다.

  5. 왼쪽 창에서 연결을 클릭합니다.

  6. cymbal_conn 연결의 경우 작업 열기 > 삭제를 클릭합니다.

  7. 연결 삭제 대화상자에서 delete를 입력한 다음 삭제를 클릭하여 확인합니다.

다음 단계