Skip to content

ChatGPT Example

The code below is a simple example of a process sending a prompt to ChatGPT (via an OpenAI-compatible chat completions endpoint, e.g. Azure OpenAI) and reading back the response. This authenticates with an API key rather than MODLR's built-in OAuth 2.0 flow, so this is an Advanced Integration.

INFO

This process requires an OpenAI/Azure OpenAI API key, stored as a Secret, and your chat completions endpoint URL, stored as a Model Variable.

Process Code

js
function pre() {
    // This function is called once before the process is executed.
    // Use this to setup prompts.
    script.log('process pre-execution parameters parsed.');
}

function begin() {
    // This function is called once at the start of the process
    script.log('process execution started.');

    const endpoint = script.variableGet("openai.endpoint"); // e.g. your Azure OpenAI chat completions URL
    const apiKey = security.getSecret("OPENAI_API_KEY");

    const response = web.post(endpoint, {
        "Content-Type": "application/json",
        "api-key": apiKey
    }, {
        messages: [
            { role: "system", content: "You are a financial analyst assistant." },
            { role: "user", content: "Summarise this month's revenue in plain English: $1.2M, up 8% on last month." }
        ],
        temperature: 0.2,
        max_tokens: 500
    });

    if (response.status >= 200 && response.status < 300) {
        const body = JSON.parse(response.body);
        const message = body.choices[0].message.content;
        console.log(message);
    } else if (response.error) {
        // An error occurred while sending the request (e.g., network error, timeout, etc.).
        console.log("Error occurred while sending the request: " + response.error);
    } else {
        // The request failed with a non-success status code.
        console.log("Request failed with status code: " + response.status);
        console.log(response.body);
    }
}

function data(record) {
    // This function is called once for each line of data on the second cycle
    // Use this to build dimensions and push data into cubes
}

function end() {
    // This function is called once at the end of the process
    script.log('process execution finished.');
}