查看: 321|回复: 3

鸿蒙7 HMAF 2.0 Skill开发实战:从describe到exe

[复制链接]
发表于 昨天 22:00 | 显示全部楼层 |阅读模式
鸿蒙7(HarmonyOS 7)的核心变化是把过去“人找App”的逻辑彻底改为“意图即服务”。华为官方将其定义为“全面构建Agent亲和的系统架构”,具体包括三件事:Agent亲和系统架构(系统能力全面Skill化)、HMAF 2.0(复杂任务成功率超90%,首次开放GUI操控能力,开放20+系统级AI能力)、以及小艺从语音助手进化为系统智慧大脑(接入2100+系统能力、500+精选Skill、2000+鸿蒙智能体,日活1.8亿)。

在这套架构下,用户说“帮我规划周末去杭州的行程”,小艺会自主拆解任务——查天气、看日程、订酒店、规划路线、写入日历——全程跨多个App和系统服务自动完成,而不是简单返回一个搜索链接。

HMAF 2.0架构分为五层:用户意图层(多模态输入,盘古大模型6.0端侧推理)、智能体调度层(图推理引擎自动拆解为子任务DAG并并行调度)、Skill能力层(500+精选Skill,每个Skill声明describe和execute)、系统服务层(分布式软总线、意图框架Intents Kit、Agent Framework Kit、MCP协议)、设备执行层(16台设备协同,延迟低至8ms)。

对于开发者而言,入门鸿蒙Agent生态最快的路径是先做Skill。HMAF 2.0提供了一套标准开发流程:先用自然语言描述Skill能力,框架自动生成骨架代码,开发者只需要填充业务逻辑。整体路径为:描述意图 → 生成Skill骨架 → 填充业务逻辑 → 注册到Agent → 本地调试 → 上架发布。

使用DevEco CLI创建Agent模块并添加Skill非常简单:
  1. # 创建agent模块
  2. deveco create --type module --name agent --template agent
  3. # 添加天气查询Skill
  4. deveco agent add-skill --name weather_query --module agent
复制代码

CLI会在agent/src/main/ets/skills/下生成WeatherQuerySkill.ets骨架文件。

一个Skill的核心就两件事:describe()声明能力,execute()执行逻辑。以下是一个完整的天气查询Skill示例,包含数据结构和HTTP请求封装:
  1. // agent/src/main/ets/skills/WeatherQuerySkill.ets
  2. import { Skill, SkillContext, SkillResult, SkillParameter } from '@kit.AgentKit'
  3. import { http } from '@kit.NetworkKit'
  4. interface WeatherData {
  5.   location: string
  6.   temperature: number
  7.   condition: string
  8.   humidity: number
  9.   forecast: ForecastItem[]
  10. }
  11. interface ForecastItem {
  12.   date: string
  13.   high: number
  14.   low: number
  15.   condition: string
  16. }
  17. class WeatherService {
  18.   private baseUrl: string = 'https://api.example.com/weather'
  19.   async fetchWeather(location: string): Promise<WeatherData> {
  20.     const httpRequest = http.createHttp()
  21.     try {
  22.       const response = await httpRequest.request(
  23.         `${this.baseUrl}?city=${encodeURIComponent(location)}`,
  24.         {
  25.           method: http.RequestMethod.GET,
  26.           header: { 'Content-Type': 'application/json' },
  27.           connectTimeout: 5000,
  28.           readTimeout: 5000
  29.         }
  30.       )
  31.       if (response.responseCode === http.ResponseCode.OK) {
  32.         return JSON.parse(response.result as string) as WeatherData
  33.       }
  34.       throw new Error(`请求失败,状态码: ${response.responseCode}`)
  35.     } finally {
  36.       httpRequest.destroy()
  37.     }
  38.   }
  39. }
  40. export class WeatherQuerySkill extends Skill {
  41.   private weatherService: WeatherService = new WeatherService()
  42.   describe(): SkillParameter {
  43.     return {
  44.       name: 'weather_query',
  45.       description: '查询指定城市的实时天气信息',
  46.       parameters: {
  47.         location: {
  48.           type: 'string',
  49.           description: '城市名称,如"北京""上海"',
  50.           required: true
  51.         },
  52.         date: {
  53.           type: 'string',
  54.           description: '查询日期,默认今天。格式:YYYY-MM-DD',
  55.           required: false
  56.         }
  57.       }
  58.     }
  59.   }
  60.   async execute(context: SkillContext): Promise<SkillResult> {
  61.     const location = context.params.location as string
  62.     if (!location) {
  63.       return SkillResult.error('你还没说要查哪个城市的天气呢')
  64.     }
  65.     try {
  66.       const data = await this.weatherService.fetchWeather(location)
  67.       const today = data.forecast[0]
  68.       return SkillResult.success({
  69.         location: data.location,
  70.         temperature: data.temperature,
  71.         condition: data.condition,
  72.         humidity: data.humidity,
  73.         summary: `${data.location}今天${data.condition},` +
  74.           `气温${today.low}~${today.high}°C,` +
  75.           `湿度${data.humidity}%`
  76.       })
  77.     } catch (e) {
  78.       console.error(`查询 ${location} 天气出错:`, e)
  79.       return SkillResult.error(`查询${location}的天气失败了,稍后再试试`)
  80.     }
  81.   }
  82. }
复制代码

Skill写好后,需要注册到Agent实例中。以下是在SmartLifeAgent中注册WeatherQuerySkill的典型代码:
  1. // agent/src/main/ets/SmartLifeAgent.ets
  2. import { Agent, AgentConfig, AgentRequest, AgentResponse } from '@kit.AgentKit'
  3. import { WeatherQuerySkill } from './skills/WeatherQuerySkill'
  4. export class SmartLifeAgent extends Agent {
  5.   onCreate(config: AgentConfig): void {
  6.     this.registerSkill(new WeatherQuerySkill())
  7.   }
  8. }
复制代码

整个调用链路是:用户说“北京天气怎么样” → 小艺解析意图 → matchSkill()匹配到WeatherQuerySkill → 调用execute() → 返回格式化结果。开发者只需要关心describe()写对参数、execute()写好逻辑,意图匹配、任务拆解、多Skill调度全部由HMAF 2.0框架自动完成。

在应用端,通过Agent Framework Kit集成智能体入口。核心组件是FunctionComponent(UI入口)和FunctionController(控制器)。以下是一个完整的集成示例,包含智能体可用性检查、对话框生命周期监听和降级方案:
  1. // entry/src/main/ets/pages/SmartAssistantPage.ets
  2. import { BusinessError } from '@kit.BasicServicesKit'
  3. import { common } from '@kit.AbilityKit'
  4. import {
  5.   FunctionComponent,
  6.   FunctionController,
  7.   ButtonType
  8. } from '@kit.AgentFrameworkKit'
  9. import { hilog } from '@kit.PerformanceAnalysisKit'
  10. @Entry
  11. @Component
  12. struct SmartAssistantPage {
  13.   @State isAgentReady: boolean = false
  14.   private agentId: string = 'agentproxy_smart_life_2026'
  15.   private controller: FunctionController = new FunctionController()
  16.   async aboutToAppear() {
  17.     try {
  18.       let context = this.getUIContext()?.getHostContext() as common.UIAbilityContext
  19.       this.isAgentReady = await this.controller.isAgentSupport(context, this.agentId)
  20.     } catch (err) {
  21.       hilog.error(0x0001, 'AgentDemo', `智能体检查失败: ${err}`)
  22.     }
  23.     this.controller.on('agentDialogOpened', () => {
  24.       hilog.info(0x0001, 'AgentDemo', '智能体对话框已打开')
  25.     })
  26.     this.controller.on('agentDialogClosed', () => {
  27.       hilog.info(0x0001, 'AgentDemo', '智能体对话框已关闭')
  28.     })
  29.   }
  30.   aboutToDisappear() {
  31.     this.controller.off('agentDialogOpened')
  32.     this.controller.off('agentDialogClosed')
  33.   }
  34.   build() {
  35.     Column({ space: 16 }) {
  36.       if (this.isAgentReady) {
  37.         FunctionComponent({
  38.           agentId: this.agentId,
  39.           onError: (err: BusinessError) => {
  40.             hilog.error(0x0001, 'AgentDemo',
  41.               `拉起智能体失败: ${err.code} - ${err.message}`)
  42.           },
  43.           options: {
  44.             title: 'AI 生活助手',
  45.             queryText: '帮我看看今天有什么安排',
  46.             buttonType: ButtonType.CAPSULE,
  47.             isShowShadow: true,
  48.             titleFontSize: 16,
  49.             iconSize: 20,
  50.             iconColors: ['#00d4ff'],
  51.             titleColors: ['#00d4ff', '#00ff88'],
  52.             backgroundColor: '#0a1628'
  53.           },
  54.           controller: this.controller
  55.         })
  56.       } else {
  57.         Text('AI助手暂不可用,请稍后重试')
  58.           .fontSize(14)
  59.           .fontColor('#999999')
  60.       }
  61.     }
  62.     .width('100%')
  63.     .height('100%')
  64.     .justifyContent(FlexAlign.Center)
  65.     .alignItems(HorizontalAlign.Center)
  66.   }
  67. }
复制代码

鸿蒙智能体的能力扩展有三个路径:端插件(通过Intents Kit桥接,数据不出设备,零网络延迟,响应小于100ms,适合隐私敏感场景)、云插件(HTTP对接后端,超时时间需小于2200ms)、以及MCP协议(跨平台工具连接标准,通过dart_mcp等库支持,实现“一句话调度全屋鸿蒙设备”)。选型原则是:能端侧就不上云,需要外部数据走云插件,跨平台互联走MCP。

在多设备协同场景下,需要通过统一服务能力模型进行动态路由。以下是一个示例模型,根据设备上下文(网络状态、位置权限、电量)自动选择最优目标:
  1. type DeviceType = 'phone' | 'tablet' | 'pc' | 'watch' | 'car'
  2. interface ServiceCapability {
  3.   id: string
  4.   name: string
  5.   scene: string
  6.   requiredPermissions: string[]
  7.   supportedDevices: DeviceType[]
  8.   riskLevel: 'low' | 'medium' | 'high'
  9.   fallback: string
  10. }
  11. const routePlanning: ServiceCapability = {
  12.   id: 'travel.route.plan',
  13.   name: '路线规划',
  14.   scene: '出行',
  15.   requiredPermissions: ['location'],
  16.   supportedDevices: ['phone', 'tablet', 'car'],
  17.   riskLevel: 'medium',
  18.   fallback: '展示手动输入地址页面'
  19. }
  20. interface DeviceContext {
  21.   device: DeviceType
  22.   networkAvailable: boolean
  23.   locationGranted: boolean
  24.   batteryLow: boolean
  25. }
  26. function selectRouteTarget(ctx: DeviceContext): string {
  27.   if (!ctx.networkAvailable) return 'offlineFallback'
  28.   if (ctx.device === 'car' && ctx.locationGranted) return 'carNavigation'
  29.   if (ctx.device === 'watch') return 'briefReminder'
  30.   return 'phoneRoutePage'
  31. }
复制代码

这套模型让同一业务规则在不同设备上自动适配:手机做身份认证和输入,平板做阅读编辑,手表做提醒,车机做导航——用户感知到的是任务连续而非设备切换。

对于想要入局的开发者,建议首先从Skill做起,因为鸿蒙7的入口不再只是App图标,Skill可以通过负一屏、语音、搜索、卡片等多渠道触达用户。当前500+精选Skill仍有竞争窗口,天工计划对单个智能体最高提供75万元激励。同时坚持端侧优先——盘古大模型6.0端侧运行加上端插件数据不出设备,是鸿蒙区别于其他平台的核心差异。此外,关注MCP生态,鸿蒙+MCP的组合意味着你的App可以同时被小艺和任何支持MCP的AI平台调用。降级设计也不能省:定位失败允许手动输入,车机不可用则手机继续导航,Agent理解失败则展示候选意图。

总体来看,鸿蒙7不是一个普通的版本升级,而是从“App的容器”到“意图的执行者”的范式转变。HMAF 2.0框架已经成熟,Skill开发门槛显著降低,Agent Framework Kit让接入极简,加上天工计划的真金白银激励,现在是进入鸿蒙Agent生态的有利时机。
回复

使用道具 举报

发表于 昨天 22:05 | 显示全部楼层

Re: 鸿蒙7 HMAF 2.0 Skill开发实战:从describe到exe

感谢分享,非常详细!对鸿蒙7的“意图即服务”理念很感兴趣,特别是Skill开发的describe和execute这种简洁模式。请问在实际应用中,多个Skill之间如何协作完成复杂任务?比如天气查询后结合日历和酒店Skill自动规划行程?另外,HMAF 2.0开放的GUI操控能力具体是指什么场景?期待后续更多实战内容。
回复 支持 反对

使用道具 举报

发表于 昨天 22:05 | 显示全部楼层

Re: 鸿蒙7 HMAF 2.0 Skill开发实战:从describe到exe

这个帖子干货满满,特别是从“意图即服务”到具体Skill开发流程的拆解,把鸿蒙7的Agent生态讲得很透。天气查询Skill的示例也很实用,`describe()`和`execute()`的结构一目了然,对于想快速上手HMAF 2.0的开发者来说,直接照着写就能跑通一个基础Skill。期待后续能分享更多实际调试中遇到的坑或者性能优化经验!
回复 支持 反对

使用道具 举报

发表于 昨天 22:05 | 显示全部楼层

Re: 鸿蒙7 HMAF 2.0 Skill开发实战:从describe到exe

感谢楼主的详细分享!鸿蒙7的“意图即服务”思路确实很吸引人,把用户从繁琐的操作中解放出来。HMAF 2.0的五层架构和Skill开发流程写得非常清楚,尤其是从 `describe` 到 `execute` 的核心模式,降低了Agent开发的入门门槛。 示例代码里 `WeatherQuerySkill` 的结构很典型,但我注意到API地址是示例的 `api.example.com`——在实际发布时,替换成真实天气服务接口后,还需要处理API授权或数据缓存吗?另外,`SkillParameter` 里 `parameters` 的声明方式,是否支持枚举或更复杂的校验规则?期待楼主后续深入讲讲调试和上架的经验。感谢!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

指导单位

江苏省公安厅

江苏省通信管理局

浙江省台州刑侦支队

DEFCON GROUP 86025

Hacking Group 021A

旗下站点

态势感知中心

应急响应中心

红盟安全

联系我们

官方QQ群:112851260

官方邮箱:security#ihonker.org(#改成@)

官方核心成员

关注微信公众号

Archiver|手机版|小黑屋| ( 沪ICP备2021026908号 )

GMT+8, 2026-7-31 05:42 , Processed in 0.025237 second(s), 17 queries , Gzip On, Redis On.

Powered by ihonker.com

Copyright © 2015-现在.

  • 返回顶部