콘텐츠 요약

문서 버전을 선택합니다.

ai.summarize 함수는 Gemini와 같은 대규모 언어 모델 (LLM)을 활용하여 입력 텍스트를 가장 필수적인 형태로 바꿔 쓰고 재구성합니다. 이 함수는 원본 작성자의 어조와 뉘앙스를 유지하면서 문서의 핵심 논제를 포착합니다. 이 함수를 사용하면 수동 검토 없이 대규모 데이터 세트에서 주요 결과와 결론을 추출하고 프롬프트에서 단어 수 또는 문장 제한과 같은 제약 조건을 지정하여 출력 길이를 제어할 수 있습니다. 일괄 처리 또는 커서 기반 스냅샷을 사용하여 수백만 개의 행을 비동기식으로 처리할 수도 있습니다.

AlloyDB AI 콘텐츠 요약 함수는 다음을 포함하되 이에 국한되지 않는 다양한 사용 사례를 지원합니다.

  • 회의 트랜스크립트: 의사 결정 및 작업 항목에 집중할 수 있도록 대화형 텍스트를 요약합니다.
  • 기술 문서: 복잡한 방법론, 결과, 영향을 간략한 개요로 압축합니다.
  • 고객 지원 로그: 여러 사용자 리뷰 또는 지원 티켓을 일반적인 문제에 대한 단일 통합 요약으로 집계합니다.

시작하기 전에

ai.summarize 함수를 사용하기 전에 다음 요구사항을 충족하는지 확인하세요.

확장 프로그램 사용 설정

미리보기 기능이 사용 설정된 상태로 최신 버전의 google_ml_integration.enable_preview_ai_functions 확장 프로그램 (버전 1.5.7 이상)이 설치되어 있는지 확인합니다.

AlloyDB Omni에서 google_ml_integration.enable_preview_ai_functions 플래그를 사용 설정하려면 SET 명령어를 사용합니다. 이 플래그는 ai.summarize와 같은 미리보기 AI 함수에 대한 액세스를 제어합니다.

  1. google_ml_integration extension이 버전 1.5.7 이상인지 확인합니다. 다음 명령어를 실행하여 버전을 확인할 수 있습니다.

    SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';
    

    이러한 미리보기 함수가 포함된 버전으로 업그레이드해야 하는 경우 다음을 호출합니다.

    CALL google_ml.upgrade_to_preview_version();
    
  2. 현재 세션 또는 전체 데이터베이스에 플래그를 사용 설정합니다. 현재 세션에 플래그를 사용 설정하려면 다음을 실행합니다.

    SET google_ml_integration.enable_preview_ai_functions = 'on';
    

    이 변경사항에는 데이터베이스를 다시 시작할 필요가 없습니다. 이 플래그의 기본값은 off입니다.

예시 테이블 만들기

이 문서의 요약 함수 예시를 따르려면 테이블을 만들고 다음 영화 리뷰로 채웁니다.

CREATE TABLE movie_reviews (
    id INT PRIMARY KEY,
    movie_id INT,
    review TEXT
);

INSERT INTO movie_reviews (id, movie_id, review) VALUES
(1, 1, 'The Midnight Echo represents a masterclass in atmospheric tension. The cinematography captures the isolation of the frozen tundra perfectly while the lead actor delivers a superb performance. Although the pacing slows down significantly in the second act, the final twist remains unexpected. This is a truly remarkable experience.'),
(2, 1, 'Neon Velocity delivers high octane action but lacks the narrative depth required to make the stakes feel real. The visual effects are undeniably stunning, creating a vibrant cyberpunk world that pops off the screen. However, the dialogue feels cliched and the secondary characters are thin. This film is a shallow blockbuster.'),

-- more rows are present in this table

단일 문자열 요약

단일 텍스트 블록을 처리하려면 ai.summarize의 스칼라 버전을 사용합니다.

SELECT ai.summarize(
  prompt => 'TEXT_CONTENT',
  model_id => 'MODEL_ID' -- Optional
);

다음 예시 쿼리를 실행하여 영화 리뷰의 간결한 요약을 제공합니다.

SELECT ai.summarize(review) FROM movie_reviews;

출력 예시는 다음과 같습니다.

 id |                         summary
----+-----------------------------------------------------------
  1 | "Atmospheric thriller with a haunting performance and shocking twist."
  2 | "Visually stunning cyberpunk action film lacks narrative depth."
...

일괄 요약

여러 레코드를 효율적으로 처리하려면 배열 기반 버전을 사용합니다.

SELECT ai.summarize(
  prompts => TEXT[],
  batch_size => INT, -- Optional. The default is 10.
  model_id => VARCHAR(100) -- Optional. The default value is gemini-2.5-flash-lite.
);

다음 예시에서는 ai.summarize 함수의 배열 기반 버전을 사용하여 단일 호출에서 여러 텍스트 레코드를 효율적으로 처리하는 방법을 보여줍니다.

WITH summarized_results AS (
SELECT
  ARRAY_AGG(id ORDER BY id) as ids,
  ai.summarize(
    prompts => array_agg( 'Please summarize this in max 10 words, review : ' || review
      ORDER BY id),
    batch_size => 15) as summaries
FROM movie_reviews
),
correlated_results AS (
    SELECT ids[i] as ID, summaries[i] as summary
    FROM summarized_results,
    generate_series(1, array_length(ids, 1)) AS i
)
SELECT movie_reviews.id, correlated_results.summary as summary
FROM movie_reviews
JOIN correlated_results ON movie_reviews.id = correlated_results.id
ORDER BY movie_reviews.id DESC ;

출력 예시는 다음과 같습니다.

 id | summary
---+----------------------------------------------------------------------------
  1 | "Masterclass in tension, haunting performance with a twist."
  2 | "High octane action, stunning visuals, shallow blockbuster."
  3 | "Gentle, moving exploration of  emotional honesty."

커서를 사용하여 요약

커서를 사용하면 잠재적으로 큰 리뷰 세트를 효율적으로 처리하고, AI 함수에 제공한 다음, 결과를 하나씩 처리하여 데이터베이스에 다시 저장할 수 있습니다.

다음 예시에서는 ai.summarize 함수와 함께 커서를 사용하여 movie_reviews 테이블의 행을 효율적으로 처리하고, 각 리뷰의 요약을 생성하고, 이러한 요약을 review_summaries라는 새 테이블에 저장하는 방법을 보여줍니다. 이 커서 기반 접근 방식은 단일 일괄 처리로 처리하거나 한 번에 메모리에 맞추기에 너무 클 수 있는 대규모 데이터 세트를 처리하는 데 유용합니다.

input_cursor 매개변수는 REFCURSOR를 가져옵니다. 즉, SQL 쿼리 결과에 대한 포인터 역할을 하는 커서 이름을 제공해야 합니다. 그러면 ai.summarize 함수는 이 커서에서 데이터를 가져와 요약의 입력으로 사용합니다.

CREATE OR REPLACE FUNCTION ai.summarize(
  prompt TEXT,
  input_cursor REFCURSOR,
  batch_size INT DEFAULT NULL,
  model_id VARCHAR(100) DEFAULT NULL)
RETURNS REFCURSOR

다음 예시에서는 필요한 경우 review_summaries 테이블을 만든 다음 영화 리뷰를 반복하고, AI 함수를 사용하여 각 리뷰의 간결한 요약을 생성하고, 요약을 테이블의 원래 리뷰 ID에 연결하여 저장합니다.

-- Create a table to store the results
CREATE TABLE IF NOT EXISTS review_summaries (
    review_id INT, 
    summary_text TEXT
);

DO $$
DECLARE
    -- Use descriptive cursor and variable names
    review_cursor   REFCURSOR;
    result_record   RECORD;
    cursor_response  REFCURSOR;
    id_array        INT[];
    idx             INT := 1; 
BEGIN
    -- 1. Open cursor for the input text
    OPEN review_cursor FOR 
        SELECT review AS prompt FROM movie_reviews ORDER BY id;

    -- 2. Call the AI summarize function
    cursor_response := ai.summarize(
        prompt       => 'Please summarize the following review in max 10 words: ',
        input_cursor => review_cursor
    );

    -- 3. Map IDs into an array to maintain relational integrity during the loop
    SELECT ARRAY_AGG(id ORDER BY id) INTO id_array FROM movie_reviews;

    -- 4. Iterate through AI results and insert into the results table
    LOOP
        FETCH cursor_response INTO result_record;
        EXIT WHEN NOT FOUND;

        INSERT INTO review_summaries (review_id, summary_text)
        VALUES (id_array[idx], result_record.output);

        idx := idx + 1;
    END LOOP;

    -- 5. Clean up cursors
    CLOSE review_cursor;
    CLOSE cursor_response;
END;
$$;

-- Verify results
SELECT * FROM review_summaries;

출력 예시는 다음과 같습니다.

 review_id | summary_text
-----------+---------------------------------------------------------------------------
         1 | "Masterclass in atmospheric tension with haunting performance, devastating twist."
         2 | "High octane action, stunning visuals, but shallow blockbuster."
         3 | "Gentle, moving exploration of grief with poetic screenplay."

행 간 요약 집계

ai.agg_summarize 함수는 열의 여러 행에서 작동합니다. 값을 통합 프롬프트로 집계하여 전체 그룹에 대한 단일 요약을 생성합니다.

다음 SQL 쿼리는 ai.agg_summarize 집계 함수를 사용하여 movie_reviews 테이블의 모든 리뷰를 기반으로 모든 movie_id에 대한 단일 통합 요약을 생성합니다.

select ai.agg_summarize(review) from movie_reviews group by movie_id;

각 행을 개별적으로 요약하는 ai.summarize와 달리 ai.agg_summarize는 여러 행의 텍스트를 단일 입력으로 결합하여 전체 행 그룹에 대한 통합 요약을 생성합니다.

출력 예시는 다음과 같습니다.

agg_summarize
"The Midnight Echo is a masterclass in atmospheric tension, featuring haunting performances and stunning cinematography, though its pacing falters in the second act before a final twist. Neon Velocity offers stunning visual effects and high-octane action within a vibrant cyberpunk world, but suffers from shallow narrative depth, cliched dialogue, and underdeveloped characters. Garden of Whispers is a gentle, moving, and emotionally honest exploration of and life, characterized by poetic screenwriting and natural performances. Shadow Protocol ambitiously attempts to reinvent the spy thriller with a non-linear narrative and precise action, but ultimately confuses the audience and presents a derivative central mystery. The Last Alchemist uniquely blends historical drama with subtle fantasy, boasting meticulous production design and electric chemistry between its protagonists."

다음 단계