swift-agent
Version:
A building block of agentic systems: an LLM that can retrieve information, use tools, and store user inputs.
109 lines (108 loc) • 3.42 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SwiftAgent = void 0;
const messages_1 = require("@langchain/core/messages");
const mcp_adapters_1 = require("@langchain/mcp-adapters");
const prebuilt_1 = require("@langchain/langgraph/prebuilt");
class SwiftAgent {
agent;
mcpClient;
messages = [];
model;
options;
tools = [];
toolsInitialized = false;
constructor(model, options) {
this.model = model;
this.options = options;
if (this.options?.mcp) {
this.mcpClient = new mcp_adapters_1.MultiServerMCPClient(this.options.mcp);
}
if (options?.messageHistory) {
this.messages = options.messageHistory;
}
if (options?.systemPrompt) {
this.applySystemPrompt(options.systemPrompt);
}
}
async initialize() {
await this.getAgent();
}
async run(message) {
const agent = await this.getAgent();
this.messages.push(new messages_1.HumanMessage(message));
const response = await agent.invoke({ messages: this.messages });
this.messages = response.messages;
return this.messages;
}
async getTools() {
if (!this.mcpClient || this.tools.length > 0) {
return this.tools;
}
const mcpServers = this.mcpClient.config.mcpServers || {};
const serverNames = Object.keys(mcpServers);
this.tools = (await Promise.all(serverNames.map(async (serverName) => {
const tools = (await this.mcpClient?.getTools(serverName));
if (!tools) {
return [];
}
tools.forEach((tool) => {
tool.serverName = serverName;
tool.isEnabled = true;
});
return tools;
}))).flat();
return this.tools;
}
async disconnectMCPServers() {
if (this.mcpClient) {
await this.mcpClient.close();
}
}
enableMCPServer(serverName) {
this.setToolsEnabled(serverName, true);
}
disableMCPServer(serverName) {
this.setToolsEnabled(serverName, false);
}
resetMessages(keepSystemMessage = true) {
if (keepSystemMessage && this.messages[0]?.getType() === "system") {
this.messages.splice(1);
}
else {
this.messages = [];
}
}
applySystemPrompt(systemPrompt) {
if (this.messages[0]?.getType() === "system") {
this.messages[0].content = systemPrompt;
}
else {
this.messages.unshift(new messages_1.SystemMessage(systemPrompt));
}
}
async getAgent() {
if (this.agent) {
return this.agent;
}
if (!this.toolsInitialized) {
this.tools = await this.getTools();
this.toolsInitialized = true;
}
this.agent = (0, prebuilt_1.createReactAgent)({
llm: this.model,
tools: this.tools.filter((tool) => tool.isEnabled),
});
return this.agent;
}
setToolsEnabled(serverName, isEnabled) {
const tools = this.tools.filter((tool) => tool.serverName === serverName);
if (tools.length === 0) {
return;
}
tools.forEach((tool) => {
tool.isEnabled = isEnabled;
});
}
}
exports.SwiftAgent = SwiftAgent;