HarmonyOS APP美寇商城如何实现自然语音商品检索
摘要: 美寇商城通过自然语音处理(NLP)技术实现语音搜索功能,用户可使用口语化表达(如“找一双透气男士跑鞋,预算500元”)进行商品检索。系统架构分为三层:前端交互层(语音/文本输入)、鸿蒙应用层(核心NLP意图解析与商品检索)、后端服务层(数据查询与结果返回)。鸿蒙的Intents Kit负责识别用户意图(动作、分类、属性等),并转换为结构化查询条件。代码示例展示了意图分析的实现,包括降级处理
一、 概述:自然语言检索的价值
传统的关键词搜索要求用户提炼精确词汇(如“男士运动鞋 43码”),而自然语音检索允许用户使用更口语化、更复杂的句子(如“帮我找一双适合夏天跑步穿的、透气一点的男士跑鞋,预算500元左右”)进行查询。这极大地提升了“美寇商城”的搜索体验和购物效率。其核心是将用户的自然语音查询,通过 自然语音处理(NLP) 技术,转化为系统可理解的结构化搜索指令。
二、 系统架构设计
下图清晰地展示了美寇商城实现自然语音检索的核心流程与架构:
整个流程可分为三个层次:
- 前端交互层:提供语音或文本输入界面。
- 鸿蒙应用层(核心处理层):
- 意图识别 (Intent Recognition):使用鸿蒙的
Intents Kit解析用户查询,识别核心意图(action,如“购买”、“查找”、“比较”)、商品类别(category,如“跑鞋”)、属性(attributes,如“透气”、“夏季”、“500元”)和实体(entities,如“男士”、“43码”)。 - 商品检索与排序:将识别出的结构化信息,转换为对商品数据库的查询条件(如分类、标签、价格区间),并调用后端接口获取结果。
- 意图识别 (Intent Recognition):使用鸿蒙的
- 后端服务层:处理复杂的商品搜索、过滤和排序逻辑,将结果返回给应用。
三、 核心代码实现示例
以下代码示例展示了在美寇商城鸿蒙应用中,如何集成 Intents Kit 来处理一次自然语音查询。
1. 配置与权限 (module.json5)
首先需要在应用的配置文件中声明对 Intents Kit 的依赖。
{
"module": {
"name": "entry",
"requestPermissions": [
{
"name": "ohos.permission.INTERNET" // 如果需要调用云端服务
}
],
"dependencies": [
{
"bundleName": "ohos.intents",
"moduleName": "intents",
"versionCode": 1
}
]
}
}
2. 封装自然语音检索服务 (NlpSearchService.ets)
这是一个核心服务类,负责调用鸿蒙的 NLP 能力。
// src/main/ets/services/NlpSearchService.ets
import { hilog } from '@kit.PerformanceAnalysisKit';
import { Intent, IntentConstant, IntentHelper } from '@kit.IntentsKit';
import { BusinessError } from '@kit.BasicServicesKit';
export class NlpSearchService {
private TAG: string = 'NlpSearchService';
/**
* 分析用户输入的自然语音,解析为购物意图
* @param query 用户输入的查询文本
* @returns 解析后的结构化意图对象
*/
async analyzeShoppingIntent(query: string): Promise<ShoppingIntent> {
hilog.info(0x0000, this.TAG, '开始分析查询: %{public}s', query);
// 1. 创建意图对象,设置待分析的文本
let intent: Intent = {
action: IntentConstant.ACTION_ANALYZE,
parameters: {
'text': query, // 待分析的文本
'domain': 'Shopping', // 指定领域为购物
'features': ['CATEGORY', 'ATTRIBUTE', 'ENTITY', 'INTENT'] // 希望识别的特征
}
};
try {
// 2. 调用鸿蒙 Intents Kit 的助手接口进行意图分析
let analyzedIntent: Intent = await IntentHelper.startAbility(intent);
hilog.info(0x0000, this.TAG, '意图分析原始结果: %{public}s', JSON.stringify(analyzedIntent));
// 3. 将通用意图结果,转换为我们自定义的“购物意图”结构
return this.parseToShoppingIntent(analyzedIntent);
} catch (error) {
const err: BusinessError = error as BusinessError;
hilog.error(0x0000, this.TAG, '意图分析失败,错误码: %{public}d, 信息: %{public}s', err.code, err.message);
// 降级方案:返回一个包含原始查询的简单意图,或触发关键词回退搜索
return this.getFallbackIntent(query);
}
}
/**
* 将鸿蒙API返回的通用Intent,解析为美寇商城定义的购物意图
* @param intent 鸿蒙Intents Kit返回的意图对象
* @private
*/
private parseToShoppingIntent(intent: Intent): ShoppingIntent {
let shoppingIntent: ShoppingIntent = {
rawQuery: '',
action: 'SEARCH', // 默认动作是搜索
categories: [],
attributes: {},
entities: [],
confidence: 0.8 // 置信度
};
const params = intent.parameters;
if (!params) {
return shoppingIntent;
}
// 提取分类(例如:从结果中解析出“跑鞋”、“服装”)
if (params['CATEGORY']) {
shoppingIntent.categories = this.parseArrayParam(params['CATEGORY']);
}
// 提取属性(例如:“透气” -> {material: “透气”}, “500元” -> {maxPrice: 500})
if (params['ATTRIBUTE']) {
shoppingIntent.attributes = this.parseAttributes(params['ATTRIBUTE']);
}
// 提取实体(例如:“男士”、“夏季”)
if (params['ENTITY']) {
shoppingIntent.entities = this.parseArrayParam(params['ENTITY']);
}
// 识别核心动作:是“购买”、“查找”还是“比较”?
if (params['INTENT']) {
const actionStr: string = this.parseAction(params['INTENT']);
shoppingIntent.action = actionStr;
}
hilog.info(0x0000, this.TAG, '解析后的购物意图: %{public}s', JSON.stringify(shoppingIntent));
return shoppingIntent;
}
private parseArrayParam(param: Object): Array<string> {
// 实现将参数转换为字符串数组的逻辑
// 例如,如果param是字符串,则返回[param];如果是数组,则直接返回
return [];
}
private parseAttributes(attributeParam: Object): Record<string, string | number> {
// 实现复杂的属性解析逻辑
// 例如,将“500元”解析为 {maxPrice: 500},将“红色”解析为 {color: “red”}
let attrs: Record<string, string | number> = {};
// ... 具体解析代码
return attrs;
}
private parseAction(intentParam: Object): string {
// 根据云端或本地模型返回的意图标签,映射到美寇商城的动作枚举
// 例如,映射 “BUY” -> ‘PURCHASE’, “FIND” -> ‘SEARCH’
return 'SEARCH';
}
private getFallbackIntent(query: string): ShoppingIntent {
// 当NLP服务不可用时,提供降级方案,例如将整个查询作为关键词
hilog.warn(0x0000, this.TAG, '使用降级意图,原始查询将作为关键词: %{public}s', query);
return {
rawQuery: query,
action: 'SEARCH',
categories: [],
attributes: {},
entities: [query], // 将整个查询放入实体,后续可做关键词匹配
confidence: 0.3
};
}
}
// 美寇商城自定义的购物意图结构
export interface ShoppingIntent {
rawQuery: string; // 原始查询语句
action: string; // 动作:SEARCH, COMPARE, ADD_TO_CART 等
categories: Array<string>; // 商品分类
attributes: Record<string, string | number>; // 商品属性(颜色、价格区间、材质等)
entities: Array<string>; // 识别出的实体(品牌、性别、季节等)
confidence: number; // 识别置信度
}
3. 在搜索页面中使用 (NaturalLanguageSearchPage.ets)
在UI页面中集成上述服务,完成从输入到展示的完整链路。
// src/main/ets/pages/NaturalLanguageSearchPage.ets
import { ShoppingIntent, NlpSearchService } from '../services/NlpSearchService';
import { SearchResult, ProductService } from '../services/ProductService'; // 假设的商品服务
import { hilog } from '@kit.PerformanceAnalysisKit';
@Entry
@Component
struct NaturalLanguageSearchPage {
@State userInput: string = '';
@State isProcessing: boolean = false;
@State searchResults: Array<SearchResult> = [];
@State currentIntent?: ShoppingIntent;
private nlpService: NlpSearchService = new NlpSearchService();
private productService: ProductService = new ProductService();
build() {
Column({ space: 20 }) {
// 1. 搜索输入框
TextInput({ placeholder: '请输入您想找的商品,比如“夏天穿的男士透气跑鞋”', text: this.userInput })
.onChange((value: string) => {
this.userInput = value;
})
.width('90%')
.height(40)
.padding(10)
.border({ width: 1, color: '#ccc' })
// 2. 搜索按钮
Button('智能搜索')
.onClick(() => {
this.handleNaturalLanguageSearch();
})
.width('50%')
.enabled(!this.isProcessing && this.userInput.trim().length > 0)
// 3. 处理状态提示
if (this.isProcessing) {
LoadingProgress()
.width(30)
.height(30)
Text('正在理解您的需求...')
.fontSize(14)
.fontColor('#888')
}
// 4. 展示解析出的意图(用于解释系统理解了用户什么)
if (this.currentIntent && !this.isProcessing) {
Text(`已理解:您想查找 ${this.currentIntent.categories.join(',') || '商品'}, 要求:${JSON.stringify(this.currentIntent.attributes)}`)
.fontSize(12)
.fontColor('#666')
.width('90%')
.multilineTextAlignment(TextAlign.Start)
}
// 5. 展示搜索结果列表
List({ space: 10 }) {
ForEach(this.searchResults, (item: SearchResult) => {
ListItem() {
ProductItemView({ product: item }) // 自定义的商品展示组件
}
})
}
.width('100%')
.layoutWeight(1) // 占据剩余空间
.visibility(this.searchResults.length > 0 ? Visibility.Visible : Visibility.None)
}
.width('100%')
.height('100%')
.padding(20)
.alignItems(HorizontalAlign.Center)
}
/**
* 处理自然语言搜索的核心逻辑
*/
private async handleNaturalLanguageSearch(): Promise<void> {
// 清空上一次的结果
this.searchResults = [];
this.isProcessing = true;
hilog.info(0x0000, 'SearchPage', '开始自然语言搜索,查询: %{public}s', this.userInput);
try {
// 步骤1: 调用NLP服务解析用户意图
this.currentIntent = await this.nlpService.analyzeShoppingIntent(this.userInput);
// 步骤2: 根据解析出的结构化意图,调用商品搜索服务
if (this.currentIntent.confidence > 0.5) { // 设置置信度阈值
const results = await this.productService.searchByIntent(this.currentIntent);
this.searchResults = results;
} else {
// 置信度太低,可以降级为关键词搜索,或提示用户重新输入
hilog.warn(0x0000, 'SearchPage', '意图识别置信度过低,执行降级关键词搜索');
this.searchResults = await this.productService.fallbackKeywordSearch(this.userInput);
}
} catch (error) {
hilog.error(0x0000, 'SearchPage', '搜索过程发生异常: %{public}s', JSON.stringify(error));
// 这里可以给用户一个友好的错误提示
} finally {
this.isProcessing = false;
}
}
}
四、 优化与进阶
-
性能优化:
- 本地轻量模型:对于高频、简单的查询(如“手机”、“红酒”),优先使用设备本地的轻量NLP模型,实现瞬时响应。
- 云端协同:对于复杂、低频的查询,调用云端更强大的NLP服务,并将结果缓存。
- 结果预加载:在用户输入过程中进行实时联想,并对最可能的意图对应的商品进行预加载。
-
体验优化:
- 多轮交互:当用户查询意图模糊时(如“我想送个礼物”),系统可以主动询问澄清问题(“送给什么人?预算是多少?”)。
- 结合用户画像:将用户的历史行为、偏好融入检索排序,实现个性化结果。
- 语音输入集成:与鸿蒙的
Audio Kit或Speech Kit结合,实现端侧或云端的语音识别,无缝衔接自然语音处理流程。
五、 总结
为美寇商城实现自然语言商品检索,核心在于利用鸿蒙OS的 Intents Kit 等AI能力,将用户的口语化查询精准地转化为结构化的商品查询指令。这需要前端交互、本地/云端NLP处理、以及后端商品搜索的紧密协同。通过上述架构和代码示例,你可以构建一个体验流畅、理解精准的智能搜索功能,从而显著提升商城应用的竞争力。
更多推荐

所有评论(0)