ML Kit의 생성형 AI 요약 API를 사용하면 기사 및 대화의 요약을 글머리 기호 목록으로 자동 생성할 수 있습니다. 이를 통해 사용자는 많은 텍스트를 이해할 수 있습니다.
요약은 데이터 개인 정보 보호 및 비용 효율성에 관한 문제를 해결하므로 기기 내 생성형 AI의 이점을 누릴 수 있습니다. 개인 채팅, 이메일, 메모, 미리 알림을 요약하는 앱은 민감한 정보를 처리하는 경우가 많으므로 사용자 개인 정보 보호를 위해 기기 내 처리가 중요합니다. 또한 요약 작업, 특히 컨텍스트가 길거나 항목이 많은 작업에는 상당한 처리 능력이 필요할 수 있습니다. 기기에서 이 콘텐츠를 처리하면 사용자 데이터를 비공개로 유지하면서 서버 부하를 줄이고 제공 비용을 낮출 수 있습니다.
주요 기능
생성형 AI 요약 API는 다음과 같은 기능을 포함합니다.
- 기사 또는 대화로 분류된 텍스트를 요약합니다.
- 요약을 글머리 기호 1개, 2개 또는 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 생성형 AI API는 Gemini Nano에 액세스하기 위해 Android AICore 앱을 사용합니다. 기기가 방금 설정되었거나 (초기화 포함) 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: 호스트를 확인할 수 없음으로 실패했습니다. | 네트워크 연결을 유지하고 몇 분 기다린 후 다시 시도하세요. |