ML Kit의 GenAI Summarization API를 사용하면 기사 및 대화의 요약을 글머리기호 목록으로 자동 생성할 수 있습니다. 이를 통해 사용자는 대량의 텍스트를 이해할 수 있습니다.
요약은 데이터 개인 정보 보호 및 비용 효율성에 대한 우려사항을 해결하므로 기기 내 생성형 AI의 이점을 활용합니다. 개인 채팅, 이메일, 메모, 리마인더를 요약하는 앱은 민감한 정보를 처리하는 경우가 많으므로 기기 내 처리가 사용자 개인 정보 보호에 중요합니다. 또한 요약 작업, 특히 긴 컨텍스트나 항목이 많은 작업에는 상당한 처리 능력이 필요할 수 있습니다. 기기에서 콘텐츠를 처리하면 서버 부하가 줄고 게재 비용이 절감되며 사용자 데이터가 비공개로 유지됩니다.
주요 기능
GenAI Summarization API는 다음 기능을 다룹니다.
- 도움말 또는 대화로 분류된 텍스트를 요약합니다.
- 글머리기호 1개, 2개 또는 3개로 요약을 출력합니다.
시작하기
build.gradle
구성에 ML Kit summarization API를 종속 항목으로 추가합니다.
implementation("com.google.mlkit:genai-summarization:1.0.0-beta1")
다음으로 프로젝트에 코드를 구현합니다.
Summarizer
객체를 만듭니다.- 다운로드 가능한 경우 기능을 다운로드합니다.
- 요약 요청을 만듭니다.
- 추론을 실행하고 결과를 가져옵니다.
Kotlin
val articleToSummarize = "Announcing a set of on-device GenAI APIs..."
// Define task with required input type, output type, and language
val summarizerOptions = SummarizerOptions.builder(context)
.setInputType(InputType.ARTICLE)
.setOutputType(OutputType.ONE_BULLET)
.setLanguage(Language.ENGLISH)
.build()
val summarizer = Summarization.getClient(summarizerOptions)
suspend fun prepareAndStartSummarization() {
// Check feature availability. Status will be one of the following:
// UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE
val featureStatus = summarizer.checkFeatureStatus().await()
if (featureStatus == FeatureStatus.DOWNLOADABLE) {
// Download feature if necessary. If downloadFeature is not called,
// the first inference request will also trigger the feature to be
// downloaded if it's not already downloaded.
summarizer.downloadFeature(object : DownloadCallback {
override fun onDownloadStarted(bytesToDownload: Long) { }
override fun onDownloadFailed(e: GenAiException) { }
override fun onDownloadProgress(totalBytesDownloaded: Long) {}
override fun onDownloadCompleted() {
startSummarizationRequest(articleToSummarize, summarizer)
}
})
} else if (featureStatus == FeatureStatus.DOWNLOADING) {
// Inference request will automatically run once feature is
// downloaded. If Gemini Nano is already downloaded on the device,
// the feature-specific LoRA adapter model will be downloaded
// quickly. However, if Gemini Nano is not already downloaded, the
// download process may take longer.
startSummarizationRequest(articleToSummarize, summarizer)
} else if (featureStatus == FeatureStatus.AVAILABLE) {
startSummarizationRequest(articleToSummarize, summarizer)
}
}
fun startSummarizationRequest(text: String, summarizer: Summarizer) {
// Create task request
val summarizationRequest = SummarizationRequest.builder(text).build()
// Start summarization request with streaming response
summarizer.runInference(summarizationRequest) { newText ->
// Show new text in UI
}
// You can also get a non-streaming response from the request
// val summarizationResult = summarizer.runInference(
// summarizationRequest).get().summary
}
// Be sure to release the resource when no longer needed
// For example, on viewModel.onCleared() or activity.onDestroy()
summarizer.close()
자바
String articleToSummarize = "Announcing: a set of on-device GenAI AI APIs.";
// Define task with required input type, output type, and language
SummarizerOptions summarizerOptions =
SummarizerOptions.builder(context)
.setInputType(SummarizerOptions.InputType.ARTICLE)
.setOutputType(SummarizerOptions.OutputType.ONE_BULLET)
.setLanguage(SummarizerOptions.Language.ENGLISH)
.build();
Summarizer summarizer = Summarization.getClient(summarizerOptions);
void prepareAndStartSummarization()
throws ExecutionException, InterruptedException {
// Check feature availability. Status will be one of the following:
// UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE
try {
int featureStatus = summarizer.checkFeatureStatus().get();
if (featureStatus == FeatureStatus.DOWNLOADABLE) {
// Download feature if necessary.
// If downloadFeature is not called, the first inference request
// will also trigger the feature to be downloaded if it's not
// already downloaded.
summarizer.downloadFeature(new DownloadCallback() {
@Override
public void onDownloadCompleted() {
startSummarizationRequest(articleToSummarize, summarizer);
}
@Override
public void onDownloadFailed(GenAiException e) { /* handle error */ }
@Override
public void onDownloadProgress(long totalBytesDownloaded) {}
@Override
public void onDownloadStarted(long bytesDownloaded) {}
});
} else if (featureStatus == FeatureStatus.DOWNLOADING) {
// Inference request will automatically run once feature is
// downloaded. If Gemini Nano is already downloaded on the
// device, the feature-specific LoRA adapter model will be
// downloaded quickly. However, if Gemini Nano is not already
// downloaded, the download process may take longer.
startSummarizationRequest(articleToSummarize, summarizer);
} else if (featureStatus == FeatureStatus.AVAILABLE) {
startSummarizationRequest(articleToSummarize, summarizer);
}
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
void startSummarizationRequest(String text, Summarizer summarizer) {
// Create task request
SummarizationRequest summarizationRequest =
SummarizationRequest.builder(text).build();
// Start summarization request with streaming response
summarizer.runInference(summarizationRequest, newText -> {
// Show new text in UI
});
// You can also get a non-streaming response from the request
// ListenableFuture<SummarizationResult> summarizationResult
// = summarizer.runInference(summarizationRequest);
// String summary = summarizationResult.get().getSummary();
}
// Be sure to release the resource when no longer needed
// For example, on viewModel.onCleared() or activity.onDestroy()
summarizer.close();
모델이 다양한 입력 유형을 처리하는 방법
텍스트 입력이 InputType.CONVERSATION
로 지정된 경우 모델은 다음 형식의 입력을 예상합니다.
<name>: <message>
<name2>: <message2>
<name>: <message3>
<name3>: <message4>
이렇게 하면 모델이 대화와 상호작용을 더 잘 이해하여 더 정확한 요약을 생성할 수 있습니다.
지원되는 기능 및 제한사항
입력은 토큰 4,000개 (영어 약 3,000단어) 미만이어야 합니다. 입력이 토큰 4, 000개를 초과하는 경우 다음 옵션을 고려하세요.
- 처음 4,000개 토큰의 요약에 우선순위를 둡니다. 테스트 결과, 일반적으로 입력이 길수록 좋은 결과를 얻을 수 있습니다. 추가 입력이 자동으로 잘리도록
setLongInputAutoTruncationEnabled
를 호출하여 자동 자르기를 사용 설정해 보세요. - 입력을 4, 000개 토큰 그룹으로 분할하고 개별적으로 요약합니다.
- 더 큰 입력에 더 적합한 클라우드 솔루션을 고려하세요.
InputType.ARTICLE
의 경우 입력도 400자(영문 기준) 이상이어야 하며, 기사가 300단어 이상일 때 모델의 성능이 가장 좋습니다.
GenAI Summarization API는 한국어, 영어, 일본어를 지원하며 SummarizerOptions.Language
에 정의되어 있습니다.
특정 기능 구성 (SummarizerOptions
로 지정됨)의 사용 가능 여부는 특정 기기의 구성과 기기에 다운로드된 모델에 따라 다를 수 있습니다.
개발자가 요청된 SummarizerOptions
가 있는 기기에서 의도한 API 기능이 지원되는지 확인하는 가장 안정적인 방법은 checkFeatureStatus()
메서드를 호출하는 것입니다. 이 메서드는 런타임에 기기의 기능 사용 가능 여부에 관한 확실한 상태를 제공합니다.
일반적인 설정 문제
ML Kit GenAI API는 Android AICore 앱을 사용하여 Gemini Nano에 액세스합니다. 기기가 초기화된 직후 (초기화 포함) 또는 AICore 앱이 초기화된 직후 (예: 데이터 삭제, 제거 후 재설치)에는 AICore 앱이 초기화를 완료할 시간이 충분하지 않을 수 있습니다 (서버에서 최신 구성 다운로드 포함). 따라서 ML Kit GenAI API가 예상대로 작동하지 않을 수 있습니다. 다음은 표시될 수 있는 일반적인 설정 오류 메시지와 처리 방법입니다.
오류 메시지 예 | 처리 방법 |
AICore가 오류 유형 4-CONNECTION_ERROR 및 오류 코드 601-BINDING_FAILURE으로 실패했습니다. AICore 서비스가 바인딩되지 않았습니다. | 이는 기기 설정 직후 ML Kit GenAI API를 사용하여 앱을 설치하거나 앱이 설치된 후 AICore가 제거될 때 발생할 수 있습니다. AICore 앱을 업데이트한 후 앱을 재설치하면 문제가 해결됩니다. |
AICore가 오류 유형 3-PREPARATION_ERROR 및 오류 코드 606-FEATURE_NOT_FOUND: Feature ... is not available 오류로 실패했습니다. |
이는 AICore가 최신 구성 다운로드를 완료하지 않은 경우 발생할 수 있습니다. 네트워크 연결을 유지하고 몇 분에서 몇 시간 정도 기다립니다.
기기의 부트로더가 잠금 해제된 경우에도 이 오류가 표시됩니다. 이 API는 부트로더가 잠금 해제된 기기를 지원하지 않습니다. |
AICore가 오류 유형 1-DOWNLOAD_ERROR 및 오류 코드 0-UNKNOWN으로 실패했습니다. 기능 ... 실패 상태 0 및 오류 esz: UNAVAILABLE: 호스트를 확인할 수 없음 ... | 네트워크 연결을 유지하고 몇 분 정도 기다린 후 다시 시도합니다. |