Claude Example
The code below is a simple example of a process sending a prompt to Claude via Anthropic's Messages API 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 Anthropic API key, stored as a Secret rather than hardcoded in the process.
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 apiKey = security.getSecret("ANTHROPIC_API_KEY");
const response = web.post("https://api.anthropic.com/v1/messages", {
"Content-Type": "application/json",
"x-api-key": apiKey,
"anthropic-version": "2023-06-01"
}, {
model: "claude-sonnet-5",
max_tokens: 500,
system: "You are a financial analyst assistant.",
messages: [
{ role: "user", content: "Summarise this month's revenue in plain English: $1.2M, up 8% on last month." }
]
});
if (response.status >= 200 && response.status < 300) {
const body = JSON.parse(response.body);
const message = body.content[0].text;
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.');
}