Agent开发-实现一个对话循环

任务:

把 juejin.cn/post/769598... 的手动流程改成一个 for 循环。

三样东西缺一不可:

  • 终止条件: finish_reason === 'stop' , 或者没有 tool_calls
  • 最大步数: 必须有,否则它会反复调同一个工具,安静地烧完你的额度
  • 异常兜底: 工具执行失败时,把错误信息作为结果回填给模型
typescript 复制代码
const MAX_STEPS = 5; //最大调用次数

const runAgent = async () => {
  for (let setup = 1; setup <= MAX_STEPS; setup++) {
    const started = Date.now();
    const response = await client.chat.completions.create({
      model: MODEL,
      messages,
      tools,
    })

    const choice = response.choices?.[0];
    if (!choice) {
      console.log(`当前模型没有返回任何结果`);
      return;
    }
    messages.push(choice.message);

    // 对话结束
    if (choice.finish_reason === "stop") {
      console.log(`当前模型对话结束: ${choice.message.content}`);
      dumpMessages(messages);
      return;
    }

    // 对话超出长度被截取
    if (choice.finish_reason === "length") {
      console.log(`当前对话超出最大长度, 请调大max_token`);
      return;
    }

    // 调用工具
    if (choice.finish_reason === "tool_calls" && choice.message.tool_calls) {
      for (const toolCall of choice.message.tool_calls) {
        let content: string;
        // 错误处理
        try {
          const args = JSON.parse(toolCall.function.arguments)
          const name = toolCall.function.name
          content = JSON.stringify(executeTool(name, args))
        } catch (error) {
          content = `工具执行失败: ${error instanceof Error ? error.message : String(error)}`
        }
        messages.push({
          role: "tool",
          tool_call_id: toolCall.id,
          content,
        });
      }
      continue;
    }

    console.log(`没有出现预期的 finish_reason: ${choice.finish_reason}`);
    return;
  }

  console.log(`对话达到最高次数 ${MAX_STEPS},仍未结束`);
}
相关推荐
奈落243 小时前
AI辅助的另一面:从2026年国际AI安全报告的“故障”清单到国内专家的可靠性短板,自主行动的Agent为什么更难及时干预
人工智能·安全·agent·本地部署·ai 办公
时早玖沐12 小时前
放弃 QQ 官方机器人:用 SnowLuma + AstrBot 自建 QQ 机器人
docker·开源·agent
nujnewnehc12 小时前
给记事软件加上 mcp
agent·mcp
轻松西西莱尔12 小时前
谷歌+斯坦福+CMU 等五家 203 页综述,我做了个HTML把主动式AI的边界跑给你看
前端·html·agent
文谦南宁AI普工12 小时前
主动性 Agent 的第一道工程题:Fast/Slow Path 两级过滤,附 80 行可跑模拟器
agent·ai编程·产品
米小虾12 小时前
Agent 省钱工程:七成的钱不是模型花掉的
人工智能·agent
阿里云云原生13 小时前
欢迎报名丨Alibaba Cloud AgentCore 企业智能体构建与治理八城巡回沙龙 · 杭州站开启
agent
不一样的少年_14 小时前
为什么你写的 Agent 一报错就死循环?很多人都漏掉了这层“错误自救与熔断”机制
前端·后端·agent
小七-七牛开发者15 小时前
Tool-Use Agent 如何扩训练数据:拆解工具、任务与环境状态的 Scaling Law
ai·agent·工具调用·scalinglaw·synthapi