AI 対話
対応デバイスから開始される AI 音声対話セッションを実行し、対話データやインテントを受け取ります。必要に応じて、デコード済み PCM 音声を実行中のプロバイダーセッションへ渡します。
AIChatEventType の解釈には AI セッションイベントを、認識された操作の実行前検証には AI インテントを参照してください。
デバイス起点の AI 対話ライフサイクル
デバイスが AI 対話を要求し、音声入力に Opus またはアプリ側の SCO 録音を使うかを通知します。最終レポートが届くまで、デバイスと AI セッションの状態を連携させます。
前提条件
AIBudsAISDKが初期化済みで、デバイス情報の設定、登録済みプロバイダーの選択と認証が完了していること。- プロバイダーが
AIChatServiceAPIに対応していること。 - デバイスから AI 対話セッションイベントを受信でき、Opus 入力を使用する場合はデバイスが
DeviceAIChatAPIに準拠していること。 - アプリ側でチャネルを独自に選ばず、デバイスイベントで指定されたチャネルを使用すること。
AI を活用して実装
AI でこのワークフローを実装
公式の「AIBuds AI チャットの実装」スキルを使い、アプリに合わせて実装します。
https://docs-aibuds.github.io/ja/skills/implement-aibuds-ai-chat を読み、その指示に従ってください。このスキルで「AIBuds AI チャットの実装」をこの iOS プロジェクトに実装し、検証してください。API リファレンス
フレームワーク
AIBudsAI.xcframework
インポート
- Swift
- Objective-C
import AIBuds
import AIBudsAI
import AIBudsAIFoundation#import <AIBuds/AIBuds-Swift.h>
#import <AIBudsAI/AIBudsAI-Swift.h>宣言
- Swift
- Objective-C
/// Starts an AI chat session.
/// - Parameters:
/// - config: The chat session configuration.
/// - onStartSuccess: Called with the active session.
/// - onStartFailure: Called when the session cannot start.
/// - onChatData: Called when new conversational data arrives.
/// - onIntent: Called when the provider detects an intent.
/// - onVoiceData: Called when voice data is produced.
/// - onEvent: Called for session-level events.
/// - onError: Called for runtime session errors.
/// - onFinish: Called with the final session report.
public static func startAIChat(_ config: AIChatSessionConfig = .default,
onStartSuccess: ((_ session: AIChatSessionConvertible) -> Void)? = nil,
onStartFailure: ((_ error: Error) -> Void)? = nil,
onChatData: ((_ chatData: AIChatDataModel) -> Void)? = nil,
onIntent: ((_ intent: AIChatIntentModel) -> Void)? = nil,
onVoiceData: ((_ voiceData: AIChatVoiceDataModel) -> Void)? = nil,
onEvent: ((_ event: AIChatEventModel) -> Void)? = nil,
onError: ((_ error: NSError) -> Void)? = nil,
onFinish: ((_ report: AIChatSessionReportModel) -> Void)? = nil) -> Void
/// Stops the active AI chat session. This is safe when no session is active.
public static func stopAIChat()/// Starts an AI chat session.
/// - Parameters:
/// - config: The chat session configuration.
/// - onStartSuccess: Called with the active session.
/// - onStartFailure: Called when the session cannot start.
/// - onChatData: Called when new conversational data arrives.
/// - onIntent: Called when the provider detects an intent.
/// - onVoiceData: Called when voice data is produced.
/// - onEvent: Called for session-level events.
/// - onError: Called for runtime session errors.
/// - onFinish: Called with the final session report.
+ (void)startAIChatWithConfig:(AIBudsAIChatSessionConfig * _Nonnull)config
onStartSuccess:(void (^ _Nullable)(id <AIBudsAIChatSessionConvertible> _Nonnull))onStartSuccess
onStartFailure:(void (^ _Nullable)(NSError * _Nonnull))onStartFailure
onChatData:(void (^ _Nullable)(AIBudsAIChatDataModel * _Nonnull))onChatData
onIntent:(void (^ _Nullable)(AIBudsAIChatIntentModel * _Nonnull))onIntent
onVoiceData:(void (^ _Nullable)(AIBudsAIChatVoiceDataModel * _Nonnull))onVoiceData
onEvent:(void (^ _Nullable)(AIBudsAIChatEventModel * _Nonnull))onEvent
onError:(void (^ _Nullable)(NSError * _Nonnull))onError
onFinish:(void (^ _Nullable)(AIBudsAIChatSessionReportModel * _Nonnull))onFinish;
/// Stops the active AI chat session. This is safe when no session is active.
+ (void)stopAIChat;startAIChat と stopAIChat を参照してください。
設定
AIChatSessionConfig では、AIChatSettingsController が使用する次の設定を指定できます。
| プロパティ | 既定値 | 用途 |
|---|---|---|
languageForSpeechInput | アプリの表示言語 | zh-CN など、選択中のプロバイダーが対応するハイフン区切りの音声入力言語。 |
audioChannel | .opusInA2dpOut | 対話セッションで使用する音声経路。セッション開始を通知するデバイスイベントと一致させます。 |
allowUserToInterruptAIResponse | true | 通常は音声再生中の AI 応答をユーザー入力で中断できるかどうか。 |
maxPauseDurationBeforeAIResponds | 0.8 秒 | AI が応答を開始するまでに許容する発話中の最長無音時間。 |
autoEndSessionAfterNoInputDuration | 15.0 秒 | 入力がない状態からセッションを自動終了するまでの時間。 |
enableVoicePlayback | true | 生成された音声を再生するかどうか。 |
shouldSaveVoiceForDebugging | false | 調査用の音声データを保存するかどうか。ポリシーで明示的に許可されていない限り、本番環境では無効にします。 |
additionalOptions | [:] | プロバイダー固有のエージェント、話者、プラン、プロンプト、インテント、ノイズ除去のオプション。 |
autoSelectAgentIfNotSpecified | true | プロバイダー固有のエージェントが未指定の場合に SDK が自動選択するかどうか。 |
プロバイダーのオプションキーを文字列で固定せず、公開されている AdditionalOptionKey... 定数を使用してください。
対話セッションを設定
Demo ではプロバイダー選択とセッション設定を分けています。ユーザーがプロバイダーを変更したら、最初に選択処理を行い、対応言語を取得し、アプリ起点の認証を完了してから対話を開始します。エージェント ID、話者 ID、インテントコード、利用プラン、初期プロンプトはプロバイダーから発行されるため、Demo の値を共通値として流用しないでください。
- Swift
- Objective-C
let vendor: AIServiceVendor = .starBurst
AIBudsAISDK.setAIServiceVendor(vendor)
let supportedLanguages = AIBudsAISDK.allSupportedLanguages(for: vendor)
let language = supportedLanguages.first?.languageCode
var options: [String: Any] = [:]
if let agentID = providerAgentID {
options[AIChatSessionConfig.AdditionalOptionKeyStarburstAgentId] = agentID
}
if let speakerID = providerSpeakerID {
options[AIChatSessionConfig.AdditionalOptionKeyStarburstSpeakerId] = speakerID
}
let config = AIChatSessionConfig(
languageForSpeechInput: language,
audioChannel: .opusInA2dpOut,
allowUserToInterruptAIResponse: true,
maxPauseDurationBeforeAIResponds: 0.8,
autoEndSessionAfterNoInputDuration: 15,
enableVoicePlayback: true,
shouldSaveVoiceForDebugging: false,
additionalOptions: options
)
config.autoSelectAgentIfNotSpecified = providerAgentID == nilAIBudsAIServiceVendor vendor = AIBudsAIServiceVendorStarBurst;
[AIBudsAISDK setAIServiceVendor:vendor];
NSArray<AIBudsAIServiceLanguage *> *supportedLanguages =
[AIBudsAISDK allSupportedLanguagesForVendor:vendor];
NSString *language = supportedLanguages.firstObject.languageCode;
NSMutableDictionary<NSString *, id> *options = [NSMutableDictionary dictionary];
if (self.providerAgentID.length > 0) {
options[AIBudsAIChatSessionConfig.AdditionalOptionKeyStarburstAgentId] = self.providerAgentID;
}
if (self.providerSpeakerID.length > 0) {
options[AIBudsAIChatSessionConfig.AdditionalOptionKeyStarburstSpeakerId] =
self.providerSpeakerID;
}
AIBudsAIChatSessionConfig *config = [[AIBudsAIChatSessionConfig alloc]
initWithLanguageForSpeechInput:language
audioChannel:AIBudsAIChatAudioChannelOpusInA2dpOut
allowUserToInterruptAIResponse:YES
maxPauseDurationBeforeAIResponds:0.8
autoEndSessionAfterNoInputDuration:15.0
enableVoicePlayback:YES
shouldSaveVoiceForDebugging:NO
additionalOptions:options];
config.autoSelectAgentIfNotSpecified = self.providerAgentID.length == 0;.mltcloud では対応する AdditionalOptionKeyMltCloud... 定数を使用します。StarBurst の利用プランやプロバイダー固有 ID は、プロバイダー設定から有効な値を取得できる場合にだけ指定してください。
使用例
通常、デバイスは .initiateWithSCO または .initiateWithOpus で対話開始を要求します。AI 対話を開始する前に、その要求チャネルをセッション設定へ反映してください。Opus の場合はデバイスから受信した音声をデコードし、PCM をセッションへ渡します。SCO の場合は .sco セッションを開始すると、デバイスのマイク音声をアプリ側で SCO 録音します。
- Swift
- Objective-C
let config = AIChatSessionConfig.default
config.audioChannel = .opusInA2dpOut
config.languageForSpeechInput = "en-US"
AIBudsAISDK.startAIChat(
config,
onStartSuccess: { session in
currentSession = session
},
onStartFailure: { error in
print("Chat start failed: \(error)")
},
onChatData: { chatData in
conversation.append(chatData)
},
onIntent: { intent in
handle(intent)
},
onVoiceData: { voiceData in
handle(voiceData)
},
onEvent: { event in
handle(event)
},
onError: { error in
print(error.localizedDescription)
},
onFinish: { report in
currentSession = nil
save(report)
}
)Opus 対話セッションでデバイスからデコード済み 16-bit PCM を受信したら、保持中のセッションへ渡します。currentSession?.appendInt16PCM?(decodedPCMData)
AIBudsAIChatSessionConfig *config = [AIBudsAIChatSessionConfig defaultConfig];
config.audioChannel = AIBudsAIChatAudioChannelOpusInA2dpOut;
config.languageForSpeechInput = @"en-US";
[AIBudsAISDK startAIChatWithConfig:config
onStartSuccess:^(id<AIBudsAIChatSessionConvertible> session) {
self.currentSession = session;
}
onStartFailure:^(NSError *error) {
NSLog(@"Chat start failed: %@", error);
}
onChatData:^(AIBudsAIChatDataModel *chatData) {
[self recordChatData:chatData];
}
onIntent:^(AIBudsAIChatIntentModel *intent) {
[self handleIntent:intent];
}
onVoiceData:^(AIBudsAIChatVoiceDataModel *voiceData) {
[self handleVoiceData:voiceData];
}
onEvent:^(AIBudsAIChatEventModel *event) {
[self handleEvent:event];
}
onError:^(NSError *error) {
NSLog(@"%@", error.localizedDescription);
}
onFinish:^(AIBudsAIChatSessionReportModel *report) {
self.currentSession = nil;
[self saveReport:report];
}];必要に応じてデコード済み PCM を転送します。[self.currentSession appendInt16PCM:decodedPCMData];
セッションを停止
デバイスから終了を要求されたら、デバイス側のフローで必要な場合は DeviceAIChatAPI を通じて停止状態を通知してから、次を呼び出します。
- Swift
- Objective-C
AIBudsAISDK.stopAIChat()
currentSession = nil[AIBudsAISDK stopAIChat];
self.currentSession = nil;注意事項
- これは音声セッション用 API であり、テキストの
sendMessageやメッセージ履歴を扱う API ではありません。 onFinish、回復不能なエラー、または明示的な停止までAIChatSessionConvertibleを保持してください。- SCO セッションでは、AIBuds AI SDK がアプリの SCO 接続を介してデバイスのマイク音声を録音します。Opus セッションではデバイスからアプリへ Opus 音声が送られるため、デコードした PCM を
appendInt16PCM(_:)へ渡してください。 - プライバシーと保存期間のポリシーで明示的に許可されていない限り、本番環境では
shouldSaveVoiceForDebuggingを有効にしないでください。