AI-сводка
Создавайте краткую сводку текста и обновляйте интерфейс по мере поступления результатов от выбранного поставщика.
Предварительные условия
AIBudsAISDKинициализирован, и выбран зарегистрированный поставщик.- Поставщик поддерживает
AISummaryServiceAPI. - При необходимости доступны авторизация поставщика и сетевое подключение.
- Исходный текст не пуст.
Реализация с помощью AI
Разработка с AI
Реализуйте этот сценарий с AI
Используйте официальный навык «Реализация ИИ-сводки AIBuds» и адаптируйте сценарий к приложению.
Прочитайте и выполните инструкции https://docs-aibuds.github.io/ru/skills/implement-aibuds-ai-summary. Используйте этот навык, чтобы реализовать «Реализация ИИ-сводки AIBuds» в данном iOS-проекте и проверить результат.API Reference
Framework
AIBudsAI.xcframework
Import
- Swift
- Objective-C
import AIBudsAI#import <AIBudsAI/AIBudsAI-Swift.h>Declaration
- Swift
- Objective-C
/// Generates a concise summary for the provided text.
/// - Parameters:
/// - text: The text to summarize.
/// - streamResultHandler: Called repeatedly with the current summary.
/// - isFinal: `true` when the summary is complete; otherwise `false`.
/// - transcript: The current incremental summary text.
/// - error: The operation error, or `nil` when no error occurred.
public static func summary(withText text: String,
streamResultHandler: ((_ isFinal: Bool, _ transcript: String?, _ error: Error?) -> Void)? = nil)
/// Cancels the current summary operation before it completes.
public static func cancelSummary()/// Generates a concise summary for the provided text.
/// - Parameters:
/// - text: The text to summarize.
/// - streamResultHandler: Called repeatedly with the current summary.
/// - isFinal: `YES` when the summary is complete; otherwise `NO`.
/// - transcript: The current incremental summary text.
/// - error: The operation error, or `nil` when no error occurred.
+ (void)summaryWithText:(NSString * _Nonnull)text
streamResultHandler:(void (^ _Nullable)(BOOL, NSString * _Nullable, NSError * _Nullable))streamResultHandler;
/// Cancels the current summary operation before it completes.
+ (void)cancelSummary;См. summary и cancelSummary.
Примеры использования
- Swift
- Objective-C
let sourceText = """
The AIBuds SDK connects supported devices to an iOS application and exposes
device control, media, AI, voice assistant, and diagnostic capabilities.
"""
AIBudsAISDK.summary(withText: sourceText) { isFinal, transcript, error in
DispatchQueue.main.async {
if let error {
summaryLabel.text = "Summary failed: \(error.localizedDescription)"
return
}
if let transcript {
summaryLabel.text = transcript
}
if isFinal {
summaryActivityIndicator.stopAnimating()
}
}
}NSString *sourceText = @"The AIBuds SDK connects supported devices to an iOS application and "
"exposes device control, media, AI, voice assistant, and diagnostic "
"capabilities.";
[AIBudsAISDK summaryWithText:sourceText
streamResultHandler:^(BOOL isFinal, NSString *transcript, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error != nil) {
self.summaryLabel.text = [NSString
stringWithFormat:@"Summary failed: %@", error.localizedDescription];
return;
}
if (transcript != nil) {
self.summaryLabel.text = transcript;
}
if (isFinal) {
[self.summaryActivityIndicator stopAnimating];
}
});
}];Отмените выполняющийся запрос, если его результат больше не нужен:
- Swift
- Objective-C
AIBudsAISDK.cancelSummary()[AIBudsAISDK cancelSummary];Примечания
- API создаёт сводку только из текста: он не принимает путь к файлу и не предоставляет параметр
maxLength. - Каждое новое значение transcript может заменять предыдущее, поскольку поставщик возвращает постепенно дополняемую сводку.
- Ошибка, отличная от
nil, означает сбой, даже если ранее уже был получен transcript. cancelSummary()не предоставляет completion callback; обновляйте состояние приложения при запросе отмены.