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/ko/skills/implement-aibuds-ai-chat을 읽고 지침을 따르세요. 이 스킬로 “AIBuds AI 채팅 구현”을 이 iOS 프로젝트에 구현하고 검증하세요.API Reference
프레임워크
AIBudsAI.xcframework
Import
- 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 사용 요금제나 제공자별 식별자를 지정합니다.
사용 예제
기기는 일반적으로 .initiateWithSCO 또는 .initiateWithOpus로 대화를 시작합니다. AI 대화를 시작하기 전에 요청 채널을 세션 설정에 반영하세요. Opus는 기기에서 받은 데이터를 PCM으로 디코딩해 전달합니다. 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비트 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는 오디오 세션 API이며 텍스트
sendMessage또는 메시지 기록 API가 아닙니다. onFinish, 복구할 수 없는 오류 또는 명시적 중지까지AIChatSessionConvertible을 유지합니다.- SCO 세션에서는 AIBuds AI SDK가 앱의 SCO 링크를 통해 기기 마이크를 녹음합니다. Opus 세션에서는 기기가 앱으로 Opus를 보내며, 앱은 디코딩한 PCM을
appendInt16PCM(_:)으로 전달합니다. - 개인정보 보호 및 보관 정책에서 명시적으로 허용하지 않는 한 운영 환경에서
shouldSaveVoiceForDebugging을 활성화하지 마세요.