logo

NJP

Code Assist - quick start and prompting guide

New article articles in ServiceNow Community · Jun 26, 2025 · article

Now Assist for Code enhances ServiceNow developer productivity when scripting by streamlining common coding tasks and adhering to best practices. The latest updates introduce powerful capabilities, allowing developers to generate, edit, explain, and autocomplete code efficiently

Install and activate Code Assist skills

To install and activate the Code Assist, see the installation instructions in the docs site (servicenow.com/docs).

  1. Install/upgrade Now Assist for Creator parent application.
    • Now Assist for code generation will be installed as a dependency.
  2. Activate the Code Assist skills in Now Assist Admin.
    • Code Assist AutoComplete
    • Code Assist Summarization
    • Code Assist Edit
    • Code Assist Generation
  3. (Optional) Choose the LLM.
    • Under Now Assist Admin > Settings > Manage LLMs. Scroll to Code Assist and choose a Provider.

Now that the Code Assist skills are activated, developers will need the "now.assist.creator" role to use Code Assist in script fields. Simply pause after typing to trigger autocomplete, or manually call Now Assist by using the command/control + / shortcut, or by clicking the sparkle ✨ Now Assist icon.

Code Assist AutoComplete

Introduced in March 2025 (v27.1.2), Now Assist for Code now supports inline autocompletion, speeding up coding workflows. This feature:

  • Predicts and suggests the next logical piece of code as you are typing
  • Works with both GPT-4o and NowLLM models
  • Provides context-aware suggestions via Retrieval Augmented Generation (RAG) - including details on scripts and tables in your scope.

To use autocompletion when scripting, pause after typing. After a few seconds, autocompletion will provide a contextually-aware suggestion to complete the code.

Example: Code Autocompletion in Action

A developer starts typing:

RobertNinness_0-1750927770832.png

Autocompletion keeps your momentum high by suggesting next steps and reduces repetitive coding tasks, improving speed, accuracy, and best practice adherence.

Code Assist Edit

Introduced in November 2024 with version 26.1.7 - Code Edit enhances developers' ability to refine, optimize, and standardize existing ServiceNow scripts. This feature allows for structured improvements, including performance optimization, validation enhancements, improved logging, and maintainability upgrades.

Code Edit can be used to:

  • Improve validation by strengthening input checks and adding specificity to regex validation.
  • Enhance error handling with more descriptive error messages.
  • Refactor variable names to be more consistent, meaningful, and readable.
  • Optimize database performance by refining queries, minimizing inefficient loops, and reducing redundant operations.
  • Improve logging and debugging by adding structured logging to capture errors, execution, and key outputs.
  • Increase maintainability with detailed inline comments for easier collaboration.

Improved validation and error handling

Now Assist for Code helps enforce stricter input validation, regex checks, and error handling to ensure robustness in ServiceNow applications.

Example prompts

🧑‍💻Add input validation to ensure the user email is not empty and follows a valid format

if (!email || !email. Match(/[\s@]+@[\s@]+\.[\s@]+$$/)) { gs.addErrorMessage("Please enter a valid email address."); return; }

🧑‍💻Wrap this code in a try/catch block and validate that user_id and task_id are present in the request body.

var requestBody = JSON.parse(request.body.data); var taskGr = new GlideRecord('task'); taskGr.get(requestBody.task_id); // Do something with the task

try { var requestBody = JSON.parse(request.body.data); if (!requestBody.user_id || !requestBody.task_id) { throw new Error("Invalid input: user_id and task_id are required."); } // Proceed with logic var taskGr = new GlideRecord('task'); if (!taskGr.get(requestBody.task_id)) { throw new Error("Task not found."); } // Do something with the task } catch (e) { response.setStatus(400);

Refactor variable names

To enhance readability and maintainability, Code Edit can rename variables for better clarity or apply a specific naming convention to variables.

Rename Variables for Clarity

🧑‍💻Improve variable names for readability in this loop

var gr = new GlideRecord('task'); gr.query(); while (gr.next()) { var n = gr.number; gs.info(n); }

var taskRecord = new GlideRecord('task'); taskRecord.query(); while (taskRecord.next()) { var taskNumber = taskRecord.number; gs.info(taskNumber); }

Apply a specific naming convention

🧑‍💻Standardize variable names to camelCase

var UserID = gs.getUserID(); var user_name = gs.getUserName();

var userId = gs.getUserID(); var userName = gs.getUserName();

Optimize database performance

Inefficient database queries can severely impact performance. Code Edit helps developers optimize GlideRecord queries, replace inefficient loops, and improve indexing strategies.

Replace Inefficient Queries with GlideAggregate

A common need is to get the count of records in a table by some criteria. The GlideRecord getRowCount method is popular, even in out of the box code, but it is inefficient because it must query the database, get all records that match the specified criteria, then loop through each of them in code even though it is not using the values of those records.

🧑‍💻 Optimize this code with GlideAggregate

function getCountOfIncidents(state) { var gr = new GlideRecord('incident'); gr.addQuery('state', state); gr.query(); return gr.getRowCount(); }

function getCountOfIncidents(state) { var ga = new GlideAggregate('incident'); ga.addQuery('state', state); ga.addAggregate('COUNT'); ga.query(); return ga.getAggregate('COUNT'); }

Savvy ServiceNow developers know that a GlideAggregate query is more efficient, but in more complex scenarios the syntax can be a bit dense and perhaps not used enough to be natural for every developer. Luckily Code Edit makes it simple to replace the existing logic of looping through every record with a database aggregate query which will return the count in one efficient step.

This is a highly simplified, if common example, but the performance benefits can be significant--check out Andrew Barnes' excellent deep-dive on the way GlideAggregate works and examples of how it improves performance

Extract repeated code into a reusable function

🧑‍💻 Refactor this date formatting logic into a reusable function

var now = new GlideDateTime(); var formattedNow = now.getDisplayValue(); var tomorrow = new GlideDateTime(); tomorrow.addDaysLocalTime(1); var formattedTomorrow = tomorrow.getDisplayValue();

function getFormattedDate(offsetDays) { var dt = new GlideDateTime(); dt.addDaysLocalTime(offsetDays); return dt.getDisplayValue(); } var formattedNow = getFormattedDate(0); var formattedTomorrow = getFormattedDate(1);

Improve logging and debugging

Debugging is faster with structured logging that captures key execution details.

Script execution timing

🧑‍💻 Add logging to measure how long this script takes to run

var gr = new GlideRecord('problem'); gr.query(); while (gr.next()) { // process problem }

var start = new Date().getTime(); var gr = new GlideRecord('problem'); gr.query(); while (gr.next()) { // process problem } var end = new Date().getTime(); gs.info("[Execution Time] Problem processing took " + (end - start) + " ms");

Log errors with context

🧑‍💻 wrap the loop code in a try/catch and log errors with record context

var gr = new GlideRecord('change_request'); gr.query(); while (gr.next()) { // risky operation }

var gr = new GlideRecord('change_request'); gr.query(); while (gr.next()) { try { // risky operation } catch (e) { gs.error("[Change Error] ID: " + gr.sys_id + ", Number: " + gr.number + ", Error: " + e.message); } }

Enhancing Code Readability with Comments

Well-commented code improves maintainability, especially in large projects.

Add clarity to a Scripted REST API

🧑‍💻 add comments to explain what this Scripted REST API is doing

var data = JSON.parse(request.body.data); var user = new GlideRecord('sys_user'); user.get(data.user_id); response.setBody(user.name);

// Parse the incoming request body to extract user_id var data = JSON.parse(request.body.data); // Retrieve the user record from the sys_user table var user = new GlideRecord('sys_user'); user.get(data.user_id); // Return the user's name in the response response.setBody(user.name);

Explain business rule conditions

🧑‍💻 add comments to explain the logic in this Business Rule

if (current.state == 3 && current.priority == 1) { current.escalated = true; }

// If the incident is in 'On Hold' state and has a high priority, // mark it as escalated if (current.state == 3 && current.priority == 1) { current.escalated = true; // Code Assist is trained to know what 3 and 1 mean with respect to state and priority

With Code Edit, developers can enhance, refactor, and optimize ServiceNow scripts efficiently. By improving validation, query performance, variable management, and logging, Code Edit helps create cleaner, faster, and more maintainable code.

Code Explain

Introduced in February 2025 with version 27.0.0, Now Assist for Code now provides the "Summarize Code" and "Explain This Code" features, allowing developers to quickly understand what a script does, saving time -- especially for complex, large, or older scripts.

  • "Summarize Code": Provides a high-level overview of the script’s functionality.
  • "Explain This Code": Breaks down the logic step-by-step for deeper understanding.

This feature is currently only available to users who have GPT-4o enabled as the default model for Now Assist for Code. Now Assist for Code version 27.0.0 introduced the ability to select GPT-4o as an instance-wide setting via Now Assist for Code system properties [name the system property]. By default, new installations of Now Assist for Code will be set to NowLLM.

To use Code Explain, highlight the code for which you would like an explanation, click the Quick Action button and then select either Summarize Code or Explain this Code.

RobertNinness_0-1750928694387.png

Code Generation

Now Assist for Code enables developers to generate well-formatted, best-practice-compliant code with precise prompts. It provides context-aware suggestions, making development faster and more accurate.

Effective Prompting for Code Generation

The quality of AI-generated code depends on how well the prompt is structured. Clear, specific prompts yield the best results, while vague or overly complex prompts may lead to suboptimal suggestions.

Example: Poor Prompt

🧑‍💻 Return the date and time

This lacks specificity, forcing the model to make assumptions about format, time zone, and user context.

Example: Improved Prompt

🧑‍💻 Write a function that returns the current date and time of a given user in the format YYYY-MM-DD HH:MM AM/PM specific to the user’s time zone.

RobertNinness_1-1750928755503.png

This function correctly retrieves the user’s time zone and returns the localized date and time.

Avoiding Overly Complex Chained Prompts

A single prompt that chains multiple tasks may introduce errors or inconsistencies. For example:

🧑‍💻 Depending on if a user is a VIP, set the incident priority to 1 automatically and send an email to "vip@concierge.com" with the details of the incident. Also send an email to the user who created the incident with the subject "We're on it!"

RobertNinness_2-1750928849710.png

A better approach is to break it down into sequential tasks, ensuring each part is correctly handled. This way if one part of the result is incorrect it doesn't cascade to subsequent results.

Additional Resources

Now Assist for Code generation documentation

Share your prompt tips below

If you've found other neat ways to achieve a specific goal with your prompts, let us know in the comments. We'd love to know how you are structuring your prompts to get the most out of Generative AI.

View original source

https://www.servicenow.com/community/now-assist-for-creator-articles/code-assist-quick-start-and-prompting-guide/ta-p/3300965