Search Knowledge Base by Keyword

OpenAI ChatGPT Integration

Last review: March 2024

Goal:

Ask ChatGPT a question based on the data in a Legito Document and insert a response to an Element in the Document.

Instructions:

In your document, tag every input you will want to use in the prompt and then tag the output. Output Element can also be an Input Element, question, and select.

Create a script for the last tag that the user will fill in the document, so the script will be called when the user inserts all tags for the prompt and insert this script:

Script Example:

/*

TAG script that takes values from all inputElements with defined TAG, construct prompt with them and gets response
from OpenAI ChatGPS via API.
*/

 

// Prompt that will be sent to openAi will have this structure:
// “PROMPT [inputElement.getValue()] [inputElement.getValue()]…”
const PROMPT = ”;

const OUTPUT_TAG = ”;
//const OUTPUT_TAG = ‘ai_object_search_output’;
const IS_SELECTABLE_ELEMENT = false;

const OPENAI_API_KEY = ”;

getResponseFromOpenAI(PROMPT, OUTPUT_TAG, IS_SELECTABLE_ELEMENT, OPENAI_API_KEY);

 

/**
* Retrieves responses from OpenAI’s API based on the values of elements with specified tags in a document.
* It constructs a prompt using the values of input elements, sends this prompt to the OpenAI API, and sets the response
* as the value for output elements.
* @param outputTag
* @param prompt
* @param isSelectableElement
* @param apiKey
*/
function getResponseFromOpenAI(prompt, outputTag, isSelectableElement, apiKey) {
// MAIN
const outputElements = getElementsByTag(outputTag);
const uniqueTags = getTagsFromPrompt(PROMPT);
const tagValueMap = getValuesForTags(uniqueTags);
const completedPrompt = constructPrompt(PROMPT, tagValueMap);

let response = makeApiCallToOpenAI(completedPrompt, apiKey);

if(isSelectableElement){
response = parseResponseToQuestionElement(outputElements[0], response);
}

setValueOfOutputElements(outputElements, response);

// FUNCTIONS
function parseResponseToQuestionElement(outputElement, response){
const options = outputElement.getItems();
let optionsIndexes = [];
for(let option in options){
optionsIndexes.push(option);
}

LEGITO.debug.log(optionsIndexes);
LEGITO.debug.log(options);
let i = 0;
for (let index in options) {
let option = options[index];
let value = Object.values(option).join(”);
LEGITO.debug.log(value + ‘ === ‘ + response);
if (value === response ) {
response = optionsIndexes[i];
LEGITO.debug.log(response);
LEGITO.debug.log(options);
return response;
}
i++;
}
return response;
}

 

function setValueOfOutputElements(outputElements, value) {
for (let element of outputElements) {
element.setValue(value + ”);
}
}

function getElementsByTag(tag) {
const elementFinder = LEGITO.documentBuilder.event.createElementFinder();
const tags = LEGITO.documentBuilder.getTagsByName(tag);
return elementFinder.findElementsByTagsGlobal(tags);
}

function makeApiCallToOpenAI(prompt, apiKey) {
const restClient = LEGITO.restClient.create();

const headers = {
“Authorization”: “Bearer ” + apiKey, “Content-Type”: “application/json”
};

const body = {
model: “gpt-3.5-turbo”, messages: [{“role”: “system”, “content”: prompt}]
};

const response = restClient.post(‘https://api.openai.com/v1/chat/completions’, body, headers);
if (!response) {
throw new Error(‘ERROR: Error while calling API call, didnt recitative response’);
}

return response.data.choices[0].message.content;
}

function getTagsFromPrompt(prompt) {
const regex = /\[([^\]]+)\]/g;
let matches;
const tags = [];

while ((matches = regex.exec(prompt)) !== null) {
tags.push(matches[1]);
}

return […new Set(tags)];
}

function getValuesForTags(tags) {
let tagValueMap = new Map();

LEGITO.debug.log(tags);

for (let tag of tags) {
const elementFinder = LEGITO.documentBuilder.event.createElementFinder();
const tagsInner = LEGITO.documentBuilder.getTagsByName(tag);
LEGITO.debug.log(tagsInner);
const elements = elementFinder.findElementsByTagsGlobal(tagsInner);

LEGITO.debug.log(elements);

if (elements !== null && elements.length > 0) {
if(elements[0].getElementName() === ‘MoneyElement’){
const value = elements[0].getValue()[0] + ‘ ‘ + elements[0].getValue()[5];
tagValueMap.set(tag, value);
}

if(elements[0].getElementName() === ‘TextElement’){
const value = elements[0].getValue() + ”;
tagValueMap.set(tag, value);
}
} else {
LEGITO.debug.log(‘No elements found for tag ‘ + tag);
}
}

return tagValueMap;
}

function constructPrompt(prompt, tagValueMap) {
return prompt.replace(/\[([^\]]+)\]/g, (match, tag) => {
const value = tagValueMap.get(tag);
return value !== undefined ? value : match;
});
}
}

 

How to construct the prompt

In the script, change the const PROMPT = ‘’. This is the whole prompt what will the AI get via the API. If you want to use inputs in your prompt, insert it as the name of the tag in the square brackets, as shown below:

const PROMPT = ‘I am taking loan in size of [money_debt]. And if I cannot pay I will pay penalization in size of [money_percent] % of the loan. Is it too much or not much for standard rates?’;

How to set output tag


In the const OUTPUT_TAG = ‘’; just write the tag of the element/s you want to print the response to. Like:

const OUTPUT_TAG = ‘money_debt_percent_output’;

Where to set OpenAI API key

Just insert the OpenAI API key to const OPENAI_API_KEY = ‘’;
So it looks something like this:


const OPENAI_API_KEY = ‘dwadwadwadwad213213123sadadwafWgEyaez3ua7NlkXR1’;

How to set up the script for questions or selects in output

Change the IS_SELECTABLE_ELEMENT to true if the output is question or select. Otherwise set to false.

If the output is a Question or Select Element:


const IS_SELECTABLE_ELEMENT = true;

If the output Text or Text Input element:

const IS_SELECTABLE_ELEMENT = false;