regent-ai
Version:
An AI multi-agent orchestration framework
82 lines • 3.4 kB
JavaScript
import { logEntries } from "../utils/Logger";
export class AgentRouter {
constructor(config) {
this.agentHistory = [];
this.conversationHistory = [];
this.agents = config.agents;
this.defaultAgent = config.defaultAgent;
}
updateAgentHistory(agentName) {
const lastAgent = this.agentHistory[this.agentHistory.length - 1];
if (lastAgent == agentName)
return;
this.agentHistory.push(agentName);
}
updateHistory(input) {
if (Array.isArray(input)) {
this.conversationHistory.push(...input);
}
else {
this.conversationHistory.push(input);
}
}
async run(conversationId, inputMessages, context, currentAgent) {
if (!currentAgent)
currentAgent = this.defaultAgent;
if (!currentAgent)
currentAgent = this.defaultAgent;
let isFinalResponse = false;
this.updateHistory(inputMessages);
while (!isFinalResponse) {
this.updateAgentHistory(currentAgent);
const agent = this.agents.get(currentAgent);
if (!agent) {
throw new Error(`Agent ${currentAgent} not found`);
}
const agentRunResult = await agent.run(conversationId, this.conversationHistory, context);
if (agentRunResult.chatCompletions) {
const messages = agentRunResult.chatCompletions.map((cc) => {
if (!cc.choices || !cc.choices[0] || !cc.choices[0].message) {
console.error("Unexpected chat completion", cc);
throw new Error("Invalid chat completion");
}
return cc.choices[0].message;
});
this.updateHistory(messages);
}
if (agentRunResult.handoffToAgent) {
if (agentRunResult.handoffToAgent.previous)
currentAgent = this.agentHistory[this.agentHistory.length - 2];
if (agentRunResult.handoffToAgent.name)
currentAgent = agentRunResult.handoffToAgent.name;
if (!currentAgent)
currentAgent = this.defaultAgent;
context = agentRunResult.context;
}
if (agentRunResult.isFinalResponse) {
isFinalResponse = agentRunResult.isFinalResponse;
const log = logEntries.get(conversationId) || [];
const usage = log.reduce((acc, curr) => {
acc.prompt_tokens += curr.usage.prompt_tokens;
acc.completion_tokens += curr.usage.completion_tokens;
acc.total_tokens += curr.usage.total_tokens;
return acc;
}, {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0,
});
return {
chatCompletions: agentRunResult.chatCompletions,
conversationHistory: this.conversationHistory,
agentHistory: this.agentHistory,
context: agentRunResult.context,
currentAgent,
logEntries: log,
usage,
};
}
}
}
}
//# sourceMappingURL=AgentRouter.js.map