@cognigy/rest-api-client
Version:
Cognigy REST-Client
166 lines • 7.95 kB
JavaScript
import { __awaiter } from "tslib";
/* Custom modules */
import { getQuestionText } from "./getQuestionText";
import { getLLMEntityExtractPrompt, getLLMEntityExtractSystemMessage } from "../../../../helpers/generativeAI/generativeAIPrompts";
import { createLastConversationChatObject } from "../../../nlu/generativeSlotFiller/prompt";
/**
* Evaluates the answer of a question against its type
*/
export function evaluateQuestionAnswer({ cognigy, config }, overwriteAnswer) {
var _a, _b, _c, _d, _e, _f;
return __awaiter(this, void 0, void 0, function* () {
const { type, keyphraseTag, usePositiveOnly, regex: regexField, storeDetailedResults,
// for LLM Extract functionality
entityName, entityDescription, examples, llmEntityExtractLLMProviderReferenceId } = config;
const { api, input } = cognigy;
const answer = overwriteAnswer || input;
let result;
switch (type) {
case "text":
result = answer.text;
break;
case "date":
const foundDate = ((_a = answer.slots) === null || _a === void 0 ? void 0 : _a.DATE) ? true : false;
if (foundDate) {
if (answer.slots.DATE.length === 1 && answer.slots.DATE[0].start && !answer.slots.DATE[0].end)
result = answer.slots.DATE[0].start;
else if (answer.slots.DATE.length === 1 && answer.slots.DATE[0].start && answer.slots.DATE[0].end)
result = answer.slots.DATE[0];
else
result = answer.slots.DATE;
}
break;
case "temperature":
case "percentage":
case "money":
case "age":
case "url":
case "duration":
case "number":
case "email":
const foundSlot = ((_b = answer.slots) === null || _b === void 0 ? void 0 : _b[type.toUpperCase()]) ? true : false;
if (foundSlot) {
if (answer.slots[type.toUpperCase()][0] !== undefined)
result = answer.slots[type.toUpperCase()][0];
else
result = answer.slots[type.toUpperCase()];
}
break;
case "regex":
if (!answer.text) {
break;
}
try {
const regexSplitted = regexField && typeof regexField === "string" && /^\/(.*)\/(.*)$/.exec(regexField.trim());
const regex = (type === "regex" && regexSplitted !== null) ? regexSplitted[1] : null;
const flags = (type === "regex" && regexSplitted !== null) ? regexSplitted[2] : null;
const matches = answer.text.match(new RegExp(regex, flags));
if (matches && Array.isArray(matches) && matches.length > 0) {
result = matches[0];
}
}
catch (err) {
throw new Error("Error in Question node while validating RegExp");
}
break;
// Legacy this type was named 'keyphrase'. For Slot Fillers we use type 'slot'.
case "slot":
case "keyphrase":
let foundKeyphrase = null;
if (answer.slots[keyphraseTag]) {
// search through all keyphrases and find the first one that matches, either all or only positives
for (let key of answer.slots[keyphraseTag]) {
if (key.neg === false || usePositiveOnly === false) {
foundKeyphrase = key;
break;
}
}
}
if (foundKeyphrase) {
result = foundKeyphrase.keyphrase;
}
break;
case "yesNo":
if (answer.type === "pAnswer" || answer.type === "nAnswer") {
result = answer.type === "pAnswer" ? true : false;
}
break;
case "intent":
if (answer.intent) {
result = answer.intent;
}
break;
case "data":
if (answer.data && typeof answer.data === 'object' && Object.keys(answer.data).length > 0) {
result = answer.data;
}
break;
case "app":
if (((_e = (_d = (_c = answer.data) === null || _c === void 0 ? void 0 : _c._cognigy) === null || _d === void 0 ? void 0 : _d._app) === null || _e === void 0 ? void 0 : _e.type) === "submit") {
result = answer.data._cognigy._app.payload;
}
break;
case "de_lp":
case "iban":
case "us_ssn":
case "bic":
case "ipv4":
case "creditcard":
case "phonenumber":
result = api.matchPattern(type, answer.text, input.language);
break;
case "llm_entity":
const prompt = getLLMEntityExtractPrompt(entityName, entityDescription, examples, answer.text);
const options = {
prompt,
temperature: (config === null || config === void 0 ? void 0 : config.llmentityTemperature) || 0.7,
maxTokens: 1000,
timeoutInMs: (config === null || config === void 0 ? void 0 : config.llmentityTimeout) || 5000,
useCase: "promptNode",
detailedResults: true
};
if (llmEntityExtractLLMProviderReferenceId && llmEntityExtractLLMProviderReferenceId !== "default") {
options["llmProviderReferenceId"] = llmEntityExtractLLMProviderReferenceId;
}
options["chat"] = createLastConversationChatObject(cognigy.lastConversationEntries, getLLMEntityExtractSystemMessage(entityName, entityDescription, examples), 5, true);
try {
const response = yield api.runGenerativeAIPrompt(options, "gptPromptNode");
// find the entity in the response
result = (_f = response === null || response === void 0 ? void 0 : response.result) === null || _f === void 0 ? void 0 : _f[entityName];
if (!result) {
try {
result = JSON.parse(`{"${entityName}": ${response.result}`)[entityName];
}
catch (err) {
try {
result = JSON.parse(response.result)[entityName];
}
catch (err) {
result = null;
}
}
}
}
catch (err) {
api.log("error", `Error in evaluation of Question Node type LLM Entity Extract. Error was: ${err.message}`);
result = null;
}
break;
case "custom":
// the custom type is always true
result = true;
break;
}
// If we want detailed results, augment the result object accordingly
if (storeDetailedResults && result !== null && result !== undefined) {
result = {
"value": result,
"question": getQuestionText(config),
"timestamp": cognigy.input.currentTime.ISODate,
"answer": cognigy.input.text
};
}
return result;
});
}
//# sourceMappingURL=evaluateQuestionAnswer.js.map