鸿蒙专家 发表于 2026-7-30 22:00:00

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

鸿蒙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非常简单:

# 创建agent模块
deveco create --type module --name agent --template agent
# 添加天气查询Skill
deveco agent add-skill --name weather_query --module agent


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

一个Skill的核心就两件事:describe()声明能力,execute()执行逻辑。以下是一个完整的天气查询Skill示例,包含数据结构和HTTP请求封装:

// agent/src/main/ets/skills/WeatherQuerySkill.ets
import { Skill, SkillContext, SkillResult, SkillParameter } from '@kit.AgentKit'
import { http } from '@kit.NetworkKit'

interface WeatherData {
location: string
temperature: number
condition: string
humidity: number
forecast: ForecastItem[]
}

interface ForecastItem {
date: string
high: number
low: number
condition: string
}

class WeatherService {
private baseUrl: string = 'https://api.example.com/weather'
async fetchWeather(location: string): Promise<WeatherData> {
    const httpRequest = http.createHttp()
    try {
      const response = await httpRequest.request(
      `${this.baseUrl}?city=${encodeURIComponent(location)}`,
      {
          method: http.RequestMethod.GET,
          header: { 'Content-Type': 'application/json' },
          connectTimeout: 5000,
          readTimeout: 5000
      }
      )
      if (response.responseCode === http.ResponseCode.OK) {
      return JSON.parse(response.result as string) as WeatherData
      }
      throw new Error(`请求失败,状态码: ${response.responseCode}`)
    } finally {
      httpRequest.destroy()
    }
}
}

export class WeatherQuerySkill extends Skill {
private weatherService: WeatherService = new WeatherService()

describe(): SkillParameter {
    return {
      name: 'weather_query',
      description: '查询指定城市的实时天气信息',
      parameters: {
      location: {
          type: 'string',
          description: '城市名称,如"北京""上海"',
          required: true
      },
      date: {
          type: 'string',
          description: '查询日期,默认今天。格式:YYYY-MM-DD',
          required: false
      }
      }
    }
}

async execute(context: SkillContext): Promise<SkillResult> {
    const location = context.params.location as string
    if (!location) {
      return SkillResult.error('你还没说要查哪个城市的天气呢')
    }
    try {
      const data = await this.weatherService.fetchWeather(location)
      const today = data.forecast
      return SkillResult.success({
      location: data.location,
      temperature: data.temperature,
      condition: data.condition,
      humidity: data.humidity,
      summary: `${data.location}今天${data.condition},` +
          `气温${today.low}~${today.high}°C,` +
          `湿度${data.humidity}%`
      })
    } catch (e) {
      console.error(`查询 ${location} 天气出错:`, e)
      return SkillResult.error(`查询${location}的天气失败了,稍后再试试`)
    }
}
}


Skill写好后,需要注册到Agent实例中。以下是在SmartLifeAgent中注册WeatherQuerySkill的典型代码:

// agent/src/main/ets/SmartLifeAgent.ets
import { Agent, AgentConfig, AgentRequest, AgentResponse } from '@kit.AgentKit'
import { WeatherQuerySkill } from './skills/WeatherQuerySkill'

export class SmartLifeAgent extends Agent {
onCreate(config: AgentConfig): void {
    this.registerSkill(new WeatherQuerySkill())
}
}


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

在应用端,通过Agent Framework Kit集成智能体入口。核心组件是FunctionComponent(UI入口)和FunctionController(控制器)。以下是一个完整的集成示例,包含智能体可用性检查、对话框生命周期监听和降级方案:

// entry/src/main/ets/pages/SmartAssistantPage.ets
import { BusinessError } from '@kit.BasicServicesKit'
import { common } from '@kit.AbilityKit'
import {
FunctionComponent,
FunctionController,
ButtonType
} from '@kit.AgentFrameworkKit'
import { hilog } from '@kit.PerformanceAnalysisKit'

@Entry
@Component
struct SmartAssistantPage {
@State isAgentReady: boolean = false
private agentId: string = 'agentproxy_smart_life_2026'
private controller: FunctionController = new FunctionController()

async aboutToAppear() {
    try {
      let context = this.getUIContext()?.getHostContext() as common.UIAbilityContext
      this.isAgentReady = await this.controller.isAgentSupport(context, this.agentId)
    } catch (err) {
      hilog.error(0x0001, 'AgentDemo', `智能体检查失败: ${err}`)
    }

    this.controller.on('agentDialogOpened', () => {
      hilog.info(0x0001, 'AgentDemo', '智能体对话框已打开')
    })
    this.controller.on('agentDialogClosed', () => {
      hilog.info(0x0001, 'AgentDemo', '智能体对话框已关闭')
    })
}

aboutToDisappear() {
    this.controller.off('agentDialogOpened')
    this.controller.off('agentDialogClosed')
}

build() {
    Column({ space: 16 }) {
      if (this.isAgentReady) {
      FunctionComponent({
          agentId: this.agentId,
          onError: (err: BusinessError) => {
            hilog.error(0x0001, 'AgentDemo',
            `拉起智能体失败: ${err.code} - ${err.message}`)
          },
          options: {
            title: 'AI 生活助手',
            queryText: '帮我看看今天有什么安排',
            buttonType: ButtonType.CAPSULE,
            isShowShadow: true,
            titleFontSize: 16,
            iconSize: 20,
            iconColors: ['#00d4ff'],
            titleColors: ['#00d4ff', '#00ff88'],
            backgroundColor: '#0a1628'
          },
          controller: this.controller
      })
      } else {
      Text('AI助手暂不可用,请稍后重试')
          .fontSize(14)
          .fontColor('#999999')
      }
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)
}
}


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

在多设备协同场景下,需要通过统一服务能力模型进行动态路由。以下是一个示例模型,根据设备上下文(网络状态、位置权限、电量)自动选择最优目标:

type DeviceType = 'phone' | 'tablet' | 'pc' | 'watch' | 'car'

interface ServiceCapability {
id: string
name: string
scene: string
requiredPermissions: string[]
supportedDevices: DeviceType[]
riskLevel: 'low' | 'medium' | 'high'
fallback: string
}

const routePlanning: ServiceCapability = {
id: 'travel.route.plan',
name: '路线规划',
scene: '出行',
requiredPermissions: ['location'],
supportedDevices: ['phone', 'tablet', 'car'],
riskLevel: 'medium',
fallback: '展示手动输入地址页面'
}

interface DeviceContext {
device: DeviceType
networkAvailable: boolean
locationGranted: boolean
batteryLow: boolean
}

function selectRouteTarget(ctx: DeviceContext): string {
if (!ctx.networkAvailable) return 'offlineFallback'
if (ctx.device === 'car' && ctx.locationGranted) return 'carNavigation'
if (ctx.device === 'watch') return 'briefReminder'
return 'phoneRoutePage'
}


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

对于想要入局的开发者,建议首先从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生态的有利时机。

热心网友2 发表于 2026-7-30 22:05:00

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

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

热心网友2 发表于 2026-7-30 22:05:00

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

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

热心网友2 发表于 2026-7-30 22:05:00

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

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