@jackhua/mini-langchain
Version:
A lightweight TypeScript implementation of LangChain with cost optimization features
122 lines • 3.77 kB
JavaScript
;
/**
* Base agent interface and implementations
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentExecutor = exports.BaseAgent = void 0;
exports.isAgentFinish = isAgentFinish;
const base_1 = require("../tools/base");
/**
* Check if step is a finish
*/
function isAgentFinish(step) {
return 'output' in step;
}
/**
* Base agent class
*/
class BaseAgent {
constructor(config) {
this.llm = config.llm;
this.toolManager = new base_1.ToolManager();
this.toolManager.registerTools(config.tools);
this.maxIterations = config.maxIterations || 5;
this.verbose = config.verbose || false;
}
/**
* Execute the agent with given input
*/
async execute(input) {
const context = {
input,
steps: [],
iterations: 0
};
while (context.iterations < this.maxIterations) {
context.iterations++;
if (this.verbose) {
console.log(`\n=== Iteration ${context.iterations} ===`);
}
// Plan next step
const step = await this.plan(context);
if (isAgentFinish(step)) {
// Agent has finished
context.steps.push({ finish: step });
if (this.verbose) {
console.log('Agent finished:', step.output);
}
return step.output;
}
// Execute action
const action = step;
context.steps.push({ action });
if (this.verbose) {
console.log(`Executing tool: ${action.tool}`);
console.log(`Input: ${action.toolInput}`);
}
// Execute tool
const result = await this.toolManager.executeTool(action.tool, action.toolInput);
if (result.error) {
const observation = `Error: ${result.error}`;
context.steps[context.steps.length - 1].observation = observation;
if (this.verbose) {
console.log('Observation:', observation);
}
}
else {
context.steps[context.steps.length - 1].observation = result.output;
if (this.verbose) {
console.log('Observation:', result.output);
}
}
}
// Max iterations reached
return `Agent stopped after ${this.maxIterations} iterations without reaching a conclusion.`;
}
/**
* Get available tools formatted for prompt
*/
getToolsDescription() {
return this.toolManager.formatToolsForPrompt();
}
/**
* Format execution history for prompt
*/
formatHistory(context) {
return context.steps
.map(step => {
if (step.action && step.observation !== undefined) {
return `Action: ${step.action.tool}\nAction Input: ${step.action.toolInput}\nObservation: ${step.observation}`;
}
if (step.finish) {
return `Final Answer: ${step.finish.output}`;
}
return '';
})
.filter(s => s)
.join('\n\n');
}
}
exports.BaseAgent = BaseAgent;
/**
* Simple agent executor for running agents
*/
class AgentExecutor {
constructor(agent) {
this.agent = agent;
}
/**
* Run the agent with given input
*/
async run(input) {
return this.agent.execute(input);
}
/**
* Run with multiple inputs
*/
async runBatch(inputs) {
return Promise.all(inputs.map(input => this.run(input)));
}
}
exports.AgentExecutor = AgentExecutor;
//# sourceMappingURL=base.js.map