Use agents in the Script Editor
Using an agent in the Script Editor is similar to calling an API in the Script Editor.
Follow these steps to make use of an agent in a script:
-
Go to edit mode.
-
In the resources panel, open Agents and find the agent you want to use. Drag and drop it to the name of your script in the list of scripts in your project.
Result: You are prompted to provide a context name.
-
Open the code snippets to find example JS code on how to use your agent. You will be using the agent through a name like
agent.MyAgentName, whereMyAgentNameis the context name you set before.
Here is an example usage of agent Test in a script:
/*
This code snippet executes an agent.
*/
const opts = {
// Required: Set the input text
input: "Explain the saying 'A hog never jumps over a fence.'",
// Optional: Set variables
variables: {
var1: "hello",
},
// Optional: Set the user
user: {
id: req.user.id,
},
// Optional: Transmit files
files,
};
try {
// Execute the agent
const response = await agent.Test(opts);
// Log response data
log.info("AI response: ", response);
} catch (error) {
log.error("Error in request: ", error);
return fail();
}
Streaming responses
You can also enable streaming for the agent response. This allows you to process the response as it is being generated, which is useful for long-running tasks or for providing immediate feedback.
To enable streaming, set stream: true in the options object and provide callback
functions for the events you want to handle.
const opts = {
input: "Write a short story about a space adventure",
stream: true,
// Callback for each chunk of text received
onChunk: (chunk) => {
console.log("Received chunk:", chunk);
},
// Callback when the generation is complete
onFinish: (metadata) => {
console.log("Finished:", metadata);
},
// Callback when a tool execution starts
onToolStart: (metadata) => {
console.log("Tool started:", metadata);
},
// Callback when a tool receives input
onToolInput: (metadata) => {
console.log("Tool input:", metadata);
},
// Callback when a tool execution finishes
onToolFinish: (metadata) => {
console.log("Tool finished:", metadata);
}
};
try {
await agent.Test(opts);
} catch (error) {
log.error("Error in streaming request: ", error);
}