Gemini 모델과 ML.GENERATE_TEXT 함수를 사용하여 텍스트 생성
이 튜토리얼에서는 gemini-2.0-flash
모델을 기반으로 하는 원격 모델을 만드는 방법과 이 모델을 ML.GENERATE_TEXT
함수와 함께 사용하여 bigquery-public-data.imdb.reviews
공개 테이블에서 영화 리뷰에서 키워드를 추출하고 감정 분석을 수행하는 방법을 보여줍니다.
필요한 역할
이 튜토리얼을 실행하려면 다음 Identity and Access Management (IAM) 역할이 필요합니다.
- BigQuery 데이터 세트, 연결, 모델을 만들고 사용하려면 BigQuery 관리자 (
roles/bigquery.admin
)가 필요합니다. - 연결의 서비스 계정에 권한 부여: 프로젝트 IAM 관리자(
roles/resourcemanager.projectIamAdmin
)
이러한 사전 정의된 역할에는 이 문서의 작업을 수행하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 확장하세요.
필수 권한
- 데이터 세트 만들기:
bigquery.datasets.create
- 연결을 만들고, 위임하고, 사용합니다.
bigquery.connections.*
- 기본 연결 설정:
bigquery.config.*
- 서비스 계정 권한 설정:
resourcemanager.projects.getIamPolicy
및resourcemanager.projects.setIamPolicy
- 모델을 만들고 추론을 실행합니다.
bigquery.jobs.create
bigquery.models.create
bigquery.models.getData
bigquery.models.updateData
bigquery.models.updateMetadata
커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.
비용
이 문서에서는 비용이 청구될 수 있는 Google Cloud구성요소( )를 사용합니다.
- BigQuery ML: You incur costs for the data that you process in BigQuery.
- Vertex AI: You incur costs for calls to the Vertex AI service that's represented by the remote model.
프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용합니다.
BigQuery 가격 책정에 대한 자세한 내용은 BigQuery 문서의 BigQuery 가격 책정을 참조하세요.
Vertex AI 가격 책정에 대한 자세한 내용은 Vertex AI 가격 책정 페이지를 참조하세요.
시작하기 전에
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the BigQuery, BigQuery Connection, and Vertex AI APIs.
데이터 세트 만들기
ML 모델을 저장할 BigQuery 데이터 세트를 만듭니다.
콘솔
Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.
탐색기 창에서 프로젝트 이름을 클릭합니다.
작업 보기 > 데이터 세트 만들기를 클릭합니다.
데이터 세트 만들기 페이지에서 다음을 수행합니다.
데이터 세트 ID에
bqml_tutorial
를 입력합니다.위치 유형에 대해 멀티 리전을 선택한 다음 US(미국 내 여러 리전)를 선택합니다.
나머지 기본 설정은 그대로 두고 데이터 세트 만들기를 클릭합니다.
bq
새 데이터 세트를 만들려면 --location
플래그와 함께 bq mk
명령어를 실행합니다. 사용할 수 있는 전체 파라미터 목록은 bq mk --dataset
명령어 참조를 확인하세요.
데이터 위치가
US
로 설정되고 설명이BigQuery ML tutorial dataset
인bqml_tutorial
데이터 세트를 만듭니다.bq --location=US mk -d \ --description "BigQuery ML tutorial dataset." \ bqml_tutorial
--dataset
플래그를 사용하는 대신 이 명령어는-d
단축키를 사용합니다.-d
와--dataset
를 생략하면 이 명령어는 기본적으로 데이터 세트를 만듭니다.데이터 세트가 생성되었는지 확인합니다.
bq ls
API
데이터 세트 리소스가 정의된 datasets.insert
메서드를 호출합니다.
{ "datasetReference": { "datasetId": "bqml_tutorial" } }
BigQuery DataFrames
이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.
BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.
원격 모델 만들기
호스팅된 Vertex AI 모델을 나타내는 원격 모델을 만듭니다.
Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.
쿼리 편집기에서 다음 쿼리를 실행합니다.
CREATE OR REPLACE MODEL `bqml_tutorial.gemini_model` REMOTE WITH CONNECTION DEFAULT OPTIONS (ENDPOINT = 'gemini-2.0-flash');
쿼리가 완료되는 데 몇 초 정도 걸리며 그 이후에는 gemini_model
모델이 탐색기 창의 bqml_tutorial
데이터 세트에 표시됩니다.
이 쿼리에서는 CREATE MODEL
문을 사용하여 모델을 만들므로 쿼리 결과가 없습니다.
키워드 추출 수행
원격 모델과 ML.GENERATE_TEXT
함수를 사용하여 IMDB 영화 리뷰에서 키워드를 추출합니다.
Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.
쿼리 편집기에서 다음 문을 입력하여 영화 리뷰 5개에서 키워드를 추출합니다.
SELECT ml_generate_text_result['candidates'][0]['content'] AS generated_text, * EXCEPT (ml_generate_text_result) FROM ML.GENERATE_TEXT( MODEL `bqml_tutorial.gemini_model`, ( SELECT CONCAT('Extract the key words from the text below: ', review) AS prompt, * FROM `bigquery-public-data.imdb.reviews` LIMIT 5 ), STRUCT( 0.2 AS temperature, 100 AS max_output_tokens));
출력은 다음과 유사하며 생성되지 않은 열은 명확성을 위해 생략됩니다.
+----------------------------------------+-------------------------+----------------------------+-----+ | generated_text | ml_generate_text_status | prompt | ... | +----------------------------------------+-------------------------+----------------------------+-----+ | {"parts":[{"text":"## Key words:\n\n* | | Extract the key words from | | | **Negative sentiment:** \"terribly | | the text below: I had to | | | bad acting\", \"dumb story\", \"not | | see this on the British | | | even a kid would enjoy this\", | | Airways plane. It was | | | \"something to switch off\"\n* | | terribly bad acting and | | | **Context:** \"British Airways plane\" | | a dumb story. Not even | | | \n* **Genre:** \"movie\" (implied)... | | a kid would enjoy this... | | +----------------------------------------+-------------------------+----------------------------+-----+ | {"parts":[{"text":"## Key words:\n\n* | | Extract the key words from | | | **Movie:** The Real Howard Spitz\n* | | the text below: This is | | | **Genre:** Family movie\n* | | a family movie that was | | | **Broadcast:** ITV station, 1.00 am\n* | | broadcast on my local | | | **Director:** Vadim Jean\n* | | ITV station at 1.00 am a | | | **Main character:** Howard Spitz, | | couple of nights ago. | | | a children's author who hates... | | This might be a strange... | | +----------------------------------------+-------------------------+----------------------------+-----+
결과에 다음 열이 포함됩니다.
generated_text
: 생성된 텍스트입니다.ml_generate_text_status
: 해당 행의 API 응답 상태입니다. 작업이 성공하면 이 값이 비어 있습니다.prompt
: 감정 분석에 사용되는 프롬프트입니다.bigquery-public-data.imdb.reviews
테이블의 모든 열입니다.
선택사항: 이전 단계에서 수행한 것처럼 함수에서 반환한 JSON을 수동으로 파싱하는 대신
flatten_json_output
인수를 사용하여 생성된 텍스트와 안전 특성을 개별 열에 반환합니다.쿼리 편집기에서 다음 쿼리를 실행합니다.
SELECT * FROM ML.GENERATE_TEXT( MODEL `bqml_tutorial.gemini_model`, ( SELECT CONCAT('Extract the key words from the text below: ', review) AS prompt, * FROM `bigquery-public-data.imdb.reviews` LIMIT 5 ), STRUCT( 0.2 AS temperature, 100 AS max_output_tokens, TRUE AS flatten_json_output));
출력은 다음과 유사하며 명확성을 위해 생성되지 않은 열은 생략됩니다.
+----------------------------------------+----------------------------------------------+-------------------------+----------------------------+-----+ | ml_generate_text_llm_result | ml_generate_text_rai_result | ml_generate_text_status | prompt | ... | +----------------------------------------+----------------------------------------------+-------------------------+----------------------------+-----+ | ## Keywords: | | | Extract the key words from | | | | | | the text below: I had to | | | * **Negative sentiment:** | | | see this on the British | | | "terribly bad acting", "dumb | | | Airways plane. It was | | | story", "not even a kid would | | | terribly bad acting and | | | enjoy this", "switch off" | | | a dumb story. Not even | | | * **Context:** "British | | | a kid would enjoy this... | | +----------------------------------------+----------------------------------------------+-------------------------+----------------------------+-----+ | ## Key words: | | | Extract the key words from | | | | | | the text below: This is | | | * **Movie:** The Real Howard Spitz | | | a family movie that was | | | * **Genre:** Family movie | | | broadcast on my local | | | * **Broadcast:** ITV, 1.00 | | | ITV station at 1.00 am a | | | am | | | couple of nights ago. | | | - ... | | | This might be a strange... | | +----------------------------------------+----------------------------------------------+-------------------------+----------------------------+-----+
결과에 다음 열이 포함됩니다.
ml_generate_text_llm_result
: 생성된 텍스트입니다.ml_generate_text_rai_result
: 차단 카테고리 중 하나로 인해 콘텐츠가 차단되었는지 여부에 대한 정보가 포함된 안전 속성입니다. 안전 속성에 대한 자세한 내용은 안전 필터 구성을 참고하세요.ml_generate_text_status
: 해당 행의 API 응답 상태입니다. 작업이 성공하면 이 값이 비어 있습니다.prompt
: 키워드 추출에 사용되는 프롬프트입니다.bigquery-public-data.imdb.reviews
테이블의 모든 열입니다.
감정 분석 수행
원격 모델과 ML.GENERATE_TEXT
함수를 사용하여 IMDB 영화 리뷰에 대한 감정 분석을 수행합니다.
Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.
쿼리 편집기에서 다음 문을 실행하여 영화 리뷰 5개에 대한 감정 분석을 수행합니다.
SELECT ml_generate_text_result['candidates'][0]['content'] AS generated_text, * EXCEPT (ml_generate_text_result) FROM ML.GENERATE_TEXT( MODEL `bqml_tutorial.gemini_model`, ( SELECT CONCAT( 'perform sentiment analysis on the following text, return one the following categories: positive, negative: ', review) AS prompt, * FROM `bigquery-public-data.imdb.reviews` LIMIT 5 ), STRUCT( 0.2 AS temperature, 100 AS max_output_tokens));
출력은 다음과 유사하며 생성되지 않은 열은 명확성을 위해 생략됩니다.
+--------------------------------------------+-------------------------+----------------------------+-----+ | generated_text | ml_generate_text_status | prompt | ... | +--------------------------------------------+-------------------------+----------------------------+-----+ | {"parts":[{"text":"## Sentiment Analysis: | | perform sentiment analysis | | | Negative \n\nThis text expresses a | | on the following text, | | | strongly negative sentiment towards the | | return one the following | | | movie. Here's why:\n\n* **Negative | | negative: I had to see | | | like \"terribly,\" \"dumb,\" and | | this on the British | | | \"not even\" to describe the acting... | | Airways plane. It was... | | +--------------------------------------------+-------------------------+----------------------------+-----+ | {"parts":[{"text":"## Sentiment Analysis: | | perform sentiment analysis | | | Negative \n\nThis review expresses a | | on the following text, | | | predominantly negative sentiment towards | | return one the following | | | the movie \"The Real Howard Spitz.\" | | categories: positive, | | | Here's why:\n\n* **Criticism of the film's | | negative: This is a family | | | premise:** The reviewer finds it strange | | movie that was broadcast | | | that a film about a children's author... | | on my local ITV station... | | +--------------------------------------------+-------------------------+----------------------------+-----+
결과에는 키워드 추출 수행에 대해 설명된 것과 동일한 열이 포함됩니다.
삭제
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.