Skip to main content
Updated in 2025.24 In a Code Node, you can use the functions of the api classes. These functions are also available in Extension Nodes. For example, you can use the api object to execute api.say().
Previously, you could use both actions and api. Now, only api is supported. Use api functions for all implementations.

CognigyScript

Use these functions to parse and evaluate CognigyScript expressions in text or conditions at run-time.
Parses CognigyScript text or conditions.Parameters
ParameterTypeDescription
textstringThe text containing CognigyScript expressions.
conditionbooleanThe CognigyScript condition to evaluate.
ReturnsstringExample
// Parse CognigyScript as text
const parsedText = api.parseCognigyScript(
"Hello {{cc.text}}, welcome!",
false
);
api.say(parsedText);

// Parse CognigyScript as a condition
const parsedCondition = api.parseCognigyScript(
"{{input.currentTime.year > 2024}}",
true
);

if (parsedCondition === "true") {
api.say("Condition is true");
} else {
api.say("Condition is false");
}
Evaluates a CognigyScript expression and returns a true or false value.CognigyScript allows you to embed expressions like {{context.value > 5}} within strings. This function extracts and evaluates such an expression, used in logic checks for Flows, conditions, or custom functions.This function is useful for dynamically checking conditions at run-time based on session data and information from the Input, Context, or Profile objects.Parameters
ParameterTypeDescription
conditionstringThe CognigyScript condition to evaluate.
ReturnsstringExample
const parseCognigyScriptCondition = api.parseCognigyScriptCondition(
"{{input.currentTime.year > 2024}}"
);

api.say(`${parseCognigyScriptCondition}`);
Parses and renders a text string containing CognigyScript expressions. Each CognigyScript expression, for example, {{cc.userName}}, is evaluated using the current execution context.Parameters
ParameterTypeDescription
textstringThe text containing CognigyScript expressions.
ReturnsstringExample
const output = api.parseCognigyScriptText("Hello {{cc.text}}, welcome to {{cc.city}}!");
api.say(`The current state is: ${output}`);

Contact Profiles

Use these functions to activate, deactivate, delete, merge, and update Contact Profiles during a conversation.
Activates the Contact Profile. Call this function to reactivate read and write operations on a previously deactivated Contact Profile.ParametersNoneReturnsvoidExample
// Reactivate a previously deactivated Profile
api.activateProfile();
Adds an entry to the memories array of the Profile object.Parameters
ParameterTypeDescription
memorystringThe text to add as a new entry in the memories array of the Profile object.
ReturnsvoidExample
api.addContactMemory("ppl");
Deactivates the Contact Profile. While the Contact Profile is deactivated, no data can be read from or written to the Contact Profile.ParametersNoneReturnsvoidExample
// Deactivate a Contact Profile
api.deactivateProfile();
Permanently deletes the Contact Profile from the system.ParametersNoneReturnsvoidExample
// Delete the Contact Profile
api.deleteProfile();
Merges the current Contact Profile with another one. This function is useful for combining duplicate Contact Profiles or moving data between users.Parameters
ParameterTypeDescription
contactIdstringThe ID of the Contact Profile to merge into.
ReturnsvoidExample
api.mergeProfile("c-89374201a7bd5a9e4");
Updates a value in the current Contact Profile.Parameters
ParameterTypeDescription
keystringThe key of the Contact Profile field to update.
valueanyThe value to set for the specified key.
ReturnsvoidExample
// Update the 'email' field of the current Contact Profile
api.updateProfile("email", "[email protected]");

// Update a custom string field
api.updateProfile("subscriptionStatus", "active");

// Update a numeric field
api.updateProfile("loyaltyPoints", 120);

// Update a boolean field
api.updateProfile("marketingConsent", true);

Context Object

Use these functions to read, write, and reset the Context object so you can store and manipulate conversation-scoped data across Nodes.
Adds a value to the Context object, either replacing an existing value or appending to it as an array.Parameters
ParameterTypeDescription
keystringThe key to add to the Context object.
valueanyThe value to assign to the key.
modestringDetermines how the value is added:
  • "simple" – replaces any existing value.
  • "array" – appends to the existing value as an array.
ReturnsvoidExample
// Simple mode: replaces existing value
api.addToContext("user.city", "Berlin", "simple");
// Context: { user: { city: "Berlin" } }

api.addToContext("user.city", "Munich", "simple");
// Context: { user: { city: "Munich" } }

// Array mode: appends to an array
api.addToContext("user.purchases", "book", "array");
// Context: { user: { purchases: ["book"] } }

api.addToContext("user.purchases", "laptop", "array");
api.addToContext("user.purchases", "coffee", "array");
// Context: { user: { purchases: ["book", "laptop", "coffee"] } }
Deletes the key and its value from the Context object.Parameters
ParameterTypeDescription
keystringThe key in the Context object to remove.
ReturnsvoidExample
api.deleteContext("user.city");
Retrieves data from the specified key in the Context object.Parameters
ParameterTypeDescription
keystringThe key to retrieve the data from the Context object.
Returnsany: The requested context data.Example
api.getContext("user.profile.name");
Retrieves the current conversation transcript, including the last 10 user inputs and the associated outputs from the AI Agent.Parameters
ParameterTypeDescription
modestringThis parameter is optional. Specifies the format of the returned transcript:
  • "string" – returns a plain text version of the conversation.
  • "json" – returns a structured array of message objects. This format is used by default.
optionsobjectThis parameter is optional. An object to configure the retrieved transcript data.
options.turnLimitnumberThis parameter is optional. Limits the transcript to the most recent N conversational turns. If the parameter is omitted, the full transcript is returned.
ReturnsEither the JSON array of conversation entries or the string representation.JSON:
[
    { "source":"user", "text":"hello" },
    { "source":"bot", "text":"You said: hello" },
    { "source":"user", "text":"you are an ai agent" },
    { "source":"bot", "text":"You said: you are an ai agent" },
    { "source":"user", "text":"show transcript" }
]
String:
- USER: hello
- BOT: You said: hello
- USER: you are an ai agent
- BOT: You said: you are an ai agent
- USER: show transcript
ExampleJSON:
// Get the transcript
const transcriptJson = api.getConversationTranscript({ turnLimit: 5 });

// Convert the JSON array to a string
const transcriptJsonPrint= JSON.stringify(transcriptJson, null, 2);

// Send it to the user
api.say(transcriptJsonPrint);
String:
// Get the transcript
const transcriptString = api.getConversationTranscript("string", { turnLimit: 1 });

// Send it to the user
api.say(transcriptString);
Removes information from the Context object either by deleting a key entirely or by removing specific entries from an array stored at that key.Parameters
ParameterTypeDescription
keystringThe key in the Context object to remove information from.
valueanyThe value to remove when using "array" mode. Ignored in "simple" mode.
modestringDetermines how the removal is performed:
  • "simple" – removes the key entirely.
  • "array" – removes only matching values from an array.
ReturnsvoidExample
// Simple mode: remove the entire key
api.removeFromContext("user.city", null, "simple");
// Context: { user: { city: undefined } }

// Array mode: remove specific values from an array
api.addToContext("user.purchases", "book", "array");
api.addToContext("user.purchases", "laptop", "array");
api.addToContext("user.purchases", "coffee", "array");

// Remove "laptop" from the purchases array
api.removeFromContext("user.purchases", "laptop", "array");
// Context: { user: { purchases: ["book", "coffee"] } }
Resets the Context object for the current conversation. All keys and values added during the conversation are removed.ParametersNoneReturnsvoidExample
// Remove all context data added during the conversation
api.resetContext();
Sets the value for a specific key in the Context object, replacing any existing value.Parameters
ParameterTypeDescription
keystringThe key in the Context object to set.
valueanyThe value to set for the key.
ReturnsvoidExample
api.setContext("user.city", "Berlin");

Encoding and Decoding

Use these functions to handle string encoding and decoding, such as converting text to Base64 for safe transmission or decoding Base64 strings back to UTF-8.
Base64 decodes a given string.Parameters
ParameterTypeDescription
datastringThe string to be decoded.
Returnsstring: The decoded string as UTF-8.Example
const decoded = api.base64Decode("SGVsbG8sIFdvcmxkIQ==");
api.say(`Decoded string: ${decoded}`);
// Output: "Hello, World!"
Base64 encodes a given string.Parameters
ParameterTypeDescription
datastringThe string to be encoded.
Returnsstring: The base64 encoded string.Example
const encoded = api.base64Encode("Hello, World!");
api.say(`Encoded string: ${encoded}`);
// Output: "SGVsbG8sIFdvcmxkIQ=="

Execution Control

Use these functions to control Flow execution, including adding conditional Entrypoints, jumping to specific Nodes or Flows, resetting overrides, stopping execution, and simulating new inputs.
Adds a conditional Entrypoint for the current conversation.If {condition} is met within the next {retentionTime} inputs, Flow execution starts at {entrypoint}.Parameters
ParameterTypeDescription
entrypointstringThe ID of the Node to execute when the condition evaluates to true.
retentionTimenumberThe number of times this conditional Entrypoint can trigger before it is automatically removed.
conditionstringA string expression evaluated. For example, input.text.includes('@') checks if the user input contains @.
ReturnsvoidExample
api.addConditionalEntrypoint({
entrypoint: "c40c50f3-2f51-422c-8a3e-748e7cc92ed0",
retentionTime: 2,
condition: "input.text.includes('@')"
});
Clears any active overrides for the next Node in the Flow.This function is useful when you’ve changed the next Node using the api.setNextNode function, and you want to return to the default Flow behavior.ParametersNoneReturnsvoidExample
// Imagine you previously used api.setNextNode("fallback-node") to redirect the Flow.
// Now, you want to clear that override so the Flow continues as originally defined.

api.resetNextNodes();
Sets the Node with the given nodeId to be executed immediately after the current one. This function is used by If and Lookup Nodes to select child Nodes based on their configuration.Parameters
ParameterTypeDescription
nodeIdstringThe ID of the Node to execute next.
newFlowIdstringThe ID of the Flow containing the target Node. This parameter is optional and is required if the target Node is in a different Flow.
ReturnsvoidExample
// The current Node is executing inside a Flow, and you want to control which Node should be executed next based on some logic.
// In this example, the execution will jump to a Node with the nodeId "c4c5c267-55d8-44ae-a123-f351d237f496" immediately after the current Node finishes.

api.setNextNode("c4c5c267-55d8-44ae-a123-f351d237f496");

// To continue the conversation in a different Flow after the current Node, specify both the target nodeId and the flowId.
// The Node with nodeId "c4c5c267-55d8-44ae-a123-f351d237f496" must be marked as an Entrypoint in the target Flow with flowId "67f511b11acdc139f91946b8".
// Execution will jump directly to that Node after the current one finishes.

api.setNextNode("c4c5c267-55d8-44ae-a123-f351d237f496", "67f511b11acdc139f91946b8");
Stops the execution of the Flow.ParametersNoneReturnsvoidExample
api.stopExecution();
Restarts Flow execution with a simulated input using the provided text and data.Parameters
ParameterTypeDescription
textstringA simulated input text
dataobjectA simulated input data object with optional fields and additional keys
ReturnsvoidExample
api.thinkV2( "Hello, how's the weather?", { location: "Berlin", units: "Celsius" });

Input and Output

Use these functions to enrich the Input object and send text or data responses to the user from a Code or Extension Node.
Adds a key-value pair to the Input object.Parameters
ParameterTypeDescription
keystringThe key to add to the Input object.
valuestringThe value to assign to the key.
ReturnsvoidExample
api.addToInput("username", "John Doe");
Executes a basic output to the contact, similar to the Say Node.Parameters
ParameterTypeDescription
textstringThe output text that is sent to the user.
dataanyThe output data that is sent to the user.
ReturnsvoidExample
// Send text with additional data
api.say("Hello, this is a message from the Code Node!", { customData: 123 });

// `api.output` is an alias of `api.say`
api.output("Hello, this is a message from the Code Node!", { customData: 123 });

Logging and Monitoring

Use these functions to write Project logs, send debug messages, inspect LLM token usage, track analytics steps, and configure sensitive logging behavior.
Completes the task. The information that the task has been completed is recorded and is available in Cognigy Insights and the Cognigy.AI OData endpoint.Parameters
ParameterTypeDescription
namestringThe name of the task.
ReturnsvoidExample
api.completeGoal("Order Pizza");
Forwards an error to the Ops Center Error page. Automatically sets the component to Flow and the subcomponent to FlowNodeExecution.Parameters
ParameterTypeDescription
titlestringThe title of the error to log.
projectIdstringThe ID of the Project where the error occurs.
ReturnsvoidExample
api.emitToOpsCenter({
    projectId: "6874becb018c552bc267cc51",
    title: "Something went wrong",
});
Retrieves the LLM token usage information for the current session.ParametersNoneReturns
{
    "llmDisplayName": string,
    "providerType": string,
    "modelType": string,
    "usage": {
    "inputTokens": number,
    "outputTokens": number
    }
}
Example
api.getLLMTokenUsageForSession();
Writes a message to the Project logs.Parameters
ParameterTypeDescription
levelstringThe log level. Cognigy.AI includes the following log levels:
  • info — general information about the normal operation of a Flow.
  • error — information about errors that occur during Flow execution.
  • debug — detailed information about Flow execution for debugging purposes.
textstringThe message to write to the logs.
ReturnsvoidExample
api.log("info", "This is an informational message.");
api.log("error", "An error occurred during Flow execution.");
api.log("debug", "Debugging details for Flow execution.");
Sends a debug message. The message is visible only in the Interaction Panel with activated debug mode.Parameters
ParameterTypeDescription
messagestring / objectThe debug message to log. When logging an object, use JSON.stringify to make it readable in the Interaction Panel.
headerstringAn optional label or header for the log message, used to categorize it in the debug panel.
ReturnsvoidExample
// Log a simple string
api.logDebugMessage("Flow started successfully", "Flow Info");

// Log multiple variables together
const sessionInfo = { sessionId: "abc123", timestamp: new Date().toISOString() };
const userData = { name: "Alice", age: 25 };

// Combine objects into one for logging
api.logDebugMessage(JSON.stringify({ sessionInfo, userData }, null, 2), "Session & User Info");
Configures masking of sensitive data in logs, analytics, and conversation content for the session.Parameters
ParameterTypeDescription
maskLoggingbooleanMasks sensitive information in system logs on the Logs page. Replaces fields like userId, text, and data with asterisks to protect user privacy.
maskAnalyticsbooleanMasks sensitive information in Input, Insights, and Analytics (inputText, inputData, userLanguageText, and user IP). Disables the Intent Trainer because input text isn’t stored. Can selectively ignore analytics using a Code Node.
maskIPAddressbooleanThis parameter is optional. Masks the user’s IP address in the Input object, Insights, and Analytics. IP addresses are replaced with asterisks and aren’t available via OData Analytics.
disableConversationsbooleanDisables logging of conversation content entirely. No conversation data will be stored.
disableIntentTrainerbooleanThis parameter is optional. Disables logging for the Intent Trainer, preventing user input from being stored or used for training intents.
traceIdstringThis parameter is optional. A unique ID for tracing this API call. Helps track requests in logs and diagnostics without affecting masking or logging behavior.
ReturnsvoidExample
api.setSensitiveLoggingSettings({
    maskLogging: true, // Mask sensitive information in conversation logs
    maskAnalytics: true, // Mask sensitive information in analytics and Insights
    maskIPAddress: true, // Optional: mask user IP addresses
    disableConversations: true, // Disable conversation logging entirely
    disableIntentTrainer: true // Disable logging for the Intent Trainer
    }, "trace-12345"); // Optional trace ID for debugging
Tracks a custom analytics step for the session. Useful for monitoring user interactions or workflow progress.Parameters
ParameterTypeDescription
stepLabelstringThe label of the analytics step to track.
ReturnsvoidExample
// Track that the user reached the "Checkout" step
api.trackAnalyticsStep("Checkout");

States

Use these functions to get, set, and reset the conversation State of a Flow.
Returns the current State of the conversation.ParametersNoneReturnsstringExample
// Get the current State of the Flow
const currentState = api.getState();

// Send the State to the user
api.say(`The current state is: ${currentState}`);
Resets the State of the Flow to the initial State.ParametersNoneReturnsvoidExample
api.resetState();
Updates the conversation State to a specified State.Parameters
ParameterTypeDescription
statestringThe State that should be activated.
ReturnsvoidExample
// Set the conversation state to "awaiting_input"
api.setState("awaiting_input");

// Verify by getting the current state
const currentState = api.getState();
api.say(`The current state is: ${currentState}`);

xApps

Use these functions to manage conversations with xApps.
Updates the state of the xApp Session for the current conversation. Only works if an xApp Session was started beforehand.Parameters
ParameterTypeDescription
appTemplateIdstringThe xApp template identifier. Can be a URL to a hosted xApp template, generic-html to load inline HTML with the xApp Page SDK, or null to close the active xApp Page.
appTemplateDataobjectThe data payload passed to the xApp Page. For generic-html, this must include an html field containing the HTML to render.
ReturnsvoidExample
// Load an xApp template hosted at a URL
api.setAppState("https://my-xapp-template-url", {
my: "xapp-template-data",
});

// Load a generic HTML xApp Page
const html = `
<html>
<body>
Hello, World!
<button type="button" onclick="SDK.submit({});">continue</button>
<script src="/sdk/app-page-sdk.js"></script>
</body>
</html>
`;

api.setAppState("generic-html", { html });

// Close the active xApp Page
api.setAppState(null, {});

Other

Use these functions to manage conversation behavior, such as adding Keyphrases, handling handovers, and localization settings.
Adds a new Keyphrase to a Lexicon.Parameters
ParameterTypeDescription
lexiconIdstringThe ID of the Lexicon to which the Keyphrase will be added.
keyphrasestringThe primary phrase to add to the Lexicon.
tagsstring[]An array of strings used to categorize or filter the Keyphrase.
synonymsstring[]An array of strings representing alternative phrases that should be recognized as the same Keyphrase.
dataobjectThis parameter is optional. The custom data associated with the Keyphrase.
ReturnsvoidExample
// Add a new keyphrase to the existing Lexicon
api.addLexiconKeyphrase(
  "6942550bf16d8343c6f1adec",
  "password reset",
  ["account", "security"], // tags
  ["reset password", "forgot password"], // synonyms
  {
    priority: "high",
    source: "dynamic",
  }
);
Evaluates a condition based on a rule configuration that follows the left, operand, right pattern. This function works similarly to the If Node. The left value is compared with the right value using the specified operator, for example, !=, >, includes. If the condition evaluates to true, the associated logic or transition is executed.Parameters
ParameterTypeDescription
leftstringThe primary value to be evaluated.
operandstringThe comparison operator used to evaluate the relationship between the left and right values. Supported operators:
  • eq – checks if values are equal. Example: 5 eq 5 → true
  • neq – checks if values aren’t equal. Example: 5 neq 3 → true
  • lt – left is less than right. Example: 3 lt 5 → true
  • lte – left is less than or equal. Example: 5 lte 5 → true
  • gt – left is greater than right. Example: 7 gt 5 → true
  • gte – left is greater than or equal. Example: 5 gte 5 → true
  • contains – left contains right. Example: "hello" contains "ell" → true
  • ncontains – left doesn’t contain right. Example: "hello" ncontains "xyz" → true
  • exists – checks if a value exists. Example: x exists → true if x is defined
  • nexists – checks if a value doesn’t exist. Example: x nexists → true if x is undefined
  • isyes – checks if a value is "yes". Example: "yes" isyes → true
  • isno – checks if value is "no". Example: "no" isno → true
.
rightstringThe reference value to compare against the left value. This parameter is ignored for operators that check only the state of the left value, such as exists, nexists, isyes, and isno.
ReturnsbooleanExample
api.evaluateRule({
    left: "hello world",
    operand: "contains",
    right: "hello"
});
Initiates a handover to a human agent or another system.Parameters
ParameterTypeDescription
textstringThe message to send to the user.
cancelIntentstringThe Intent that will be triggered if the user cancels the handover.
unavailablestringThe message shown to the user if no agent is available.
unsupportedChannelstringThe message shown if the current channel doesn’t support handover.
quickReplystringThe text for a quick reply button offered to the user.
chatwootInboxIdstringThe ID of the Chatwoot inbox where the conversation should be routed.
liveAgentInboxIdstringThe ID of the Live Agent inbox where the conversation should be routed.
ReturnsvoidExample
api.handover({
    text: "Connecting you to a human agent...",
    cancelIntent: "CancelHandover",
    unavailable: "No agents are available at the moment.",
    unsupportedChannel: "This channel doesn't support handover.",
    quickReply: "Talk to an agent",
    chatwootInboxId: "chatwoot_123",
    liveAgentInboxId: "liveagent_456"
});
Sets the Reference ID to specify which Locale is used for localization.Parameters
ParameterTypeDescription
localeReferenceIDstringThe Locale Reference ID to set.
ReturnsvoidExample
api.setLocaleReferenceId("b4dc8ff5-bd05-467a-a281-2514122c4aa2")
Sets a rating for the conversation to prefill a rating prompt with a specific value or update it based on other actions or user inputs. Using this function, you can collect feedback at specific steps.Parameters
ParameterTypeDescription
ratingnumberThe rating for the conversation: -1 for negative or 1 for positive.
commentstringAdditional information about the rating.
ReturnsvoidExample
api.setRating({
    rating: 1,
    comment: "The conversation was helpful."
});
Sets the time zone offset from UTC for the session, allowing time-related data to be interpreted correctly. You can view the applied time zone in the Input object under input.currentTime.timezoneOffset.Parameters
ParameterTypeDescription
offsetnumberThe time offset in hours.
ReturnsvoidExample
// Set the session timezone offset to UTC+4
api.setTimezoneOffset(4);

More Information