daggerai
Version:
A simple and powerful Typescript based agent framework to help businesses thrive in the AI Agent revolution.
214 lines • 8.28 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Task = void 0;
const helpers_1 = require("./helpers");
const node_1 = require("./node");
const parser_1 = require("./parser");
const prompts_1 = require("./prompts");
const tool_1 = require("./tool");
class Task extends node_1.Node {
type = 'task';
agent;
name;
description;
expectedOutput;
tools;
memories;
inputs;
llm;
// the max attemps to execute this task
maxAttempts = 10;
constructor(params) {
super();
this.id = params.id || '';
this.name = params.name;
this.description = params.description;
this.agent = params.agent;
this.expectedOutput = params.expectedOutput;
this.tools = params.tools || [];
this.inputs = params.inputs || [];
this.memories = params.memories || [];
this.llm = params.llm;
}
async execute(squad) {
let llmPrompt = this.buildInitialPrompt(squad);
const llmParser = new parser_1.SquadResponseParser();
const toolRunner = new tool_1.ToolRunner(this.tools, squad.events);
squad.events.emit('agent.started', {
agent: this.agent.id,
name: this.name,
task: this.id,
output: `Executing task *${this.name}*`,
});
let intermediateSteps = [];
let iterations = 0;
let sources = [];
while (this.shouldContinue(iterations)) {
if (squad.verbose) {
(0, helpers_1.logWithColor)(`Running Iteration ${iterations}`, 'blue');
}
try {
let promptWithSteps = llmPrompt + this.buildIntermediateStepsPrompt(intermediateSteps);
if (squad.verbose) {
(0, helpers_1.logWithColor)(`LLM Prompt: ${promptWithSteps}`, 'yellow');
}
squad.events.emit('agent.thinking', {
agent: this.agent.id,
name: this.name,
task: this.id,
output: '',
});
const response = await this.llm.invoke(promptWithSteps);
if (squad.verbose) {
(0, helpers_1.logWithColor)(response, 'green');
}
const nextStep = llmParser.parse(response);
if (squad.verbose) {
(0, helpers_1.logWithColor)(`Next step: ${JSON.stringify(nextStep)}`, 'magenta');
}
if (nextStep instanceof parser_1.AgentFinish) {
this.output = nextStep.response;
squad.events.emit('agent.finished', {
agent: this.agent.id,
name: this.name,
output: this.output,
task: this.id,
sources,
});
return this.output;
}
if (nextStep instanceof parser_1.AgentStep) {
intermediateSteps.push([
nextStep.action,
{ text: nextStep.observation },
]);
const action = nextStep.action;
const output = await toolRunner.run({
tool: action.tool,
toolInput: action.toolInput,
});
if (output instanceof tool_1.ToolError) {
intermediateSteps.push([null, { text: output.observation }]);
}
else {
(0, helpers_1.logWithColor)(`Tool output: ${JSON.stringify(output)}`, 'red');
if (output.sources) {
sources = [...sources, ...output.sources];
}
intermediateSteps.push([null, output]);
}
}
}
catch (error) {
const err = error;
if (squad.verbose) {
(0, helpers_1.logWithColor)(err.message, 'red');
}
if (error instanceof parser_1.ParserError) {
intermediateSteps.push([null, { text: error.observation }]);
}
else {
intermediateSteps.push([null, { text: err.message }]);
}
}
(0, helpers_1.logWithColor)(`Finished iteration`, 'red');
iterations++;
}
return 'The agent exceeded the maximum number of attempts.';
}
shouldContinue(iterations) {
return iterations < this.maxAttempts;
}
getToolsPrompt() {
return (0, helpers_1.interpolateVariablesIntoPrompt)(prompts_1.SQUAD_PROMPTS.tools, {
toolNames: this.tools.map(t => t.name).join(', '),
tools: this.tools
.map(t => `${t.name}, ${t.description}. Params: ${(0, helpers_1.convertZodSchemaToJson)(t.schema)}`)
.join('\n'),
});
}
buildIntermediateStepsPrompt(intermediateSteps) {
let prompt = '';
if (intermediateSteps.length) {
intermediateSteps.forEach(([action, response]) => {
if (action) {
prompt += `\n\n${action.log}`;
}
if (response && response.text) {
prompt += `\nObservation: ${response.text}`;
}
});
}
return prompt;
}
getUserInputsPrompt() {
if (!this.inputs || !this.inputs.length) {
return '';
}
let finalUserInputs = '\nHere is additional data for your tasks:\n';
for (const input of this.inputs) {
if (!input.value)
continue;
const tag = (0, helpers_1.convertToXmlTag)(input.label, input.value);
finalUserInputs += `\n${tag}\n`;
}
return finalUserInputs;
}
getNoToolsPrompt() {
return prompts_1.SQUAD_PROMPTS.noTools;
}
getExpectedOutputPrompt() {
return (0, helpers_1.interpolateVariablesIntoPrompt)(prompts_1.SQUAD_PROMPTS.expectedOutput, {
expectedOutput: this.expectedOutput,
});
}
getTaskKickoffPrompt() {
return prompts_1.SQUAD_PROMPTS.kickoff;
}
getCurrentTaskPrompt(squad) {
let taskPrompt = (0, helpers_1.interpolateVariablesIntoPrompt)(prompts_1.SQUAD_PROMPTS.task, {
input: this.description,
});
let previousTasksIds = this.adjancentFrom;
if (!previousTasksIds.length) {
return taskPrompt;
}
const previousTasks = squad.nodesById(previousTasksIds);
const taskContext = previousTasks.map(t => t.nodeOutput()).join('\n');
if (taskContext) {
taskPrompt += (0, helpers_1.interpolateVariablesIntoPrompt)(prompts_1.SQUAD_PROMPTS.taskWithContext, { context: taskContext });
}
return (0, helpers_1.dedent) `${taskPrompt}`;
}
getAdditionalInstructions(squad) {
if (squad.instructions) {
return `\n\n<important_user_instructions>${squad.instructions}</important_user_instructions>`;
}
return '';
}
/**
* Builds the initial prompt for the LLM.
* It uses different prompts if there are tools involved in the task.
*/
buildInitialPrompt(squad) {
const isTaskWithsTools = this.tools.length > 0;
let prompt = this.agent.getRolePlaying();
if (isTaskWithsTools) {
prompt += this.getToolsPrompt();
}
else {
prompt += this.getNoToolsPrompt();
}
prompt += this.getCurrentTaskPrompt(squad);
prompt += this.getUserInputsPrompt();
prompt += this.getExpectedOutputPrompt();
prompt += this.getAdditionalInstructions(squad);
prompt += this.getTaskKickoffPrompt();
return (0, helpers_1.dedent) `${prompt}`;
}
nodeOutput() {
return `${(0, helpers_1.convertToXmlTag)((0, helpers_1.removeDiacritics)(this.name).toLocaleLowerCase(), this.output || '')}`;
}
}
exports.Task = Task;
//# sourceMappingURL=task.js.map