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},仍未结束`);
}
相关推荐
愤怒的代码1 小时前
吴恩达画了张 AI 工程技能地图:软件工程师要补这四门课
llm·agent·ai编程
可夫小子5 小时前
a16z 实测 11307 次 Agent 购物:AI 买东西只看 3 个详情页,要登录直接放弃
agent·ai编程
蜡笔小谢11 小时前
DeepSeek Harness Java 实战笔记(五)|插件、MCP 与 Skill
java·笔记·ai·agent·deepseek·harness
YIAN11 小时前
我踩完 DeepAgents 记忆模块的坑,才搞懂长期记忆和摘要不是一回事
前端·javascript·agent
23957304912 小时前
从 GUI 彻底转向 CLI:我用 .NET + Avalonia + NativeAOT 打造了 Agent 终端托管工具 Octopus
开源·.net·agent·avalonia·ai coding
YIAN13 小时前
用 Deep Agents 复现一个深度调研助手:从主 Agent、子 Agent 到 Skill
javascript·agent
IT规划师14 小时前
热点速递 | MCP 省 token,不是少接工具,是把工具变成文件
agent·ai编程
AI-Frontiers15 小时前
讲透企业级本体落地!从六要素建模到图谱、知识库与数字员工全链路实战
agent
阿里云云原生16 小时前
AgentTeams 1.2.8:全新工作台与新官网,一键开启团队协作
agent
吴凡wudianmei17 小时前
给 LLM 套输出契约:校验失败怎么把错误回灌给模型
python·llm·agent