UNPKG

taskforce-aiagent

Version:

TaskForce is a modular, open-source, production-ready TypeScript agent framework for orchestrating AI agents, LLM-powered autonomous agents, task pipelines, dynamic toolchains, RAG workflows and memory/retrieval systems.

190 lines (189 loc) 9.24 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Agent = void 0; const aiClient_js_1 = require("../llm/aiClient.js"); const aiConfig_js_1 = require("../configs/aiConfig.js"); const toolExecutor_js_1 = require("../tools/toolWorker/toolExecutor.js"); const agent_helper_js_1 = require("./agent.helper.js"); const chalk_1 = __importDefault(require("chalk")); const log_helper_js_1 = require("../helpers/log.helper.js"); const baseTool_js_1 = require("../tools/base/baseTool.js"); const toolRegistry_js_1 = require("../tools/base/toolRegistry.js"); const helper_js_1 = require("../helpers/helper.js"); const enum_js_1 = require("../configs/enum.js"); const memoryFactory_js_1 = require("../memory/memoryFactory.js"); const retrieval_helper_js_1 = require("../memory/retrievals/retrieval.helper.js"); const agentTraining_helper_js_1 = require("../agentTraining/agentTraining.helper.js"); class Agent { constructor(agent) { this.delegationCount = 0; this.MAX_DELEGATION = 3; this.verbose = false; this.name = agent.name; this.role = agent.role; this.goal = agent.goal; this.backstory = agent.backstory; this.model = agent.model; this.modelOptions = agent.modelOptions; this.guardrails = agent.guardrails; this.systemPrompt = agent.systemPrompt; this.allowDelegation = agent.allowDelegation ?? false; this.retriever = agent.retriever; this.autoTruncateHistory = agent.autoTruncateHistory ?? false; this.llmModel = (0, aiConfig_js_1.getLLMModelByName)(this.model || process.env.DEFAULT_MODEL); // 🆕 Tool sınıflarını instance’a çevir + ToolRegistry’ye kaydet const instantiatedTools = (agent.tools || []).map((t) => { if (typeof t === "function") { try { const instance = this.isClassConstructor(t) ? new t() : t(); // 👈 ayrım burada toolRegistry_js_1.ToolRegistry.register(instance); return instance; } catch (err) { throw new Error(`[Agent] Tool initialization failed: ${err}`); } } else if (t instanceof baseTool_js_1.Tool) { toolRegistry_js_1.ToolRegistry.register(t); return t; } else { throw new Error(`[Agent] Invalid tool type: ${typeof t}`); } }); this.agentTools = instantiatedTools; this.toolExecutor = new toolExecutor_js_1.ToolExecutor(instantiatedTools, agent.taskForce, agent.name); this.memoryScope = agent.memoryScope ?? (this.memoryProvider && this.memoryProvider.getMemoryScope()) ?? enum_js_1.MemoryScope.None; this.memoryProvider = agent.memoryProvider ?? (0, memoryFactory_js_1.MemoryProvider)(this.name, this.memoryScope, enum_js_1.MemoryMode.Same, enum_js_1.VectorMemoryProviderType.Local); if (this.memoryProvider && this.memoryScope != enum_js_1.MemoryScope.None) { this.memoryInitialized = true; } const data = (0, agentTraining_helper_js_1.loadTraining)(agent.name); if (data) { this.trained = data; if (this.verbose) { (0, log_helper_js_1.TFLog)(`📚 Loaded training data for ${agent.name}: ${JSON.stringify(data)}`, chalk_1.default.magenta); } } } isClassConstructor(func) { return (typeof func === "function" && /^class\s/.test(Function.prototype.toString.call(func))); } setDelegationDisallowed(disallowed) { this.delegationDisallowed = disallowed; } getDelegationDisallowed() { return this.delegationDisallowed; } setVerbose(verbose) { this.verbose = verbose; } getVerbose() { return this.verbose; } canUseTools() { return this.toolExecutor.getTools().length > 0; } canDelegate() { return this.allowDelegation && this.delegationCount < this.MAX_DELEGATION; } incrementDelegation() { this.delegationCount++; } async runTask(inputs, taskDescription, outputFormat, inputFromPrevious, retryReason, delegateReason, rePlanReason, executionMode, retriever, isTraining = false) { if (this.verbose) { (0, log_helper_js_1.TFLog)(`🚀 [Agent Run Task] ${this.name} is executing task: ${taskDescription}`, chalk_1.default.yellow); } // ❌ MEMORY READ: Skip during training if (!isTraining && this.memoryScope !== enum_js_1.MemoryScope.None) { let enrichedContext = ""; const retrieverToUse = this.retriever || retriever; if (retrieverToUse || this.memoryProvider) { enrichedContext = await (0, retrieval_helper_js_1.retrieveAndEnrichPrompt)(inputFromPrevious || Object.values(inputs).join(" "), retrieverToUse, this.memoryProvider, this.model || process.env.DEFAULT_MODEL, this.verbose, { agent: this.name, taskId: taskDescription, }); } if (enrichedContext) { inputFromPrevious = inputFromPrevious ? `${enrichedContext}\n\n${inputFromPrevious}` : enrichedContext; if (this.verbose) { const providerName = this.memoryProvider?.constructor?.name || "UnknownMemory"; (0, log_helper_js_1.TFLog)(`Injected Memory from from ${providerName} to ${this.name}:\n${inputFromPrevious}\n`, chalk_1.default.white); } } } const systemMessage = (0, agent_helper_js_1.buildSystemMessage)(inputs, this, isTraining); const userMessage = (0, agent_helper_js_1.buildUserMessage)(inputs, this, taskDescription, inputFromPrevious, retryReason, delegateReason, outputFormat, rePlanReason); let chatMessage = [ { role: "system", content: systemMessage, }, { role: "user", content: userMessage, }, ]; let safeMessages = chatMessage; if (this.autoTruncateHistory) { safeMessages = await (0, agent_helper_js_1.truncateMessagesToFitModelLimit)(this.model || process.env.DEFAULT_MODEL, chatMessage); } const output = await (0, aiClient_js_1.callAIModel)(this.name, this.model || process.env.DEFAULT_MODEL, safeMessages, this.verbose, this.llmModel.supportsTools && this.canUseTools() ? this.agentTools : [], this.modelOptions); if (this.verbose) { (0, log_helper_js_1.TFLog)(`📤 [Agent Output] ${this.name} result:`, chalk_1.default.blue); (0, log_helper_js_1.TFLog)(`${output}\n`, chalk_1.default.gray); } if (this.canUseTools() && !this.llmModel.supportsTools && (0, helper_js_1.checkTool)(output)) { const enrichedOutput = await (0, agent_helper_js_1.recursiveToolWorker)(output, this, taskDescription, outputFormat ?? "", inputs); if (enrichedOutput) { let safeMessages = enrichedOutput; if (this.autoTruncateHistory) { safeMessages = await (0, agent_helper_js_1.truncateMessagesToFitModelLimit)(this.model || process.env.DEFAULT_MODEL, enrichedOutput); } const secondOutput = await (0, aiClient_js_1.callAIModel)(this.name, this.model || process.env.DEFAULT_MODEL, safeMessages, this.verbose, [], this.modelOptions); return secondOutput; } } if (this.getDelegationDisallowed()) { if (this.verbose) { (0, log_helper_js_1.TFLog)(`⛔ [Delegation Blocked] ${this.name} is not allowed to delegate further.`, chalk_1.default.red); } if ((0, helper_js_1.checkDelegate)(output)) { return output.replace(/^DELEGATE\(.*?\)$/, "⚠️ Delegation blocked."); } } if (this.canDelegate() && (0, helper_js_1.checkDelegate)(output)) { const delegation = await (0, agent_helper_js_1.delegateTo)(this, output, inputs, 0); if (delegation) { return JSON.stringify({ __delegate__: delegation, __depth__: 1 }); } } // ❌ MEMORY WRITE: Skip during training if (!isTraining && executionMode === enum_js_1.ExecutionMode.Sequential) { // 🧠 OUTPUT sonrası: Hafıza kaydı if (this.memoryScope !== enum_js_1.MemoryScope.None && this.memoryProvider) { await this.memoryProvider.storeMemory({ taskId: taskDescription, input: JSON.stringify(inputs), output, metadata: { agent: this.name }, }); } } return output; } } exports.Agent = Agent;