tinyagent-ts
Version:
Modern TypeScript framework for building AI agents with pluggable tools and ReAct reasoning
58 lines • 2.28 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.runMultiStep = runMultiStep;
const final_answer_tool_1 = require("./final-answer.tool");
const json_1 = require("./utils/json");
async function runMultiStep(agent, input, options = {}) {
const { maxSteps = 6 } = options;
const modelName = agent.getModelName();
const tools = agent.buildToolRegistry();
const toolCatalog = Object.values(tools)
.filter((t) => t.meta.name !== 'final_answer')
.map((t) => `- ${t.meta.name}: ${t.meta.description}`)
.join('\n');
const system = agent.promptEngine.render('agent', { tools: toolCatalog });
const messages = [
{ role: 'system', content: system },
{ role: 'user', content: String(input) }
];
const scratch = [];
for (let step = 0; step < maxSteps; step++) {
const resp = await agent.makeOpenRouterRequest(messages, modelName);
const reply = resp.choices[0]?.message?.content?.trim() ?? '';
const jsonStr = (0, json_1.extractJson)(reply);
if (!jsonStr) {
// Non JSON => done
return { answer: reply };
}
let parsed;
try {
parsed = JSON.parse(jsonStr);
}
catch {
return { answer: reply };
}
if (parsed.tool === 'final_answer') {
const finalTool = new final_answer_tool_1.FinalAnswerTool();
const args = finalTool.schema.parse(parsed.args ?? {});
const out = await finalTool.forward(args);
return out;
}
const selected = tools[parsed.tool];
if (!selected) {
return { answer: `Unknown tool: ${parsed.tool}` };
}
let result;
try {
result = await selected.call(parsed.args);
}
catch (e) {
result = e instanceof Error ? e.message : String(e);
}
scratch.push({ tool: parsed.tool, output: String(result) });
messages.push({ role: 'assistant', content: reply });
messages.push({ role: 'assistant', content: JSON.stringify({ observation: String(result) }) });
}
return { answer: scratch[scratch.length - 1]?.output ?? '' };
}
//# sourceMappingURL=runMultiStep.js.map