ML Kit의 GenAI 요약 API를 사용하면 기사와 대화의 요약을 글머리 기호 목록으로 자동 생성할 수 있습니다. 이를 통해 사용자는 대량의 텍스트를 이해할 수 있습니다.
요약은 데이터 개인 정보 보호 및 비용 효율성에 대한 우려를 해결하므로 기기 내 생성형 AI의 이점을 누릴 수 있습니다. 개인 채팅, 이메일, 메모, 알림을 요약하는 앱은 민감한 정보를 처리하는 경우가 많으므로 사용자 개인 정보 보호를 위해 온디바이스 처리가 중요합니다. 또한 요약 작업, 특히 컨텍스트가 길거나 항목이 많은 요약 작업에는 상당한 처리 능력이 필요할 수 있습니다. 기기에서 이 콘텐츠를 처리하면 서버 부하가 줄고 서버 사용 비용이 낮아지며 사용자 데이터는 비공개로 유지됩니다.
주요 기능
생성형 AI 요약 API는 다음 기능을 지원합니다.
- 텍스트를 요약하고, 텍스트를 문서 또는 대화로 분류합니다.
- 요약을 1~3개의 글머리 기호로 출력합니다.
시작하기
build.gradle
구성에 ML Kit 요약 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단어 이상일 때 모델의 성능이 가장 좋습니다.
생성형 AI 요약 API는 한국어, 영어, 일본어를 지원하며 SummarizerOptions.Language
에 정의되어 있습니다.
특정 기능 구성 (SummarizerOptions
로 지정)의 사용 가능 여부는 특정 기기의 구성과 기기에 다운로드된 모델에 따라 달라질 수 있습니다.
개발자가 요청된 SummarizerOptions
가 있는 기기에서 의도한 API 기능이 지원되는지 확인하는 가장 안정적인 방법은 checkFeatureStatus()
메서드를 호출하는 것입니다. 이 메서드는 런타임에 기기에서 기능이 사용 가능한지 여부를 나타내는 최종 상태를 제공합니다.
일반적인 설정 문제
ML Kit GenAI API는 Android AICore 앱을 사용하여 Gemini Nano에 액세스합니다. 기기가 설정된 직후 (초기화 포함) 또는 AICore 앱이 초기화된 직후 (예: 데이터 삭제, 제거 후 재설치)에는 AICore 앱이 초기화 (서버에서 최신 구성 다운로드 포함)를 완료할 시간이 충분하지 않을 수 있습니다. 따라서 ML Kit 생성형 AI API가 예상대로 작동하지 않을 수 있습니다. 표시될 수 있는 일반적인 설정 오류 메시지와 처리 방법은 다음과 같습니다.
오류 메시지 예 | 처리 방법 |
AICore가 오류 유형 4-CONNECTION_ERROR 및 오류 코드 601-BINDING_FAILURE로 실패했습니다. AICore 서비스가 바인딩되지 않았습니다. | 기기 설정 직후 ML Kit 생성형 AI API를 사용하여 앱을 설치하거나 앱이 설치된 후 AICore가 제거되는 경우에 발생할 수 있습니다. AICore 앱을 업데이트한 후 앱을 다시 설치하면 문제가 해결됩니다. |
AICore가 오류 유형 3-PREPARATION_ERROR 및 오류 코드 606-FEATURE_NOT_FOUND로 실패했습니다. 기능 ...을 사용할 수 없습니다. |
이는 AICore가 최신 구성 다운로드를 완료하지 않은 경우 발생할 수 있습니다. 기기가 인터넷에 연결되어 있으면 업데이트하는 데 보통 몇 분에서 몇 시간이 걸립니다. 기기를 다시 시작하면 업데이트 속도를 높일 수 있습니다.
기기의 부트로더가 잠금 해제된 경우에도 이 오류가 표시됩니다. 이 API는 부트로더가 잠금 해제된 기기를 지원하지 않습니다. |
AICore가 오류 유형 1-DOWNLOAD_ERROR 및 오류 코드 0-UNKNOWN으로 실패했습니다. 기능 ...이 실패 상태 0 및 오류 esz: UNAVAILABLE로 실패했습니다. 호스트 ...를 확인할 수 없습니다. | 네트워크 연결을 유지하고 몇 분 정도 기다린 후 다시 시도합니다. |