随着大语言模型技术的成熟,人机交互正从图形用户界面(GUI)转向语言用户界面(LUI)。HarmonyOS推出的HMAF(鸿蒙智能体框架)作为操作系统级基础设施,旨在打通感知、决策、行动全链路,实现跨平台智能体协作。本文从开发角度解析HMAF的三层架构、核心能力及代码接入方式。
一、三层架构与开发入口
HMAF采用应用层、框架层、能力层三层设计。应用层通过Agent Framework Kit暴露两个关键模块:FunctionComponent用于声明式拉起智能体,AgentController管理生命周期。开发者只需约40行声明式代码即可接入系统级智能体,操作系统自动处理UI渲染、流式输出和网络通信。
二、感知层实现:环境感知智能体
感知是链路起点,包括交互感知和环境感知。以下代码展示环境感知智能体:每5秒轮询传感器数据,检测到人员存在且温度超标时自动通知空调智能体,光照不足时通知灯光智能体。- import { BaseAgent } from '@ohos.ai.agent';
- export class EnvironmentSensorAgent extends BaseAgent {
- private temperature: number = 24;
- private brightness: number = 500;
- private presence: boolean = false;
- private pollingTimer: number = -1;
- constructor() {
- super('agent.environment.sensor', [
- 'temperature_monitoring',
- 'brightness_detection',
- 'presence_sensing'
- ]);
- this.startSensorPolling();
- }
- private startSensorPolling(): void {
- this.pollingTimer = setInterval(async () => {
- this.temperature = 22 + Math.random() * 6;
- this.brightness = 300 + Math.random() * 400;
- this.presence = Math.random() > 0.3;
- if (this.presence) {
- await this.checkEnvironmentAndNotify();
- }
- }, 5000);
- }
- private async checkEnvironmentAndNotify(): Promise<void> {
- if (this.temperature > 26) {
- await this.sendMessage('agent.ac.control', {
- action: 'cooling',
- targetTemperature: 24,
- urgency: 'high'
- });
- }
- if (this.brightness < 200 && this.presence) {
- await this.sendMessage('agent.light.control', {
- action: 'turn_on',
- brightness: 70,
- colorTemperature: 4000
- });
- }
- }
- onDestroy(): void {
- if (this.pollingTimer !== -1) {
- clearInterval(this.pollingTimer);
- this.pollingTimer = -1;
- }
- }
- }
复制代码
三、决策层:多智能体协同与任务规划
决策层包含任务规划器和多智能体协同引擎。场景编排智能体可将用户高层意图拆解为子任务,并行调度多个专业智能体。例如创建“舒适休息”场景时,同时发送指令给空调、灯光、窗帘智能体,并支持失败回滚。- import { BaseAgent } from '@ohos.ai.agent';
- export class SceneOrchestratorAgent extends BaseAgent {
- constructor() {
- super('agent.scene.orchestrator', [
- 'scene_planning',
- 'multi_agent_coordination',
- 'task_decomposition'
- ]);
- }
- async createRelaxScene(): Promise<void> {
- const results = await Promise.all([
- this.sendMessage('agent.ac.control', {
- action: 'cooling',
- targetTemperature: 24,
- mode: 'quiet'
- }),
- this.sendMessage('agent.light.control', {
- action: 'set_scene',
- scene: 'warm_relax',
- brightness: 40
- }),
- this.sendMessage('agent.curtain.control', {
- action: 'close',
- speed: 'slow'
- })
- ]);
- const allSuccess = results.every(r => r.success === true);
- if (allSuccess) {
- console.info('舒适休息场景编排完成');
- } else {
- await this.rollbackScene(results);
- }
- }
- private async rollbackScene(results: Array<{success: boolean, agentId: string}>): Promise<void> {
- for (const result of results) {
- if (result.success) {
- await this.sendMessage(result.agentId, { action: 'restore' });
- }
- }
- }
- }
复制代码
四、行动层:服务调用与跨设备流转
行动层通过服务调用器标准化调用鸿蒙生态服务,兼容MCP协议。跨设备任务流转依赖分布式软总线,智能体之间通过Agent通信协议进行服务发现、能力协商和安全鉴权。该协议针对高频小数据量交互优化,跨设备协作时延降低70%。
五、智能体注册与拉起完整流程
开发者注册智能体时需声明agentId、名称、版本和能力列表;拉起时通过AgentController检测可用性,再调用FunctionComponent传入参数。- import agent from '@ohos.ai.agent';
- import { AgentController, FunctionComponent } from '@ohos.ai.agentframeworkkit';
- import { BusinessError } from '@ohos.base';
- import hilog from '@ohos.hilog';
- export class AgentIntegrationDemo {
- private agentId: string = 'agent.travel.booking';
- async registerTravelAgent(): Promise<void> {
- try {
- agent.registerAgent({
- agentId: this.agentId,
- name: 'TravelBookingAgent',
- version: '1.0.0',
- capabilities: [
- 'flight_search',
- 'hotel_booking',
- 'itinerary_planning',
- 'cross_device_handoff'
- ]
- });
- hilog.info(0x0001, 'AgentDemo', '旅行预订智能体注册成功');
- } catch (err) {
- hilog.error(0x0001, 'AgentDemo', `注册失败: ${(err as BusinessError).message}`);
- }
- }
- async invokeTravelAgent(): Promise<void> {
- const isAvailable = await AgentController.isServiceAvailable(this.agentId);
- if (!isAvailable) {
- hilog.warn(0x0001, 'AgentDemo', '旅行预订智能体当前不可用');
- return;
- }
- FunctionComponent.create({
- agentId: this.agentId,
- params: {
- destination: 'Beijing',
- date: '2026-05-10',
- preference: 'comfort'
- },
- onError: (err: BusinessError) => {
- hilog.error(0x0001, 'AgentDemo', `智能体调用出错: ${err.code} - ${err.message}`);
- }
- });
- hilog.info(0x0001, 'AgentDemo', '旅行预订智能体已拉起');
- }
- }
复制代码
六、开发总结
HMAF通过三层架构和分布式软总线,实现了极简开发(约40行代码接入)、自主决策(多智能体协同)、无缝流转(跨设备任务迁移)和生态兼容(MCP协议)。开发者应重点关注智能体能力声明的颗粒度、消息协议的标准化以及异常回滚机制,以构建稳健的智能体应用。 |