鸿蒙智能体框架(HMAF)开发指南:如何快速接入 AI 交互能力

随着鸿蒙生态对 AI 能力的深度整合,鸿蒙智能体框架(HMAF, HarmonyOS Agent Framework)成为开发者快速构建智能交互应用的核心工具。HMAF 提供了自然语言理解、任务规划、服务调用等一站式能力,让开发者无需从零搭建 AI 模型,就能实现“语音/文字交互 + 业务服务联动”的智能应用。本文将拆解 HMAF 的核心开发流程,以“简易购物助手”为例,手把手讲解自然语言交互与服务调用的实现,帮你快速上手 HMAF 开发。

一、核心认知:HMAF 是什么?能解决什么问题?

1. HMAF 核心定位

HMAF 是鸿蒙系统推出的智能体开发框架,核心目标是降低 AI 交互应用的开发门槛。它封装了大语言模型(LLM)的能力,提供标准化的 API 接口,让开发者只需关注业务逻辑,就能实现“用户自然语言输入 → 智能体理解意图 → 调用对应服务 → 反馈结果”的完整流程。

2. 核心优势与适用场景

  • 优势:无需关注 LLM 训练、自然语言理解(NLU)等底层技术,直接复用鸿蒙生态的 AI 能力;支持多模态交互(文字、语音),适配手机、平板、智慧屏等多设备;
  • 适用场景:智能助手(购物、办公)、设备控制、信息查询等需要自然语言交互的场景。

3. 核心组件拆解

HMAF 的开发依赖以下 3 个核心组件,无需额外集成第三方库:

  • 交互引擎:处理用户输入(文字/语音转文本),解析用户意图(如“查询商品”“添加购物车”);
  • 任务规划器:根据用户意图拆解为可执行的任务(如“查询商品”拆解为“调用商品搜索服务 + 返回结果”);
  • 服务调用器:标准化调用鸿蒙生态的服务(如购物服务、支付服务)或自定义业务服务。

二、开发准备:环境搭建与权限配置

1. 开发环境要求

  • 开发工具:DevEco Studio 5.0+(需安装 HarmonyOS 4.0+ SDK,HMAF 需依赖 API 10 及以上版本);
  • 测试设备:鸿蒙 4.0+ 手机/模拟器(需开启“AI 能力”权限,部分功能需登录华为账号);
  • 依赖配置:在项目的 build.gradle 中添加 HMAF 依赖(自动同步鸿蒙 SDK 时会默认引入):
    dependencies {
        implementation 'ohos:hmaf-core:1.0.0.0'
        implementation 'ohos:hmaf-interaction:1.0.0.0'
    }
    

2. 核心权限配置

module.json5 中添加 AI 交互与服务调用相关权限:

{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.ACCESS_AI_ENGINE", // 访问 AI 引擎
        "reason": "用于解析用户自然语言意图",
        "usedScene": { "when": "always" }
      },
      {
        "name": "ohos.permission.MICROPHONE", // 麦克风权限(语音交互用)
        "reason": "用于接收用户语音输入",
        "usedScene": { "when": "user_grant" }
      },
      {
        "name": "ohos.permission.INTERNET", // 网络权限(调用远程服务用)
        "reason": "用于调用商品搜索服务",
        "usedScene": { "when": "always" }
      }
    ]
  }
}

三、开发流程拆解:简易购物助手实现

以“简易购物助手”为例,实现核心功能:用户通过文字/语音输入需求(如“搜索华为手机”“添加商品到购物车”),智能体解析意图后调用对应服务,反馈处理结果。

1. 第一步:初始化 HMAF 智能体

在应用启动时初始化 HMAF 核心实例,配置交互模式(文字/语音)和服务列表:

import hmaf from '@ohos.hmaf.core';
import interactionEngine from '@ohos.hmaf.interaction';

@Entry
@Component
struct ShoppingAssistantPage {
  // 状态变量:用户输入文本、智能体反馈结果
  @State userInput: string = '';
  @State agentReply: string = '请输入需求(如"搜索华为手机")';
  // HMAF 智能体实例
  private agentInstance: hmaf.Agent | null = null;

  // 页面加载时初始化智能体
  aboutToAppear() {
    this.initHMAFAgent();
  }

  // 初始化 HMAF 智能体
  initHMAFAgent() {
    // 1. 配置智能体基础信息
    const agentConfig: hmaf.AgentConfig = {
      agentName: '简易购物助手',
      interactionMode: [interactionEngine.InteractionMode.TEXT, interactionEngine.InteractionMode.VOICE], // 支持文字+语音
      supportedServices: ['ProductSearchService', 'CartService'] // 支持的服务:商品搜索、购物车
    };

    // 2. 创建智能体实例
    hmaf.createAgent(agentConfig, (err, agent) => {
      if (err) {
        console.error('HMAF 智能体初始化失败:', err.message);
        this.agentReply = '智能体初始化失败,请重试';
        return;
      }
      this.agentInstance = agent;
      // 3. 监听智能体的反馈结果
      this.agentInstance.on('reply', (reply) => {
        this.agentReply = reply.content;
      });
      // 4. 监听服务调用结果
      this.agentInstance.on('serviceResult', (result) => {
        if (result.success) {
          this.agentReply = `操作成功:${JSON.stringify(result.data)}`;
        } else {
          this.agentReply = `操作失败:${result.errorMsg}`;
        }
      });
    });
  }

  // 后续实现交互与服务调用逻辑...
}

2. 第二步:实现自然语言交互(文字/语音)

添加 UI 交互组件,支持用户输入文字或语音,将输入传递给 HMAF 智能体解析意图:

// 继续在 ShoppingAssistantPage 中添加以下代码
// 处理文字输入提交
submitTextInput() {
  if (!this.agentInstance || this.userInput.trim() === '') return;
  // 将用户文字输入传递给智能体
  this.agentInstance.sendInput({
    type: interactionEngine.InputType.TEXT,
    content: this.userInput.trim()
  });
  // 清空输入框
  this.userInput = '';
}

// 处理语音输入(启动麦克风录音)
async startVoiceInput() {
  if (!this.agentInstance) return;
  try {
    // 调用 HMAF 语音交互 API,获取语音转文字结果
    const voiceResult = await interactionEngine.startVoiceRecognition({
      language: 'zh-CN',
      timeout: 10000 // 录音超时时间:10秒
    });
    if (voiceResult.success) {
      this.userInput = voiceResult.text;
      // 自动提交语音转文字后的内容
      this.submitTextInput();
    } else {
      this.agentReply = '语音识别失败,请重试';
    }
  } catch (err) {
    console.error('语音输入失败:', err);
    this.agentReply = '语音输入异常,请检查麦克风权限';
  }
}

// 构建 UI 交互界面
build() {
  Column() {
    // 智能体反馈区域
    Text(this.agentReply)
      .fontSize(18)
      .width('90%')
      .minHeight(100)
      .padding(10)
      .backgroundColor('#f5f5f5')
      .borderRadius(8)
      .margin(10);

    // 文字输入区域
    Row({ space: 10 }) {
      TextInput({ placeholder: '请输入需求...', text: this.userInput })
        .width('70%')
        .height(50)
        .padding(10)
        .borderRadius(25)
        .backgroundColor('#eee');
      Button('发送')
        .width('20%')
        .height(50)
        .borderRadius(25)
        .backgroundColor('#007dff')
        .onClick(() => this.submitTextInput());
    }
    .width('90%')
    .margin(10);

    // 语音输入按钮
    Button('按住说话')
      .width('90%')
      .height(50)
      .borderRadius(25)
      .backgroundColor('#00c88c')
      .onClick(() => this.startVoiceInput())
      .margin(10);
  }
  .width('100%')
  .height('100%')
  .justifyContent(FlexAlign.Center);
}

3. 第三步:实现服务调用(商品搜索 + 购物车)

HMAF 智能体解析用户意图后,会触发对应的服务调用。我们需要实现 ProductSearchService(商品搜索服务)和 CartService(购物车服务),并注册到 HMAF 框架中。

(1)定义服务接口

创建 services 目录,定义服务的标准化接口(遵循 HMAF 服务规范):

// services/ProductSearchService.ts
import hmaf from '@ohos.hmaf.core';

// 商品搜索服务实现
export class ProductSearchService implements hmaf.Service {
  // 服务 ID(需与初始化时的 supportedServices 一致)
  serviceId: string = 'ProductSearchService';

  // 服务执行方法(HMAF 会自动调用)
  async execute(params: any): Promise<hmaf.ServiceResult> {
    try {
      const keyword = params.keyword; // 从参数中获取用户搜索关键词
      // 模拟调用商品搜索接口(实际开发中替换为真实接口)
      const mockProducts = [
        { id: 1, name: '华为 Mate 60 Pro', price: 6999, stock: 100 },
        { id: 2, name: '华为 Pura 70', price: 4999, stock: 80 }
      ];
      const result = mockProducts.filter(p => p.name.includes(keyword));
      return {
        success: true,
        data: result,
        message: `找到 ${result.length} 件相关商品`
      };
    } catch (err) {
      return {
        success: false,
        errorMsg: '商品搜索失败',
        data: null
      };
    }
  }
}

// services/CartService.ts
import hmaf from '@ohos.hmaf.core';

// 购物车服务实现
export class CartService implements hmaf.Service {
  serviceId: string = 'CartService';
  // 模拟购物车数据
  private cartData: Array<{ id: number; name: string; price: number; count: number }> = [];

  async execute(params: any): Promise<hmaf.ServiceResult> {
    try {
      const { action, productId, count = 1 } = params;
      switch (action) {
        case 'add': // 添加商品到购物车
          const mockProduct = { id: productId, name: productId === 1 ? '华为 Mate 60 Pro' : '华为 Pura 70', price: productId === 1 ? 6999 : 4999 };
          const existingItem = this.cartData.find(item => item.id === productId);
          if (existingItem) {
            existingItem.count += count;
          } else {
            this.cartData.push({ ...mockProduct, count });
          }
          return { success: true, data: this.cartData, message: '商品已添加到购物车' };
        case 'query': // 查询购物车
          return { success: true, data: this.cartData, message: `购物车共有 ${this.cartData.length} 件商品` };
        default:
          return { success: false, errorMsg: '不支持的操作' };
      }
    } catch (err) {
      return { success: false, errorMsg: '购物车操作失败', data: null };
    }
  }
}
(2)注册服务到 HMAF 智能体

在智能体初始化后,将自定义服务注册到实例中:

// 在 initHMAFAgent 方法中添加服务注册逻辑
import { ProductSearchService } from './services/ProductSearchService';
import { CartService } from './services/CartService';

initHMAFAgent() {
  // ... 前面的智能体创建逻辑 ...
  this.agentInstance = agent;
  // 注册自定义服务
  this.agentInstance.registerService(new ProductSearchService());
  this.agentInstance.registerService(new CartService());
  // ... 后面的监听逻辑 ...
}

4. 第四步:测试验证

启动应用,进行以下测试场景验证:

  1. 文字输入“搜索华为手机”:智能体解析意图为“商品搜索”,调用 ProductSearchService,反馈找到的商品列表;
  2. 文字输入“把华为 Mate 60 Pro 添加到购物车”:解析意图为“添加购物车”,调用 CartServiceadd 操作,反馈添加成功;
  3. 语音输入“查询我的购物车”:语音转文字后解析意图为“查询购物车”,调用 CartServicequery 操作,反馈购物车商品。

四、核心优化:提升智能体交互体验

1. 意图解析优化

  • 问题:用户输入模糊时(如“买手机”),智能体可能无法准确解析;
  • 解决方案:通过 HMAF 的 IntentConfig 配置自定义意图映射,补充常见模糊输入的解析规则:
    const intentConfig: hmaf.IntentConfig = {
      customIntents: [
        {
          intentName: 'ProductSearch',
          patterns: ['买{keyword}', '选购{keyword}', '找{keyword}'] // 补充模糊输入模式
        }
      ]
    };
    // 初始化智能体时传入意图配置
    hmaf.createAgent({ ...agentConfig, intentConfig }, (err, agent) => { ... });
    

2. 交互反馈优化

  • 问题:服务调用耗时较长时,用户无等待反馈;
  • 解决方案:添加加载状态提示,在服务调用前显示“处理中…”,调用完成后更新为结果:
    // 新增状态变量
    @State isLoading: boolean = false;
    
    // 提交输入时设置加载状态
    submitTextInput() {
      if (!this.agentInstance || this.userInput.trim() === '') return;
      this.isLoading = true;
      this.agentInstance.sendInput({ ... });
      // 监听服务调用开始
      this.agentInstance.on('serviceStart', () => {
        this.agentReply = '处理中...';
      });
      // 服务调用结束后关闭加载状态
      this.agentInstance.on('serviceResult', (result) => {
        this.isLoading = false;
        // ... 其他处理 ...
      });
    }
    

3. 多设备协同优化

HMAF 支持多设备协同,可将购物助手扩展到平板、智慧屏:

  • 在多设备上登录同一华为账号;
  • 启用 HMAF 的分布式能力,实现“手机输入需求,平板显示商品列表”的跨设备交互。

五、常见问题与解决方案

  1. 智能体初始化失败:“AI 引擎未就绪”

    • 原因:设备未开启 AI 能力,或鸿蒙系统版本过低;
    • 解决方案:升级设备到鸿蒙 4.0+,在“设置 → 智慧助手 → AI 实验室”中开启 AI 能力。
  2. 语音识别无响应

    • 原因:未获取麦克风权限,或设备麦克风故障;
    • 解决方案:检查并申请麦克风权限,测试设备麦克风是否正常。
  3. 服务调用无反馈

    • 原因:服务 ID 与初始化时的 supportedServices 不一致,或服务未正确注册;
    • 解决方案:核对服务 ID 的一致性,确保 registerService 调用在智能体创建后执行。

六、总结

HMAF 框架让鸿蒙开发者无需深入 AI 底层技术,就能快速实现智能交互应用。其核心开发流程可概括为“初始化智能体 → 实现交互输入 → 开发注册服务 → 测试优化”。本文的简易购物助手案例,覆盖了 HMAF 的核心能力,开发者可在此基础上扩展更多服务(如订单查询、支付),或适配多模态交互(图像识别商品)。

随着鸿蒙生态的完善,HMAF 还将支持更多 AI 能力(如多轮对话、个性化推荐),为智能应用开发提供更便捷的工具链。掌握 HMAF 的开发逻辑,能让你在鸿蒙 AI 生态中快速抢占先机。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐