• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Developing Intents Using Decorators
2## When to Use
3Starting from API version 20, you can develop intents using decorators, allowing you to quickly integrate existing features into system entry points. The table below lists some typical scenarios.
4
5| Intent Call Scenario| Common Intent Example| Intent Development Method|
6| --- | --- | --- |
7| Launching an application| - Play music.<br>- Open a shopping application to a product details page.|  - Create new intent logic using [@InsightIntentEntry](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintententry), and bind the intent to a UIAbility or UIExtensionAbility.<br>- Convert a URI into an intent using [@InsightIntentLink](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintentlink).<br>- Convert a page route to an intent using [@InsightIntentPage](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintentpage).|
8| Querying or updating information| - Query the weather.<br>- Modify application settings or update an application.| - Convert a function call to a system intent using [@InsightIntentFunctionMethod](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintentfunctionmethod).<br>- Create new intent logic using [@InsightIntentEntry](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintententry), and bind the intent to the background execution mode of a UIAbility or a ServiceExtensionAbility.|
9| Adding service widgets| - Add a weather widget.| - Develop an intent using [@InsightIntentForm](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintentform).|
10
11## Working Principles
12
13| Function| Intent Development| Intent Execution|
14| --- | --- | --- |
15| Developing intents using [@InsightIntentEntry](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintententry)| 1. Add a new intent execution file. If the execution file is not imported by other files, configure its path through the **insightIntentsSrcEntry** field in the **insight_intent.json** file to include it in compilation.<br> 2. Use decorators to define the application component to be bound to the intent and the intent execution mode.| The system entry point matches the intent and triggers the startup of the application component and intent execution according to the intent execution mode.|
16| Developing intents using [@InsightIntentLink](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintentlink)| Define an intent for link redirection, which can be an existing or a new URI.| The system entry point matches the intent, transfers a URI, and triggers intent execution via [openLink](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#openlink12). For parameter processing during intent execution, see the **paramCategory** description in [LinkIntentParamMapping](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#linkintentparammapping).|
17| Developing intents using [@InsightIntentPage](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintentpage)| Define a page redirection intent, and configure the corresponding UIAbility, [page route](../ui/arkts-routing.md) path, and [Navigation](../ui/arkts-navigation-navigation.md) path for the intent.| 1. The system entry point uses **startAbility** to start the UIAbility bound to the intent. If the intent is not bound to a UIAbility, it starts the UIAbility corresponding to the [mainElement](../quick-start/module-configuration-file.md#tags-in-the-configuration-file) of the module where the intent is located.<br>2. During intent execution, if the application is not started, it jumps to the page corresponding to the intent after loading the home page of the UIAbility; if the application is already started, it jumps to the page corresponding to the intent from the current page.<br>3. Parameters are passed to the target page during intent execution.<br>4. If the **navigationId** or **navDestinationName** field fails to match, the system falls back to page redirection corresponding to the **pagePath** field.|
18| Developing intents using [@InsightIntentFunctionMethod](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintentfunctionmethod)| Define an intent for a static method, which can be an existing or a new method.| The system entry point uses [Call](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#background-communication-capability) to start the UIAbility corresponding to the [mainElement](../quick-start/module-configuration-file.md#tags-in-the-configuration-file) of the module where the intent is located.|
19| Developing intents using [@InsightIntentForm](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintentform)| Define an intent for a widget, which can be an existing or a new widget.| The system entry point creates an intent widget using the FormComponent.|
20
21## How to Develop
22
23This section uses the development of standard intents and custom intents with @InsightIntentEntry as an example. Developing standard and custom intents with other decorators is similar to @InsightIntentEntry. You can refer to the API documentation for developing other types of intents.
24
25### Developing Standard Intents with Intent Decorators
26
27The following uses the standard intent [ViewLogistics](./insight-intent-access-specifications.md#viewing-logistics) as an example to describe how to develop a standard intent with the @InsightIntentEntry decorator.
28
291. Declare the intent execution file in the **insightIntentsSrcEntry** field of the **insight_intent.json** file.
30
31    ```json
32    {
33      "insightIntentsSrcEntry": [
34        {
35          "srcEntry": "./ets/insightintents/ViewLogisticsImpl.ets"
36        }
37      ]
38    }
39    ```
40
412. Implement the intent executor.
42
43    When developing a standard intent, you do not need to define the large language model description, intent parameters, or intent execution results. Standard intents are matched from the [Appendix: Standard Intent Access Specifications](insight-intent-access-specifications.md) based on the **schema** and **intentVersion** fields. The intent executor must inherit from the **InsightIntentEntryExector\<T>** class and implement the **onExecute()** API.
44    ```ts
45    import { InsightIntentEntryExecutor, insightIntent, InsightIntentEntry } from '@kit.AbilityKit';
46
47    class ViewLogisticsResultDef {
48      msg?: string = '';
49    }
50
51    @InsightIntentEntry({
52      intentName: 'ViewLogistics',
53      domain: 'LocalDomain',
54      intentVersion: '1.0.1',
55      displayName: 'Query Logistics',
56      displayDescription: 'Query logistics with tracking number',
57      schema: 'ViewLogistics',
58      icon: $r('app.media.viewLogistics'), // $r indicates a local icon, which must be defined in the resource catalog.
59      abilityName: 'EntryAbility',
60      executeMode: [insightIntent.ExecuteMode.UI_ABILITY_BACKGROUND],
61    })
62    export default class ViewLogisticsImpl extends InsightIntentEntryExecutor<ViewLogisticsResultDef> {
63      trackingNo?: string = '';
64      entityId?: string = '';
65
66      onExecute(): Promise<insightIntent.IntentResult<ViewLogisticsResultDef>> {
67        // Execute logistics query logic.
68        let result: insightIntent.IntentResult<ViewLogisticsResultDef> = {
69          code: 0,
70          result: {
71            msg: 'the logistics is being delivered'
72          }
73        }
74        return Promise.resolve(result);
75      }
76    }
77    ```
78
79The intent execution process is as follows:
801. The system entry point responds to the user request "Query logistics with tracking number 12345", matches the "ViewLogistics" intent of the application, and triggers intent execution through the InsightIntent framework.
812. The intent is bound to an EntryAbility and configured with the execution mode **insightIntent.ExecuteMode.UI_ABILITY_BACKGROUND**. During intent execution, the bound EntryAbility is started via [Call](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#background-communication-capability). The **trackingNo** property of the **ViewLogisticsImpl** class is assigned, and the **onExecute()** API is executed to return the intent execution result to the system entry point through the InsightIntent framework.
823. The system entry point converts the intent execution result into natural language and presents it to the user.
83
84### Developing Custom Intents with Intent Decorators
85
86The following uses the development of a custom intent "Play Music" as an example. You are required to define the large language model description, intent search keywords, intent parameters, and intent execution results for the intent.
87
881. Declare the intent execution file in the **insightIntentsSrcEntry** field of the **insight_intent.json** file.
89
90    ```json
91    {
92      "insightIntentsSrcEntry": [
93        {
94          "srcEntry": "./ets/insightintents/PlayMusicImpl.ets"
95        }
96      ]
97    }
98    ```
99
1002. Implement the intent executor.
101
102    When developing custom intents, you are required to define the large language model description, intent search keywords, intent parameters, and intent execution results. The intent executor must inherit from the **InsightIntentEntryExector\<T>** class and implement the **onExecute()** API.
103
104    ```ts
105    // Implementation of the insightIntentsSrcEntry field in the insight_intent.json file.
106    import { InsightIntentEntryExecutor, insightIntent, InsightIntentEntity, InsightIntentEntry } from '@kit.AbilityKit';
107
108    // Data format definition of the intent execution result.
109    class PlayMusicResultDef {
110      msg?: string = '';
111    }
112
113    // Intent definition.
114    @InsightIntentEntry({
115      intentName: 'PlayMusic',
116      domain: 'MusicDomain',
117      intentVersion: '1.0.1',
118      displayName: 'Play Music',
119      displayDescription: 'Intent to play music',
120      icon: $r('app.media.playMusic'), // $r indicates a local icon, which must be defined in the resource catalog.
121      llmDescription: 'Supports passing song names to play music',
122      keywords: ['music playback', 'play music', 'PlayMusic'],
123      abilityName: 'EntryAbility',
124      executeMode: [insightIntent.ExecuteMode.UI_ABILITY_FOREGROUND],
125      parameters: {
126        "type": "object",
127        "description": "A schema for describing songs and their artists",
128        "properties": {
129          "songName": {
130            "type": "string",
131            "description": "The name of the song",
132            "minLength": 1
133          },
134          "singer": {
135            "type": "string",
136            "description": "The name of the singer",
137            "minLength": 1
138          }
139        },
140        "required": ["songName"]
141      }
142    })
143    export class PlayMusicImpl extends InsightIntentEntryExecutor<PlayMusicResultDef> {
144      songName: string = '';
145      singer?: string = '';
146
147      onExecute(): Promise<insightIntent.IntentResult<PlayMusicResultDef>> {
148        // Execute the music playback logic.
149        let result: insightIntent.IntentResult<PlayMusicResultDef> = {
150          code: 123,
151          result: {
152            msg: 'play music succeed'
153          }
154        }
155        return Promise.resolve(result);
156      }
157    }
158    ```
159
160The intent execution process is as follows:
1611. The system entry point responds to the user request "Play song B of singer A", matches the "PlayMusic" intent of the application, and triggers intent execution through the InsightIntent framework.
1622. The intent is bound to an EntryAbility and configured with the execution mode **insightIntent.ExecuteMode.UI_ABILITY_FOREGROUND**. During intent execution, the bound EntryAbility is started via **startAbility**. The **songName** and **singer** properties of the **PlayMusicImpl** class are assigned, and the **onExecute()** API is executed to return the intent execution result to the system entry point through the InsightIntent framework.
1633. The system entry point converts the intent execution result into natural language and presents it to the user.
164
165### (Optional) Passing Complex Parameters by Developing Intent Entities
166
167By default, data passed from the system entry point to the application is of basic types. For more complex data—such as singer information (including name, nationality, and more) when playing music—you need object types. These are defined using the [@InsightIntentEntity](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintententity) decorator and are known as intent entities.
168
169Consider a music playback scenario: A user tells the voice assistant Celia the name and singer information of the desired song, and Celia launches the corresponding music screen to play the song based on the information.
170
171To implement this, you can define singer information as an intent entity and develop the intent entity. The procedure is as follows:
172
1731. Define an intent entity.
174
175    Define singer information (including name, country, city, and more) as a class and use the @InsightIntentEntity decorator to define this class as an intent entity. The **parameters** property of the decorator lists the class's data members, data formats, and the required status of each member.
176
177    ```ts
178    import { insightIntent, InsightIntentEntity } from '@kit.AbilityKit';
179
180    @InsightIntentEntity({
181      entityCategory: 'artist entity category',
182      parameters: {
183        '$id': '/schemas/ArtistClassDef',
184        'type': 'object',
185        'description': 'Information about the artist',
186        'properties': {
187          'country': {
188            'type': 'string',
189            'description': 'The artist\'s country of origin',
190            'default': 'zh'
191          },
192          'city': {
193            'type': 'string',
194            'description': 'The artist\'s city of origin'
195          },
196          'name': {
197            'type': 'string',
198            'description': 'The name of the artist',
199            'minLength': 1
200          }
201        },
202        // name is a mandatory parameter.
203        'required': ['name']
204      }
205    })
206    export class ArtistClassDef implements insightIntent.IntentEntity {
207      entityId: string = '0x11';
208      country?: string = '';
209      city?: string = '';
210      name: string = '';
211    }
212    ```
213
2142. Use the intent entity. Add an intent decorated with [@InsightIntentEntry](../reference/apis-ability-kit/js-apis-app-ability-InsightIntentDecorator.md#insightintententry) that uses the song name and singer information (the **ArtistClassDef** intent entity) as input parameters for music playback.
215
216    ```ts
217    import { insightIntent, InsightIntentEntry, InsightIntentEntryExecutor, InsightIntentEntity } from '@kit.AbilityKit';
218    import { hilog } from '@kit.PerformanceAnalysisKit';
219
220    const LOG_TAG: string = 'testTag-EntryIntent';
221
222    @InsightIntentEntity({
223      entityCategory: 'artist entity category',
224      // The ArtistClassDef intent entity information has been described in parameters of the @InsightIntentEntry decorator. Therefore, parameters can be left unspecified.
225    })
226    export class ArtistClassDef implements insightIntent.IntentEntity {
227      entityId: string = '0x11';
228      country?: string = '';
229      city?: string = '';
230      name: string = '';
231    }
232
233    // Use the @InsightIntentEntry decorator to define an intent.
234    @InsightIntentEntry({
235      intentName: 'PlayMusic',
236      domain: 'MusicDomain',
237      intentVersion: '1.0.1',
238      displayName: 'Play Music',
239      displayDescription: 'Intent to play music',
240      icon: $r('app.media.app_icon'), // $r indicates a local icon, which must be defined in the resource catalog.
241      llmDescription: 'Supports passing song names to play music',
242      keywords: ['music playback', 'play music', 'PlayMusic'],
243      abilityName: 'EntryAbility',
244      executeMode: [insightIntent.ExecuteMode.UI_ABILITY_FOREGROUND],
245      parameters: {
246        'schema': 'http://json-schema.org/draft-07/schema#',
247        'type': 'object',
248        'title': 'Song Schema',
249        'description': 'A schema for describing songs and their artists',
250        'properties': {
251          'songName': {
252            'type': 'string',
253            'description': 'The name of the song',
254            'minLength': 1
255          },
256          'artist': {
257            'type': 'object',
258            'description': 'Information about the artist',
259            'properties': {
260              'country': {
261                'type': 'string',
262                'description': 'The artist\'s country of origin',
263                'default': 'zh'
264              },
265              'city': {
266                'type': 'string',
267                'description': 'The artist\'s city of origin'
268              },
269              'name': {
270                'type': 'string',
271                'description': 'The name of the artist',
272                'minLength': 1
273              }
274            },
275            'required': ['name']
276          }
277        },
278        'required': ['songName']
279      }
280    })
281    export default class PlayMusicDemo extends InsightIntentEntryExecutor<string> {
282      songName: string = '';
283      // Use the intent entity.
284      artist?: ArtistClassDef;
285
286      onExecute(): Promise<insightIntent.IntentResult<string>> {
287        hilog.info(0x0000, LOG_TAG, 'PlayMusicDemo executeMode %{public}s', JSON.stringify(this.executeMode));
288        hilog.info(0x0000, LOG_TAG, 'PlayMusicDemo artist %{public}s', JSON.stringify(this.artist));
289        let storage = new LocalStorage();
290        storage.setOrCreate('songName', this.songName);
291        storage.setOrCreate('artist', this.artist);
292        // Open the PlayMusicPage page in different ways based on the executeMode parameter.
293        if (this.executeMode == insightIntent.ExecuteMode.UI_ABILITY_FOREGROUND) {
294          this.windowStage?.loadContent('pages/PlayMusicPage', storage);
295        } else if (this.executeMode == insightIntent.ExecuteMode.UI_EXTENSION_ABILITY) {
296          this.uiExtensionSession?.loadContent('pages/PlayMusicPage', storage);
297        }
298        // Define the intent execution result.
299        let result: insightIntent.IntentResult<string> = {
300          code: 123,
301          result: 'execute success'
302        }
303        hilog.info(0x0000, LOG_TAG, 'PlayMusicDemo return %{public}s', JSON.stringify(result));
304        return Promise.resolve(result);
305      }
306    }
307    ```
308