为了搞懂 Agent 原理,没用任何框架,手撸了一个最小 ReAct 循环:思考 → 行动 → 观察 → 再思考。核心逻辑其实不复杂:
async function reactLoop(goal: string, tools: Tool[], maxSteps = 8) {
let scratch = "";
for (let i = 0; i < maxSteps; i++) {
const step = await claude.think(goal, scratch, tools);
if (step.done) return step.answer;
const obs = await tools.find((t) => t.name === step.action)!.run(step.input);
scratch += step.thought + obs;
}
throw new Error("达到最大步数,疑似循环");
}
手写一遍之后对框架封装的理解深了很多。建议大家入门都自己撸一个最小版本。