AI 问答(TSAIQuestionAnswerInterface)
AI 问答提供厂商无关的单次文本输入、流式文本输出能力,独立于 AI 助手的文本总结和多轮语音对话。
前提条件
TSAIContext *context = [TSAIKit sharedInstance].activeContext;
if (![context supportsAIFeatures:TSAIFeatureQuestionAnswering]) {
return;
}
id<TSAIQuestionAnswerInterface> questionAnswer = context.questionAnswer;
数据模型
| 模型 | 属性 | 说明 |
|---|---|---|
TSAIQuestionAnswerConfig | agentId、audioRouteConfiguration | 可选 AI Agent;设备语音问答使用的音频路由 |
TSAIQuestionAnswerPartialResult | taskId、questionId | 任务和服务端问题标识 |
TSAIQuestionAnswerPartialResult | deltaText、fullText、isFinal | 增量、累积文本和最终标志 |
TSAIQuestionAnswerResult | taskId、questionId、answerText | 最终答案 |
使用 [TSAIQuestionAnswerConfig defaultConfig] 创建默认配置。
回调类型
| 回调 | 线程与语义 |
|---|---|
TSAIQuestionAnswerStartBlock | 服务开始回答时在主线程调用 |
TSAIQuestionAnswerPartialBlock | 累积答案更新,在主线程调用零次或多次 |
TSAIQuestionAnswerCompletionBlock | 成功、失败或取消时在主线程调用一次 |
发起问答
- (NSString *)askQuestion:(NSString *)question
config:(TSAIQuestionAnswerConfig *)config
onStartAnswering:(nullable TSAIQuestionAnswerStartBlock)onStartAnswering
onPartialResult:(nullable TSAIQuestionAnswerPartialBlock)onPartialResult
completion:(nullable TSAIQuestionAnswerCompletionBlock)completion;
TSAIQuestionAnswerConfig *config = [TSAIQuestionAnswerConfig defaultConfig];
config.agentId = @"health-assistant";
NSString *taskId = [questionAnswer askQuestion:@"如何改善睡眠质量?"
config:config
onStartAnswering:^(NSString *taskId, NSString *questionId) {
TSLog(@"AI 开始回答: %@", questionId);
}
onPartialResult:^(TSAIQuestionAnswerPartialResult *partial) {
TSLog(@"回答中: %@", partial.fullText);
}
completion:^(TSAIQuestionAnswerResult *result, NSError *error) {
if (error) {
TSLog(@"问答失败: %@", error.localizedDescription);
return;
}
TSLog(@"最终回答: %@", result.answerText);
}];
取消问答
- (void)cancelQuestionAnswerWithTaskId:(NSString *)taskId;
当前 AIBuds 服务没有服务端物理取消 API。取消是本地逻辑取消:原 completion 会收到取消错误,后续迟到回调会被丢弃,但服务端任务可能仍在继续。
[questionAnswer cancelQuestionAnswerWithTaskId:taskId];
设备主动问答
- (NSString *)startDeviceQuestionAnswerWithConfig:(TSAIQuestionAnswerConfig *)config
completion:(nullable TSAICompletionBlock)completion;
- (void)stopDeviceQuestionAnswerWithTaskId:(NSString *)taskId;
该入口配置并等待一次设备语音问答会话,返回稳定 taskId。audioRouteConfiguration 只由这个设备语音入口消费;纯文本 askQuestion:config: 不会激活音频路由。完整编排与输出对象见设备主动 AI 场景。
注意事项
- 问题文本不能为空。
completion是任务终态的权威信号。deltaText适合追加处理,fullText适合直接刷新 UI。- 页面退出时取消未完成任务,并忽略与当前 taskId 不匹配的 UI 更新。