【开发心得】如何从零构建类 Codex 的 AI 智能体【3】

五、第三块砖:Agent 循环(ReAct Loop)

Agent 循环是 AI 编程智能体的核心逻辑,负责从理解用户意图到执行任务的整个过程。本节将详细介绍 Agent 循环的设计和实现。

核心循环逻辑

Agent 循环的逻辑可以分为以下几个步骤:

  1. LLM 推理:通过 LLM 理解用户的意图,并生成任务规划。
  2. 执行工具:根据任务规划,调用工具执行任务。
  3. 结果回填上下文:将工具执行的结果回填到上下文,供 LLM 下一轮推理使用。
  4. 迭代修正:根据执行结果,调整任务规划,进行必要的修正。
  5. 直到 LLM 输出"最终答案"或达到最大轮次:循环结束。
python 复制代码
def agent_loop(prompt, llm, tools, max_rounds=10):
    messages = [{"role": "user", "content": prompt}]
    round = 0
    done = False

    while not done and round < max_rounds:
        response = llm_chat(messages, llm)
        if response.tool_calls:
            results = [execute(t) for t in response.tool_calls]
            messages.append(tool_results(results))
        else:
            print(response.content)  # 最终回答
            done = True
        round += 1

最大轮次限制(防止死循环)

为了避免 Agent 循环陷入死循环,需要设置最大轮次限制:

  • 最大轮次:设置一个合理的最大轮次限制,防止无限循环。
python 复制代码
def agent_loop(prompt, llm, tools, max_rounds=10):
    messages = [{"role": "user", "content": prompt}]
    round = 0
    done = False

    while not done and round < max_rounds:
        response = llm_chat(messages, llm)
        if response.tool_calls:
            results = [execute(t) for t in response.tool_calls]
            messages.append(tool_results(results))
        else:
            print(response.content)  # 最终回答
            done = True
        round += 1

思考链(Chain of Thought)设计

为了提高任务执行的透明度,可以设计思考链机制:

  • 思考链:记录 LLM 的每一步思考过程,供用户查看。
python 复制代码
def agent_loop(prompt, llm, tools, max_rounds=10):
    messages = [{"role": "user", "content": prompt}]
    round = 0
    done = False
    thought_chain = []

    while not done and round < max_rounds:
        response = llm_chat(messages, llm)
        thought_chain.append(response.content)
        if response.tool_calls:
            results = [execute(t) for t in response.tool_calls]
            messages.append(tool_results(results))
        else:
            print(response.content)  # 最终回答
            done = True
        round += 1

    return thought_chain

错误处理:工具执行失败 → 重试 / 换策略 / 求助用户

为了提高系统的鲁棒性,需要处理工具执行失败的情况:

  • 重试:自动重试失败的工具。
  • 换策略:尝试不同的执行策略。
  • 求助用户:在无法解决的情况下,求助用户。
python 复制代码
def execute_tool(tool_name, params):
    try:
        if tool_name == "read_file":
            return read_file(params["file_path"])
        elif tool_name == "write_file":
            return write_file(params["file_path"], params["content"])
        # 其他工具...
    except Exception as e:
        return {"error": str(e)}

def agent_loop(prompt, llm, tools, max_rounds=10):
    messages = [{"role": "user", "content": prompt}]
    round = 0
    done = False

    while not done and round < max_rounds:
        response = llm_chat(messages, llm)
        if response.tool_calls:
            results = [execute(t) for t in response.tool_calls]
            for result in results:
                if "error" in result:
                    # 重试或换策略
                    pass
            messages.append(tool_results(results))
        else:
            print(response.content)  # 最终回答
            done = True
        round += 1

进度汇报:让用户知道当前在做什么

为了提高用户的体验,可以在每一步执行后汇报进度:

  • 进度汇报:在每一步执行后,向用户汇报当前的进度。
python 复制代码
def agent_loop(prompt, llm, tools, max_rounds=10):
    messages = [{"role": "user", "content": prompt}]
    round = 0
    done = False

    while not done and round < max_rounds:
        response = llm_chat(messages, llm)
        if response.tool_calls:
            results = [execute(t) for t in response.tool_calls]
            for result in results:
                if "error" in result:
                    # 重试或换策略
                    pass
            messages.append(tool_results(results))
            print(f"Step {round + 1}: {response.content}")
        else:
            print(response.content)  # 最终回答
            done = True
        round += 1

六、第四块砖:安全沙箱与权限控制

安全沙箱是 AI 编程智能体的重要组成部分,负责确保任务执行的安全性。本节将详细介绍安全沙箱的设计和实现。

命令白名单/黑名单:哪些 Shell 命令允许执行

为了防止 AI Agent 执行危险的 Shell 命令,需要设置命令白名单和黑名单:

  • 命令白名单:只允许执行白名单中的命令。
  • 命令黑名单:禁止执行黑名单中的命令。
python 复制代码
ALLOWED_COMMANDS = ["ls", "cat", "grep", "rg"]
FORBIDDEN_COMMANDS = ["rm", "mv", "chmod"]

def run_command(command):
    if command.split()[0] in FORBIDDEN_COMMANDS:
        raise ValueError("Forbidden command")
    if command.split()[0] not in ALLOWED_COMMANDS:
        raise ValueError("Unknown command")
    result = subprocess.run(command, shell=True, capture_output=True, text=True)
    return result.stdout, result.stderr

文件路径限制:只允许在指定目录内读写

为了防止 AI Agent 访问敏感文件,需要限制文件路径:

  • 指定目录:只允许在指定目录内读写文件。
python 复制代码
ALLOWED_DIRS = ["/home/user/"]

def read_file(file_path):
    if not any(file_path.startswith(d) for d in ALLOWED_DIRS):
        raise ValueError("Forbidden path")
    with open(file_path, 'r') as file:
        return file.read()

def write_file(file_path, content):
    if not any(file_path.startswith(d) for d in ALLOWED_DIRS):
        raise ValueError("Forbidden path")
    with open(file_path, 'w') as file:
        file.write(content)

危险操作确认:rm -rf、git push --force、写密钥文件等

为了防止 AI Agent 执行高风险操作,需要在执行前进行确认:

  • 确认机制:在执行高风险操作前,要求用户确认。
python 复制代码
def run_command(command):
    if command.startswith("rm -rf"):
        response = input("Are you sure you want to run 'rm -rf'? [y/N]: ")
        if response.lower() != "y":
            raise ValueError("Operation cancelled")
    result = subprocess.run(command, shell=True, capture_output=True, text=True)
    return result.stdout, result.stderr

沙箱方案:Docker 容器 / chroot / 权限隔离

为了进一步提高安全性,可以使用沙箱方案:

  • Docker 容器:将 AI Agent 运行在 Docker 容器中,限制其访问权限。
  • chroot:使用 chroot 技术,将 AI Agent 运行在受限的文件系统中。
  • 权限隔离:使用权限隔离技术,限制 AI Agent 的操作系统权限。

审计日志:所有操作留痕,可追溯

为了确保操作的可追溯性,需要记录审计日志:

  • 审计日志:记录所有操作的详细信息。
python 复制代码
import logging

logging.basicConfig(filename="audit.log", level=logging.INFO)

def run_command(command):
    result = subprocess.run(command, shell=True, capture_output=True, text=True)
    logging.info(f"Command: {command}, Output: {result.stdout}, Error: {result.stderr}")
    return result.stdout, result.stderr

宪法机制:不可被用户 prompt 覆盖的底层规则

为了防止用户通过 prompt 覆盖底层规则,需要实现宪法机制:

  • 宪法机制:定义不可被用户 prompt 覆盖的底层规则。
python 复制代码
def llm_chat(prompt, llm, tools):
    if "rm -rf" in prompt:
        raise ValueError("Forbidden operation")
    response = stream_chat_completions(prompt, llm)
    return response
相关推荐
今年下半年15 分钟前
AI智能体项目实战记录(47):飞书渠道进阶——图片/文件、互动卡片与打字机
llm·飞书·智能体·打字机·图片识别·langgraph
zc.z23 分钟前
RAG (一):从底层原理、Naive RAG 到企业级项目开发与面试实战
人工智能·python·rag
夜雪轻寒26 分钟前
AI 工具踩坑录:Prompt 我越写越长,模型反而越来越笨,删到第三版才明白它在装
java·开发语言·人工智能·语言模型·自然语言处理·prompt
Elastic 中国社区官方博客29 分钟前
从 137,306 行日志定位到一个故障副本:在 Kibana 中排查错误激增
大数据·运维·人工智能·安全·elasticsearch·搜索引擎
oil欧哟31 分钟前
面向长周期应用开发的 Harness 设计
人工智能
龙智DevSecOps解决方案40 分钟前
ICCAD-Expo 2026 回顾:Perforce与龙智联合亮相,基于P4/VersIC/IPLM分享IP与设计数据管理实践
人工智能·网络协议·tcp/ip
摩尔芯创43 分钟前
仿真软件如何推动自动驾驶汽车设计发展
人工智能·自动驾驶·汽车·仿真·ansys
风中芦苇啊1 小时前
Spring AI 项目实战:从零搭建一个智能问答服务
java·人工智能·spring
sun153690275721 小时前
面向生态通量观测|三维超声波风速风向传感器技术特点与实测优势
人工智能