AI 对话
响应受支持设备发起的 AI 对话请求,接收对话内容和意图,并根据设备指定的音频通道接入用户语音。
有关 AIChatEventType 的会话事件,请参阅 AI 会话事件;执行识别出的操作前,请根据 AI 意图完成校验。
由设备发起的 AI 对话流程
设备发起 AI 对话时,会指定由设备通过 Opus 发送语音,或由 App 通过 SCO 采集语音。整个过程中需要保持设备状态与 AI 会话状态一致。
前提条件
AIBudsAISDK已初始化,当前设备信息已配置,并已选择已注册且鉴权成功的 AI 服务商。- AI 服务商支持
AIChatServiceAPI。 - 设备会发送 AI 对话会话事件;使用 Opus 输入时,设备遵循
DeviceAIChatAPI。 - 音频通道必须读取设备事件中的请求,不应由 App 独立选择。
使用 AI 辅助实现
让 AI 帮助实现此工作流
使用官方“实现 AIBuds AI 对话”技能,根据你的 App 完成实现。
请阅读并遵循 https://docs-aibuds.github.io/zh-Hans/skills/implement-aibuds-ai-chat,使用该技能在当前 iOS 项目中完成“实现 AIBuds AI 对话”,并验证结果。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 | App 语言 | 语音输入语言,使用 AI 服务商支持的连字符格式标识符,例如 zh-CN。 |
audioChannel | .opusInA2dpOut | 当前对话会话使用的音频传输方式,必须与启动会话的设备事件匹配。 |
allowUserToInterruptAIResponse | true | 是否允许用户说话打断 AI 语音回复。 |
maxPauseDurationBeforeAIResponds | 0.8 秒 | 用户停止说话后,等待 AI 开始回复的最大停顿时长。 |
autoEndSessionAfterNoInputDuration | 15.0 秒 | 持续未检测到输入后,自动结束会话的等待时长。 |
enableVoicePlayback | true | 是否播放 AI 生成的语音回复。 |
shouldSaveVoiceForDebugging | false | 是否保存输入音频用于调试。除非策略明确允许,否则生产环境应保持禁用。 |
additionalOptions | [:] | AI 服务商专用的 Agent、音色、计划、提示词、意图或降噪选项。 |
autoSelectAgentIfNotSpecified | true | 未指定 Agent 时,SDK 是否自动选择。 |
使用公开的 AdditionalOptionKey... 常量,不要硬编码 AI 服务商选项的键名。
配置 AI 对话
Demo 将 AI 服务商选择与会话配置分开。更改服务商时,先完成选择,再查询其支持的语言,并在启动对话前由 App 完成鉴权。Agent 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... 常量。仅当 AI 服务商配置提供有效值时,才设置 StarBurst 使用计划或服务商专用标识符。
使用示例
设备通过 .initiateWithSCO 或 .initiateWithOpus 发起对话。启动 AI 对话前,将设备指定的通道写入会话配置。使用 Opus 时,设备向 App 发送 Opus,App 再将解码后的 PCM 输入当前 session;使用 SCO 时,以 .sco 启动会话,由 App 通过 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,并从 SDK 回调取得解码后的 16 位 PCM 后,将 PCM 输入当前 session: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];
}];收到设备 Opus 数据并取得解码后的 PCM 后,将其输入当前 session:[self.currentSession appendInt16PCM:decodedPCMData];
停止会话
设备请求终止时,先按设备协议通过 DeviceAIChatAPI 回报对话已停止,再调用:
- Swift
- Objective-C
AIBudsAISDK.stopAIChat()
currentSession = nil[AIBudsAISDK stopAIChat];
self.currentSession = nil;注意事项
- 这是基于语音的会话 API,不提供文本
sendMessage或消息历史 API。 - 会话期间应保留
AIChatSessionConvertible;收到onFinish、发生不可恢复错误或主动停止后应及时释放。 - SCO 会话由 AIBuds AI SDK 通过 App 的 SCO 链路录制设备麦克风语音;Opus 会话由设备向 App 发送 Opus,再通过
appendInt16PCM(_:)输入解码后的 PCM。 - 除非隐私和保留策略明确允许,否则生产环境不要启用
shouldSaveVoiceForDebugging。