Knowledge processing refers to the capability of generating a knowledge base based on actual service data. It includes the following operations:
Configure the schema to generate knowledge processing products (such as inverted index tables, vector libraries, and vector tables). These products are used for retrieval during knowledge Q&A. The schema configuration must be based on the database and data table structure used in actual services. Knowledge processing and retrieval are optimized for Chinese. Therefore, the Q&A performance of Chinese is better than that of English.
Call the API for obtaining the knowledge processing status.
Knowledge processing supports the following file types:
Text and web pages: txt and html.
Office files: doc, docx, ppt, pptx, xls, xlsx, and pdf. Only basic processing of plain text is supported. For complex or specific content, use the corresponding app to parse and process it and then convert it to the TXT format for subsequent processing.
Images: jpeg, jpg, and png.
Since version 6.1.0(23), keyword tables and time feature tables are supported. The following table describes the structure of the product generated during knowledge processing.
Table 1 Inverted index table structure
| Column | Type | Description |
|---|---|---|
| reference_id | UNINDEXED | ID used for association, which corresponds to the primary key ID in the service table. |
| chunk_id | UNINDEXED | ID of a split chunk. A chunk indicates a slice of the text that needs to be processed. |
| chunk_source | UNINDEXED | Field of a chunk in the service table. |
| chunk_text | TEXT | Inverted index field, which is the text content of a chunk. |
Table 2 Vector table structure
| Column | Type | Description |
|---|---|---|
| id | INTEGER | Auto-increment primary key. |
| reference_id | INTEGER | ID used for association, which corresponds to the primary key ID in the service table. |
| chunk_id | TEXT | ID of a split chunk. A chunk indicates a slice of the text that needs to be processed. |
| chunk_source | TEXT | Field of a chunk in the service table. |
| repr | FLOATVECTOR(128) | Vector representation of the text corresponding to chunk_id. |
| Scalar | TEXT | All scalar fields defined in the schema are of the TEXT type. |
Table 3 Keyword table structure
| Column | Type | Description |
|---|---|---|
| id | INTEGER | Auto-increment primary key. |
| reference_id | INTEGER | ID used for association, which corresponds to the primary key ID in the service table. |
| chunk_id | TEXT | ID of a split chunk. A chunk indicates a slice of the text that needs to be processed. |
| word | TEXT | Matched keyword. |
| extendFields | TEXT | All columns defined by extendFields under the customKeyword field in the schema. Each field occupies a column, and the type of each column is TEXT. |
Table 4 Time feature table structure
| Column | Type | Description |
|---|---|---|
| id | INTEGER | Auto-increment primary key. |
| reference_id | INTEGER | ID used for association, which corresponds to the primary key ID in the service table. |
| chunk_id | TEXT | ID of a split chunk. A chunk indicates a slice of the text that needs to be processed. |
| start_time | TEXT | Start time of the matched time period. |
| end_time | TEXT | End time of the matched time period. |
| extendFields | TEXT | All columns defined by extendFields under the time field in the schema. Each field occupies a column, and the type of each column is TEXT. |
Knowledge processing can be triggered in the following scenarios:
After the knowledge_schema.json file and the database creation or opening parameters are configured according to Development Procedure, a knowledge processing task is triggered each time the database is created or opened.
When the database is successfully created or opened and an active database connection is available, a knowledge processing task is automatically triggered upon any data change (insert, update, or delete) to the data source table.
Tables used for knowledge processing do not support cross-device synchronization and device-cloud synchronization, and cannot be used for search.
The schema configuration file for knowledge processing is src/main/resources/rawfile/arkdata/knowledge/knowledge_schema.json. The file content must be valid JSON strings.
Knowledge processing cleanup API: In the schema upgrade scenario, call the cleanKnowledgeData API before opening or creating a database for the first time or calling the getKnowledgeProcessor API.
The following table lists the key knowledge processing APIs common.BaseContext. For details about the APIs, see API Reference.
| API | Description |
|---|---|
| getKnowledgeProcessor(context: common.BaseContext, config: KnowledgeProcessorConfig): Promise<KnowledgeProcessor> | Obtains the knowledge processing object for obtaining the knowledge processing status. |
| getStatus(): Promise<ProcessorStatus> | Obtains the knowledge processing status. |
| startProcess(option: KnowledgeProcessConfig): Promise<void> | Starts knowledge processing based on the input parameter configurations. |
| stopProcess(): Promise<void> | Stops the current knowledge processing. |
| cleanKnowledgeData(context: common.BaseContext, config: KnowledgeProcessorConfig): Promise<void> | Cleans the knowledge base. This API obtains the knowledge base information based on the knowledge processing configuration in the input parameters and cleans the knowledge base. |
| getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> | Creates a relational database (RDB) or opens an existing RDB. After setting database creation or opening parameters according to step 2, this API can be called to trigger knowledge processing. |
In 6.1.0(23) and later versions, the knowledge_schema.json schema configuration file for knowledge processing supports the commonAttribute and customKeyword parameters, and the type field of knowledgeField supports the Markdown type.
In 26.0.0 and later versions, the intelligent email analysis capability is added to knowledge processing.
Import the required modules.
import { knowledgeProcessor } from '@kit.DataAugmentationKit';
import { relationalStore } from '@kit.ArkData';
import { UIContext } from '@kit.ArkUI'; Configure the knowledge processing schema file knowledge_schema.json based on the service requirements. The following is a configuration example. The naming rules of knowledge processing products are as follows:
// File path: src/main/resources/rawfile/arkdata/knowledge/knowledge_schema.json
// If the directory does not exist in the project, create it recursively.
// Delete this comment during app development. The comment is provided only for field description.
{
"knowledgeSource": [{
"version": 1,
"dbName": "testmail_store.db", // Name of the database file for storing original data.
"tables": [{
"tableName": "email", // Name of the table used for knowledge processing.
"referenceFields": ["id"], // Reference fields of the knowledge data source, which are used to associate data in the knowledge base.
"processSequence": { // Define the processing sequence as descending order by ID.
"columnName": "id",
"sortType": "DESC"
},
"customKeyword": {
"wordTablePath": "/data/storage/el2/base/haps/entry/files/keywords.txt", // This is only an example. Set the actual file path based on the service requirements.
"sourceFields": ["subject", "content"], // Columns where keyword extraction takes effect.
"extendFields": [] // Additional columns added when creating the keyword table. The data is the same as that in the source table.
},
"commonAttribute": {
"time": {
"baseTimeField": "received_date",
"sourceFields": ["subject", "content"],
"extendFields": ["sender"]
}
},
"knowledgeFields": [{ // Fields used for knowledge processing.
"columnName": "subject", // Column name for knowledge processing.
"type": ["Text"] // Field type for knowledge processing. The value **Text** is for vector and inverted indexes.
},
{
"columnName": "content",
"type": ["Text"]
},
{
"columnName": "image_text",
"type": ["Text"]
},
{
"columnName": "attachment_names",
"type": ["Text"]
},
{
"columnName": "inline_files",
"type": ["Json"],
"parser": [
{
"type": "File",
"path": "$[*].uri" // The value of **path** is a JSON path expression.
}
]
},
{
"columnName": "sender",
"type": ["Scalar"], // The value **Scalar** indicates a scalar field. Under this setting, knowledge will not be processed and is directly written to the corresponding column in the vector table for scalar retrieval and filtering.
"description": "sender"
},
{
"columnName": "receivers",
"type": ["Scalar"],
"description": "receivers"
},
{
"columnName": "received_date",
"type": ["Scalar"],
"description": "received_date"
}],
"pipelineHandlers": {
"FileParserHandler": ["SplitTextHandler"], // After the file is parsed, the SplitTextHandler continues to process the file.
"SplitTextHandler": ["TextEmbeddingHandler"],
"TextEmbeddingHandler": ["ImageEmbeddingHandler"],
"ImageEmbeddingHandler": []
}
}],
"knowledgeProcess": {
"embeddingModelCfg":
{
"modelVersion": "default" // Vector representation model. The value **default** indicates the default version.
},
"chunkSplitter":
{
"chunkSize": 3072,
"segmentSize": 300,
"overlapRatio": 0.1
},
"perRecordLimit":
{
"parseFileMaxCnt": 10,
"textEmbeddingMaxCnt": 50,
"imageEmbeddingMaxCnt": 10
}
}
}]
} | Field | Mandatory (Yes/No) | Description |
|---|---|---|
| version | No | Schema version number. The value is a positive integer. The maximum value is 2147483647. |
| dbName | No | Database store name. The value contains 1 to 120 characters, including digits, uppercase letters, lowercase letters, underscores (_), and periods (.). |
| tableName | No | Knowledge table name. The value contains 1 to 120 characters, including digits, uppercase letters, lowercase letters, and underscores (_). |
| columnName | No | Knowledge field column name. The value contains 1 to 255 characters. |
| referenceFields | No | Primary key of the associated knowledge table. Only one field is supported. The value is an integer that contains 1 to 255 digits. |
| type | No | Knowledge field type. The following knowledge field types are supported: - Text: plain text knowledge processing field. - Scalar: scalar field. The description field is mandatory. The value range is [1, 255]. The fields of the Scalar type are not used for knowledge processing. The field values are the same as those in the service table. The length range of the columnName field of the Scalar type is [1, 128]. - Json: knowledge processing field in JSON format. The parser field must be included to specify the parser of the file path. Each knowledge processing field of the Json type can contain 1 to 5 parsers, and a maximum of five different local file paths can be parsed. The type and path fields are mandatory for each parser object. The value of type is fixed to File, and the value of path is a string of 1 to 255 characters. The value of path must be a valid JSON path expression, which specifies the file path to be parsed during knowledge processing. - Markdown: knowledge processing field in Markdown format. Currently, only one knowledge field of the Markdown type is supported, and the Markdown field cannot be set to other types at the same time. Since: 6.1.0(23) |
| processSequence | Yes | Processing sequence, which is used to define the data processing sequence. It contains two fields: columnName and sortType. - columnName corresponds to a column name of a data source table. The length of the columnName value ranges from 1 to 255 characters, including digits, uppercase letters, lowercase letters, and underscores (_). The column corresponding to columnName must be of the integer type and must exist in the data source table. - sortType specifies whether to sort data in ascending or descending order. The value of sortType can only be ASC (ascending order) or DESC (descending order). |
| customKeyword | Yes | Customized keyword, which is used to configure the keyword extraction function. After this field is configured, an additional keyword table is generated during knowledge processing. Compared with the data source table, the table name has the suffix _knowledge_keyword and contains three fields. - wordTablePath: path of the keyword list file. The length range is [1, 255]. The file must be a .txt file and must exist. - sourceFields: specifies a column for which the keyword extraction function takes effect. The length range is [1, 10]. Each column can contain 1 to 255 characters, including digits, uppercase letters, lowercase letters, and underscores ( ). - extendFields: specifies the columns that need to be created for the keyword extraction product. The length range is [0, 10]. Each column can contain 1 to 255 characters, including digits, uppercase letters, lowercase letters, and underscores ( ).Since: 6.1.0(23) |
| commonAttribute | Yes | Common feature. Currently, only the time feature can be configured, and the corresponding field is time. After this field is configured, an additional time table is generated during knowledge processing. Compared with the data source table, the table name has the suffix _knowledge_time and contains three fields. - baseTimeField: corresponds to the base time column. The length range is [1, 255] and the column must exist. This column must be a valid Unix millisecond-level timestamp in the data source table. - sourceFields: specifies a column for which the time feature extraction function takes effect. The length range is [1, 10]. Each column can contain 1 to 255 characters, including digits, uppercase letters, lowercase letters, and underscores ( ). - extendFields: specifies the columns that need to be created for the time feature extraction product. The length range is [0, 10]. Each column can contain 1 to 255 characters, including digits, uppercase letters, lowercase letters, and underscores ( ).Since: 6.1.0(23) |
| pipelineHandlers | No | Execution sequence, which defines the execution sequence of each handler during knowledge processing. It controls how the original data is parsed, split, and represented, and finally written to the inverted index table and vector table. You can modify the handler process and configure it as a mapping (unordered_map<string, vector<string>>). Each key is the current handler, and the value is the list of handlers to be executed subsequently. The following is an example: "pipelineHandlers": { "FileParserHandler": ["SplitTextHandler"], "SplitTextHandler": ["TextEmbeddingHandler"], "TextEmbeddingHandler": ["ImageEmbeddingHandler"], "ImageEmbeddingHandler": [] } Currently, the following handlers are supported: FileParserHandler, SplitTextHandler, TextEmbeddingHandler, ImageEmbeddingHandler, MailSummaryHandler, MailTodoHandler, and MailClassificationHandler. Handlers cannot depend on each other cyclically. Otherwise, the system will report an error when loading the schema. The downstream of each handler can be an empty array, indicating that the processing ends here. The recommended standard knowledge processing flow is as follows: FileParserHandler → SplitTextHandler → TextEmbeddingHandler → ImageEmbeddingHandler The recommended standard execution process for intelligent email analysis is as follows: MailSummaryHandler -> MailTodoHandler -> MailClassificationHandler. You can add or delete handlers as required. If the configuration sequence is incorrect (for example, some handlers are skipped, the sequence is incorrect, or a closed loop is formed), files may not be processed, the processing may be interrupted, or the initialization may fail. You can simplify the configuration based on the actual scenario. For example, if only the inverted index table needs to be processed, you need to configure only the SplitTextHandler. The functions and dependencies of the handlers are as follows: - FileParserHandler: extracts the text content from the local files specified by the knowledge processing fields of the Json type. The supported file formats are doc, docx, ppt, pptx, xls, xlsx, html, txt, pdf, png, jpg, and jpeg. For text files, the text content is extracted. For image files, OCR is used to extract the recognizable text. This handler does not depend on other handlers. Recommended configuration sequence: You are advised to place this handler before the SplitTextHandler so that the extracted file content can be split and represented. Impact of not configuring the handler: The files specified by the knowledge processing fields of the Json type will not be parsed, and the inverted index table and vector table will not contain the file content (image vector representation is not affected). - SplitTextHandler: Splits a text field into two levels. - Level-1 chunk: used for inverted indexing - Level-2 segment: used for vector representation (embedding) Recommended configuration sequence: This handler must be configured before the TextEmbeddingHandler. Otherwise, segments will be missing in the vector representation phase, and the subsequent representation will fail. Impact of not configuring the handler: The inverted index table and vector table will not contain text content, and no text content can be returned during retrieval. - TextEmbeddingHandler: performs text vector representation for the segments generated by the SplitTextHandler and generates data for vector retrieval. This handler depends on the result of the SplitTextHandler. Recommended configuration sequence: Place this handler after the SplitTextHandler and before the ImageEmbeddingHandler. Impact of not configuring the handler: The text representation result will not be stored in the vector table, affecting semantic search. - ImageEmbeddingHandler: loads images from the image paths parsed based on the knowledge processing fields of the Json type and generates a vector representation of image features. Image processing does not depend on SplitTextHandler or TextEmbeddingHandler and is not used in the text inverted index table. It is independent of text processing. Recommended configuration sequence: Place this handler after the TextEmbeddingHandler to prevent the image path field from being mistakenly treated as text and incorporated into the representation, which will introduce noise. Impact of not configuring the handler: The image representation result will not be stored in the vector table, affecting image search. - MailSummaryHandler: uses the foundation model to perform semantic analysis on email content and generate a summary of the email content. Impact of not configuring the handler: The email summarization function will not be executed. - MailTodoHandler: uses the foundation model to perform semantic analysis on email content, identify whether the email contains to-dos, automatically extract key elements, and convert them into structured to-dos. Impact of not configuring the handler: The email to-do function will not be executed. - MailClassificationHandler: uses the foundation model to perform semantic analysis on email content and classify emails into one of the following categories: complaint, decision-making, approval, help-seeking, to-do, progress report, and others. The number and types of categories cannot be customized. However, the API caller can choose which categories to display on the GUI. Recommended configuration sequence: Place MailClassificationHandler after MailTodoHandler to use to-do information extraction for classification assistance. Impact of not configuring the handler: The email classification function will not be executed. |
| knowledgeProcess | Yes | Processing parameters, which are used to set knowledge processing parameters. You can select one or more fields for configuration based on the actual situation. After the corresponding fields are configured, the content in the corresponding subfields is mandatory. Partial configuration is not allowed. The following three fields are included: - embeddingModelCfg: representation model settings. If the embeddingModelCfg field is set in the knowledgeProcess field, the modelVersion field of the string type must also be set, indicating the version of the vector representation model. The value can contain a maximum of 100 characters. If the value is an empty string, the default version will be used. The field value must match the version of the deployed or supported model, and the version of the representation model for knowledge processing must be the same as that used for inference. The default value is default. - chunkSplitter: text splitting settings. If the chunkSplitter field is set in the knowledgeProcess field, the following fields must also be set: - chunkSize: maximum length of a chunk. The value is of the integer type. The value range is [100, 5000]. The default value is 3072. - segmentSize: maximum length of a segment in a chunk, which is the unit of vector representation. The value is of the integer type. The value range is [128, 512]. The default value is 300. - overlapRatio: overlap ratio between adjacent chunks. The value is of the floating point number type. The value range is (0.0, 0.3]. The default value is 0.1. These fields are used to control the text splitting policies, affecting the granularity of chunks and the continuity of context. If these fields are not set, the system uses the preceding default values. - perRecordLimit: file preprocessing limit. If the perRecordLimit field is set in the knowledgeProcess field, the following fields must also be set: - parseFileMaxCnt: maximum number of files that can be parsed in each record. The value is of the integer type. The value range is [0, 200]. The default value is 10. - textEmbeddingMaxCnt: maximum number of text segments that can be vectorized in each record. The value is of the integer type. The value range is [0, 200]. The default value is 50. Text segments that exceed the upper limit will not be vectorized. - imageEmbeddingMaxCnt: maximum number of images that can be processed in each record. The value is of the integer type. The value range is [0, 200]. The default value is 10. These parameters are used to limit the maximum processing scale of a single record during knowledge processing. If these parameters are not set, the system uses the default values. |
| mailAnalysisProcess | Yes | Email analysis parameter, which is used for email analysis settings. After the corresponding fields are configured, the content in their subfields is mandatory. Partial configuration is not allowed. A typical example is as follows: "mailAnalysisProcess": { "outputTableName": "mail_ai_insights", "inputFields": { "subject": "subject", "content": "content", "received_date": "received_date" }, "outputFields": { "summary": "summary", "todo": "todo", "classification": "classification" } } Field Description - outputTableName: name of the email analysis output table. The value is a string of 1 to 120 characters. - inputFields: names of the processed columns in the email analysis input table. The value must correspond to the column names in the knowledgeFields field. Currently, the following columns are included: subject (column name of the email subject in the email analysis input table), content (column name of the email content in the email analysis input table), and received_date (column name of the email receiving time in the email analysis input table). The value is a string of 1 to 255 characters. - outputFields: column names in the email analysis output table. Currently, the options are summary (column name of the summary generated by email analysis in the email analysis output table), todo (column name of the to-do task generated by email analysis in the email analysis output table), and classification (column name of the category generated by email analysis in the email analysis output table). The value is a string of 1 to 255 characters. Constraints on the email analysis function - Email analysis is performed regardless of whether the email has been read. The API caller determines whether to display the analysis result of a read email. - Email analysis is based only on the subject, body content, and receiving time of a single email, excluding attachments, images, and tables. - If the body is less than 45 bytes, the original text is directly returned as the email summary. - For canceled emails (starting with Cancel), the email to-do extraction is skipped, and the email category is directly set to others. - For emails with reply/forward content, only the latest non-empty content block of the reply/forward is processed. Historical content is not processed. Example of email analysis results - Email summary: summary text, for example, a project progress synchronization meeting will be held at 3:00 p.m. this Wednesday to report the development progress of each module, clarify issues and directions, understand the progress of each module, organize risk discussions, specify owners and time limits, arrange the work plan for the next week, optimize resource allocation, and ensure reasonable use of funds. - Email to-do: JSON string, for example, {"todo_list": [{"content":"Attend the project progress synchronization meeting at 3:00 p.m. this Wednesday","end_time":"","start_time":"2026-04-19 15:00:00"}]}. The time format is YYYY-MM-DD HH:MM:SS (24-hour format). If there is no time, start_time or end_time is an empty string. If no to-do task is extracted, the analysis result is an empty string. More than one to-do task may be extracted. That is, the number of elements in the todo_list array exceeds 1. - Email classification: The classification result must be one of the predefined categories: complaint, decision-making, approval, help-seeking, to-do, progress report, and others. The number and types of categories cannot be customized. However, the API caller can choose which categories to display on the GUI. |
Configure the parameters of the data source database and preset data based on service requirements. The following provides sample code for your reference.
If the type field of the inline_files column in the schema example is set to Json and the path field is set to the path expression pointing to a URI, the knowledge processing capability will parse the URI value in the inline_files column of the database as the file path. The value of the inline_files column in the SQL statement for inserting data must be set to the object array of the file path shown in the sample code. Knowledge construction is performed based on the obtained file paths during knowledge processing.
Knowledge processing can be triggered only when the following conditions are met: The value of the name field specified for setting the relationalStore database creation or opening parameters is the same as the value of dbName in the schema file. The enableSemanticIndex field is set to true.
The table name used in the table creation statement must be the same as the value of tableName in the schema file, and the column name must be the same as the value of columnName.
let context = UIContext.getCallingScopeUIContext()?.getHostContext();
// Set the relationalStore database creation or opening parameters.
let knowledgeConfig: relationalStore.StoreConfig = {
name: 'test.db',// Name of the database where knowledge processing is triggered.
securityLevel: relationalStore.SecurityLevel.S1,
vector: false,
tokenizer: relationalStore.Tokenizer.CUSTOM_TOKENIZER,
enableSemanticIndex: true,
};
let sourceConfig: knowledgeProcessor.KnowledgeSourceConfig = {
rdbSource: knowledgeConfig
};
let config: knowledgeProcessor.KnowledgeProcessorConfig = {
sourceConfig: sourceConfig,
}; let sourceDbStore: relationalStore.RdbStore;
async initDBData() {
try {
await relationalStore.getRdbStore(context, knowledgeConfig)
.then((retriever:relationalStore.RdbStore) => {
sourceDbStore = retriever;
});
let createSourceTable = 'CREATE TABLE IF NOT EXISTS mail (' +
'id INTEGER PRIMARY KEY,' +
'subject TEXT,' +
'content TEXT' +
');';
await sourceDbStore.executeSql(createSourceTable);
let sqlInsert =
'INSERT INTO mail (subject, content) VALUES ("Live sports scenario", "content");'
await sourceDbStore.execute(sqlInsert);
console.info('InitModel success');
} catch (err) {
console.error('InitModel failed msg: ' + err.message + ' code: ' + err.code);
}
} You can call the getStatus() API to query the current knowledge processing status based on the service requirements.
async getStatus() {
try {
// Obtain the knowledge processing object.
let processor = await knowledgeProcessor.getKnowledgeProcessor(context, config);
console.info('GetStatus getKnowledgeProcessor success');
if (processor) {
await processor.getStatus();
console.info('GetStatus success');
}
} catch (err) {
console.error('GetStatus failed msg: ' + err.message + ' code: ' + err.code);
}
} You can call the startProcess(option: KnowledgeProcessConfig) API to start knowledge processing based on service requirements.
async startProcess() {
try {
// Obtain the knowledge processing object.
let processor = await knowledgeProcessor.getKnowledgeProcessor(context, config);
console.info('StartProcess getKnowledgeProcessor success');
// Start knowledge processing.
let processMode: knowledgeProcessor.KnowledgeProcessMode = knowledgeProcessor.KnowledgeProcessMode.INVERTED_INDEX;
let processconfig: knowledgeProcessor.KnowledgeProcessConfig = {
mode: processMode,
};
if (processor) {
await processor.startProcess(processconfig);
console.info('StartProcess success');
}
} catch (err) {
console.error('StartProcess failed msg: ' + err.message + ' code: ' + err.code);
}
} You can call the stopProcess() API to stop knowledge processing based on service requirements.
async stopProcess() {
try {
// Obtain the knowledge processing object.
let processor = await knowledgeProcessor.getKnowledgeProcessor(context, config);
console.info('StopProcess getKnowledgeProcessor success');
if (processor) {
await processor.stopProcess();
console.info('StopProcess success');
}
} catch (err) {
console.error('StopProcess failed msg: ' + err.message + ' code: ' + err.code);
}
} You can call the cleanKnowledgeData(context: common.BaseContext, config: KnowledgeProcessorConfig) API to clear the knowledge base based on service requirements. Note: Use this function based on the constraints and restrictions.
async cleanKnowledgeData() {
try {
// Clear the knowledge base.
await knowledgeProcessor.cleanKnowledgeData(context, config);
console.info('CleanKnowledgeData success');
} catch (err) {
console.error('CleanKnowledgeData failed msg: ' + err.message + ' code: ' + err.code);
}
} The email intelligent analysis handler can call the getStatus() API to query the current knowledge processing status. Before using this handler, complete the following configurations in KnowledgeProcessorConfig:
import { BusinessError } from '@kit.BasicServicesKit';
import { relationalStore } from '@kit.ArkData';
import { knowledgeProcessor } from '@kit.DataAugmentationKit';
import { localChatModel } from '@kit.DataAugmentationKit'
class MockLLMEngine implements knowledgeProcessor.ChatLLM {
async chat(query: string): Promise<string> {
console.info(`[LLM] Chat query: ${query}`);
const questionInfo: localChatModel.QuestionInfo = {
questionId: 1,
content: query
};
const localConfig: localChatModel.Config = {
isStream: false
};
return new Promise<string>((resolve) => {
localChatModel.chat(questionInfo, localConfig, (err: BusinessError, ans: localChatModel.Answer) => {
if (err) {
console.error('[LLM] Chat failed:', err.message);
resolve(""); // Resolve even if the operation fails to prevent the caller from being suspended permanently.
} else {
console.info(`[LLM] Chat done: ${ans.content}`);
resolve(ans.content); // Send the result returned by the foundation model.
}
});
});
}
}
// Asynchronous function for obtaining the knowledge processing status. Call this function based on the service requirements.
async function getStatus() {
let context = getContext();
// Set the relationalStore database creation or opening parameters.
const storeConfig: relationalStore.StoreConfig = {
name: 'testmail_store.db', // The value must be the same as that of dbName in step 1.
securityLevel: relationalStore.SecurityLevel.S1,
enableSemanticIndex: true,
tokenizer: relationalStore.Tokenizer.CUSTOM_TOKENIZER
};
let knowledgeSourceConfig: knowledgeProcessor.KnowledgeSourceConfig = {
rdbSource: storeConfig,
};
let myLLM = new MockLLMEngine();
let knowledgeProcessorConfig: knowledgeProcessor.KnowledgeProcessorConfig = {
sourceConfig: knowledgeSourceConfig,
llm: myLLM,
properties: "{\"userName\": \"John\", \"maxCtxLen\": 30000}",
}
try {
// Obtain the knowledge processing object.
const processor = await knowledgeProcessor.getKnowledgeProcessor(context, knowledgeProcessorConfig);
// Obtain the knowledge processing status.
const status: knowledgeProcessor.ProcessorStatus = await processor.getStatus();
return status;
} catch (err) {
console.error("Error: " + err.message + " code: " + err.code);
return undefined;
}
}