{"revision":"c10276e953456835cdbb1f3a60d58ae1980be353","document":{"id":24422,"path":"intelligent-experiences/servicenow-lens/ai-lens-action-service-api.md","title":"Script include - AILensActionService","bundle":null,"doc_type":null,"release":"australia","body":"\n# Script include - AILensActionService\n\nUse the AILensActionService script include together with Lens actions to leverage ServiceNow AI Lens as a service for extracting information from the provided images and getting answers to your questions.\n\nThis script include is part of the ServiceNow AI Lens \\(sn\\_ai\\_lens\\) store application and is located within the `sn_app_lens_core` scope.\n\nThis script include provides methods that enable the following:\n\n-   Calls Lens as a back-end service\n-   Analyzes and comprehends data from provided images\n-   Gets response from AI as per provided directions\n-   Does not require ServiceNow AI Lens desktop app\n\n**Parent Topic:**[ServiceNow AI Lens reference](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/intelligent-experiences/servicenow-lens/servicenow-lens-reference.md)\n\n## AILensActionService - AILensActionService\\(\\)\n\nCreates an AILensActionService instance.\n\n|Name|Type|Description|\n|----|----|-----------|\n|None| ||\n\nThe following example shows how to initialize AILensActionService.\n\n```\nvar lensService = new sn_app_lens_core. AILensActionService()\n```\n\n## AILensActionService - invokeLens\\(String lensActionId, String\\[\\] attachmentIds, String userPrompt, Object\\[\\] imageArr, Object inputJSON, Object\\[\\] additionalContext, Boolean skipACL\\)\n\nInvokes ServiceNow AI Lens as a service.\n\n<table id=\"table_v4d_qzt_lgc\" class=\"parameters\"><thead><tr><th>\n\nName\n\n</th><th>\n\nType\n\n</th><th>\n\nDescription\n\n</th></tr></thead><tbody><tr><td>\n\nlensActionId\n\n</td><td>\n\nString\n\n</td><td>\n\nSys\\_id of the Lens Actions record created for your use case, or you can select the out-of-the-box option that fits your requirements.Example: 842bfc8e37066210b97528c734924baf\n\nThis parameter is mandatory.\n\n</td></tr><tr><td>\n\nattachmentIds\n\n</td><td>\n\nString\\[\\]\n\n</td><td>\n\nArray of sys\\_ids for existing image attachments.Example: `[\"0067e66f93f022108319f9ed1dba108b\", \"0000e8a42c9a7110f877137af4eab4b5\"]`\n\nYou must pass either `attachmentIds` or `imageArr` parameter.\n\n</td></tr><tr><td>\n\nuserPrompt\n\n</td><td>\n\nString\n\n</td><td>\n\nAn instruction or question for AI to answer after analyzing the contents of the attachments.Example: `Analyze this production issue and create an incident ticket`\n\n</td></tr><tr><td>\n\nimageArr\n\n</td><td>\n\nObject\\[\\]\n\n</td><td>\n\nArray of objects containing name of the screenshot and base64 encoded image data.Example:\n\n```\n[\n    {\n        name: \"screenshot1.png\",\n        data: \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==\"\n    },\n    {\n        name: \"screenshot2.png\",\n        data: \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9Qz0AEYAJMgkU1f5kAAAAASUVORK5CYII=\"\n    }\n];\n```\n\nYou must pass either `attachmentIds` or `imageArr` parameter.\n\n</td></tr><tr><td>\n\ninputJSON\n\n</td><td>\n\nObject\n\n</td><td>\n\nAdditional JSON input parameters that you want to pass in the pre-processing script of the Lens action.**Note:** To use Multi-table schema mapping, you must pass at least one table name key and its corresponding value inside the input JSON. For example, \\{ 'tableName': 'sn\\_ent\\_model,sn\\_ent\\_asset' \\},\n\nExample:\n\n```\n{\n      \"type\" : \"object\",\n      \"properties\" : {\n        \"short_description\" : {\n          \"type\" : \"string\",\n          \"label\" : \"Short description\"\n        },\n        \"description\" : {\n          \"type\" : \"string\",\n          \"label\" : \"Description\"\n        },\n      },\n      \"required\" : [ \"short_description\", \"comments\" ],\n   }\n```\n\n</td></tr><tr><td>\n\nadditionalContext\n\n</td><td>\n\nObject\n\n</td><td>\n\nAn optional parameter that you can use to pass any extra key–value information while you're performing a Lens service call. The examples show the key–value information that you can pass.-   **Example**:\n\n    ```\n{IsFileUploadEnabled: true}\n    ```\n\n-   **Example**: As part of the Excel mapping services, you can pass key-value information to:\n\n    -   auto-map the column headers of an Excel file with ServiceNow table fields\n    -   auto-map Excel values to ServiceNow drop-down values\n    -   auto-map Excel values to referenced records in ServiceNow tables\nFor more information on the various key-values of the Excel mapping service, see [Key-values of the Excel auto-mapping services](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/intelligent-experiences/servicenow-lens/ai-lens-action-service-api.md)\n\n**Key-values of the Excel auto-mapping services**\n\n    -   **Schema mapping** — Maps Excel column headers to ServiceNow table fields and identifies the field type of each mapped field. You can also use this option to map Excel column headers from a single sheet to multiple ServiceNow tables. Key-values for schema mapping are:\n\n        -   `mappingStrategy`: Set to `'schema_mapping'`\n        -   `rowContextSize`: Number of sample data rows to use for mapping context. Default: `10`.\n        -   `randomizeRowOrder`: If `true`, Lens selects rows randomly from the Excel file. If `false`, Lens uses rows in order from the top.\n        -   `sheetName`: Name of the Excel Sheet. If no name is specified, the first sheet is chosen by default.\n        -   `headerRowNumber`: The row number from which the header with column names start with.\n        ```\n**Request example**: var response = new sn_app_lens_core.AILensActionService().invokeLens(  \n     'b7fbd8694730c310dbc4964a516d431e',  \n     ['0c0b1c6d4730c310dbc4964a516d43f2'],  \n     '', [], {},  \n     true, {\"mappingStrategy\":\"schema_mapping\", sheetName: \"Incident Data\",headerRowNumber: 2,\"rowContextSize\":5,\"randomizeRowOrder\":false \n\n} \n);    \ngs.info(\"Lens Response : \" + JSON.stringify(response));\n\n**Response example**: {\n  \"Owner\":           { \"type\": \"string\",     \"mappings\": { \"0.8\": [\"assigned_to\", \"parent\", \"epic\"] } },\n  \"Age\":             { \"type\": \"integer\",    \"mappings\": { \"0.8\": [\"story_points\"] } },\n  \"Status\":          { \"type\": \"choice\",     \"mappings\": { \"0.8\": [\"state\", \"priority\"] }, \"choiceValues\": [\"Retired\", \"On Boarding\", \"Working\"] },\n  \"Start Date\":      { \"type\": \"glide_date\", \"mappings\": { \"1.0\": [\"expected_start\"], \"0.8\": [\"due_date\"] } },\n  \"End Date\":        { \"type\": \"glide_date\", \"mappings\": { \"1.0\": [\"due_date\"], \"0.8\": [\"expected_start\"] } },\n  \"Project Assigned\":{ \"type\": \"string\",     \"mappings\": { \"0.8\": [\"short_description\", \"task\", \"description\"] } }\n}\n        ```\n\n**Multi-table schema mapping**\n\nMaps Excel column headers from a single sheet to multiple ServiceNow tables simultaneously. ServiceNow AI Lens identifies the relevant fields in each table for each Excel column header and maps the data accordingly.\n\n**Request example**\n\n        ```\nvar response = new sn_app_lens_core.AILensActionService().invokeLens(\n    \"3290a3dc2b420310d666fe3db891bfb8\",\n    [\"566997542b46c310a371f33ec891bfbc\"],\n    \"\",\n    {},\n    {\n        'tableName': 'sn_ent_model,sn_ent_asset'\n    },\n    true,\n    {\n        \"mappingStrategy\": \"schema_mapping\",\n        \"rowContextSize\": 5,\n        \"randomizeRowOrder\": false,\n        \"headerRowNumber\": 2\n    }\n);\ngs.info(\"Overall Lens Response \" + JSON.stringify(response));\nvar res = JSON.parse(response.lensResponse);\ngs.info(\"Mapped Object\" + JSON.stringify(res, null, '   '));\n\n        ```\n\n    -   **Choice mapping** — For fields identified as Choice type, maps the unique values from the Excel column to the valid choice values in the ServiceNow table field. Key-values for Choice mapping are:\n\n        -   `mappingStrategy`: Set to `'choice_mapping'`.\n        -   `columnConfigs`: An array of objects that specifies the ServiceNow choice field and the corresponding Excel column to map, including the field name, column header, and optionally the cell values to use instead of reading from the file.\n        ```\n**Request example**: { \n    mappingStrategy: 'choice_mapping', \n\n    SheetName:’Incident Data’, \n\n    SheetNameheaderRowNumber:2, \n    columnConfigs: [ \n        { field: 'priority', name: 'Priority' }, \n        { field: 'state',    name: 'Ticket Status' } \n    ] \n} \n**Response example**: [ \n  { \n      \"name\": \"Priority\", \n      \"field\": \"priority\", \n      \"mappings\": [ \n        { \"key\": \"High\",   \"value\": \"1\", \"label\": \"1 - Critical\", \"score\": 1.0 }, \n        { \"key\": \"Medium\", \"value\": \"3\", \"label\": \"3 - Moderate\", \"score\": 0.9 } \n      ] \n  } \n]\n        ```\n\n**Multi-column to single field choice mapping**\n\nMaps multiple Excel column headers and their values to a single ServiceNow field. This is useful when related data from separate columns should be consolidated into one field.\n\n**Request example**\n\n        ```\nvar response = new sn_app_lens_core.AILensActionService().invokeLens(\n    \"4b50a72c2b694710c18df2086e91bf84\",\n    [\"e782e364936103105357f1cfb903d682\"],\n    \"\",\n    {},\n    {},\n    true,\n    {\n        \"mappingStrategy\": \"choice_mapping\",\n        \"columnConfigs\": [\n            { \"field\": \"location\", \"name\": \"city\" },\n            { \"field\": \"location\", \"name\": \"zip\" },\n            { \"field\": \"location\", \"name\": \"state\" }\n        ]\n    }\n);\ngs.info(\"response \" + JSON.stringify(response, null, '   '));\n\n        ```\n\n**Note:** Multi-column to single field mapping also works with Reference mapping.\n\n    -   **Reference mapping** — Maps Excel cell values to the corresponding ServiceNow reference field records. Key-values for Reference mapping are:\n\n        -   `mappingStrategy`: Set to `'reference_mapping'`.\n        -   `columnConfigs`: Configuration for the specific column being mapped, including the source column name and the target reference table details.\n        ```\n**Request example**: var response = new sn_app_lens_core.AILensActionService().invokeLens( \n    'b7fbd8694730c310dbc4964a516d431e', \n    ['0c0b1c6d4730c310dbc4964a516d43f2'], \n    '', [], {}, \n    true, { \n        mappingStrategy: 'reference_mapping', \n\n  SheetName:’Incident Data’, \n\n  SheetNameheaderRowNumber:2, \n\n  columnConfigs: [{ \n            field: 'assignment_group', \n            name: 'Assignment Group', \n        }] \n    } \n); \n\n**Response example**: [ \n  { \n      \"name\": \"Assignment Group\", \n      \"field\": \"assignment_group\", \n      \"mappings\": [ \n        { \"key\": \"IT Help Desk\",  \"value\": \"abc123...\", \"label\": \"IT Help Desk\",  \"score\": 1.0  } \n      ] \n  } \n]\n        ```\n\n\n</td></tr></tbody>\n</table><table id=\"table_w4d_qzt_lgc\" class=\"returns\"><thead><tr><th>\n\nType\n\n</th><th>\n\nDescription\n\n</th></tr></thead><tbody><tr><td>\n\n&lt;object&gt;\n\n</td><td>\n\nReturned success object```\n{\n    \"status\": \"success\",\n    \"lensResponse\": \"{\\\"short_description\\\":\\\"Service Degradation Error in Order Processing System\\\",\\\"description\\\":\\\"The Order Processing API v2.1 encountered a service degradation issue in the Production environment.\\\" }\"\n}\n```\n\n</td></tr><tr><td>\n\nerror\n\n</td><td>\n\nReturned error object```\n{\n    \"status\": \"error\",\n    \"error\": {\n        \"errorType\": \"Execution Error\",\n        \"message\": \"Detailed error message here\"\n    }\n}\n```\n\n</td></tr></tbody>\n</table>This example shows how to call Lens service from a script block.\n\n```\nvar lensActionId = \"cd6570cdf36a2210b9751f09f6968c42\";\nvar attachmentIds = [\"3fe930093b626210aba1fadc73e45a38\", \"0000e8a42c9a7110f877137af4eab4b5\"];\nvar userPrompt = \"Analyze this production issue and create an incident ticket\";\nvar imageArr = [\n    {\n        name: \"screenshot1.png\",\n        data: \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==\"\n    },\n    {\n        name: \"screenshot2.png\",\n        data: \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9Qz0AEYAJMgkU1f5kAAAAASUVORK5CYII=\"\n    }\n];\nvar inputJSON = {\n      \"type\" : \"object\",\n      \"properties\" : {\n        \"short_description\" : {\n          \"type\" : \"string\",\n          \"label\" : \"Short description\"\n        },\n        \"description\" : {\n          \"type\" : \"string\",\n          \"label\" : \"Description\"\n        },\n      },\n      \"required\" : [ \"short_description\", \"comments\" ],\n   }\nvar additionalContext = {\n      IsFileUploadEnabled: true};\n\n // Call the method\nvar result = new sn_app_lens_core. AILensActionService().invokeLens(lensActionId, attachmentIds, userPrompt, imageArr, inputJSON, skipACL, additionalContext);\n \n// Handle the response\nif (result.status === 'success') {\n    var response = JSON.parse(result.lensResponse);\n    gs.info(\"AI Lens Analysis Complete:\");\n    gs.info(\"Title:\", response.short_description);\n    gs.info(\"Description:\", response.description);\n} else {\n    gs.error(\"Error occurred:\", result.error.message);\n}\n```\n\n"}}