五、第三块砖:Agent 循环(ReAct Loop)
Agent 循环是 AI 编程智能体的核心逻辑,负责从理解用户意图到执行任务的整个过程。本节将详细介绍 Agent 循环的设计和实现。
核心循环逻辑
Agent 循环的逻辑可以分为以下几个步骤:
- LLM 推理:通过 LLM 理解用户的意图,并生成任务规划。
- 执行工具:根据任务规划,调用工具执行任务。
- 结果回填上下文:将工具执行的结果回填到上下文,供 LLM 下一轮推理使用。
- 迭代修正:根据执行结果,调整任务规划,进行必要的修正。
- 直到 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