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 小时前
Bash 工具讲解
agent·harness
沛东的认知和实践1 小时前
不检索比检索更准:模型已经会的题,上RAG后F1 掉 0.15~0.38,token 多花 3~34 倍——彻底搞懂LLMWiki第三篇补一
agent
熊猫钓鱼>_>1 小时前
告别手工贴发票:增值税发票识别+核验,搭一条报销自动化流水线
人工智能·ai·职场和发展·自动化·大模型·llm·agent
RuoyiOffice1 小时前
SpringBoot3+Vue3 企业 AI 工作流:Tinyflow 画布、LLM 节点与在线试跑怎么落地
spring boot·大模型·vue3·agent·ai工作流·ruoyi office·tinyflow
武子康2 小时前
PUBACK 已到,灯还没亮:Agent 设备指令何时算完成?
人工智能·后端·agent
浮生望2 小时前
用 PostgreSQL + pgvector 保存 Agent 长期记忆:从三表模型到语义检索
agent
枫叶丹42 小时前
AGENTS.md 越写越长之后:如何管理 AI 的上下文
人工智能·chatgpt·开源·agent·codex
墨心@2 小时前
CreateWorkflow 工具
agent·coding agent·harness·zcode
武子康2 小时前
ESP32 唤醒词标称 98%,为什么还要自己做验收?
人工智能·后端·agent