ReAct框架搭建故障排查智能运维机器人

先搞懂 ReAct 和智能运维机器人能干什么

很多运维同学觉得 AI 编程门槛高,其实借助 ReAct(Reasoning + Acting)框架,你只需要写几行 Python 就能让大模型自动分析日志、调用系统命令并给出修复建议。
简单说,ReAct 让 LLM 先思考“故障可能是什么原因”,然后执行一个动作(比如查 CPU 使用率、读错误日志),再根据结果继续推理,直到找到根本原因。
本文的目标就是带你亲手做一个这样的机器人,用它排查 nginx 挂掉、磁盘满、进程假死等常见问题。

第一步:环境搭建与依赖安装

打开你的 Linux 服务器或本地开发机(本文以 Ubuntu 22.04 为例),先确保 Python 3.8 以上已安装。
然后创建项目目录并安装核心库:

mkdir react-robot && cd react-robot
python3 -m venv venv
source venv/bin/activate
pip install langchain openai python-dotenv

接着在项目根目录创建 .env 文件,写入你的 OpenAI API Key(或者兼容接口):

OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxx
OPENAI_API_BASE=https://api.openai.com/v1  # 如果使用其他模型请修改端点
⚠️ 避坑:如果 API Key 在代码里硬编码,不小心提交到 Git 会泄露。务必使用环境变量或 .env 文件,且将 .env 加入 .gitignore

第二步:编写机器人核心代码——定义工具与Agent

创建一个 robot.py
核心思路是:
定义几个“工具函数”(比如执行 shell 命令、
读取日志文件),
然后让 LangChain 的 ReAct Agent 根据用户问题自动调用这些工具。

import os
from dotenv import load_dotenv
load_dotenv()

from langchain.agents import Tool, AgentExecutor, create_react_agent
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
import subprocess

# 1. 定义工具函数:执行 shell 命令并返回输出
def run_bash(command: str) -> str:
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return result.stdout + result.stderr
    except Exception as e:
        return f"执行出错: {e}"

# 2. 注册工具
tools = [
    Tool(
        name="ShellExecutor",
        func=run_bash,
        description="用于在服务器上执行 shell 命令,例如 'ps aux'、'df -h'、'tail -n 50 /var/log/nginx/error.log'。"
    )
]

# 3. 初始化 LLM
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

# 4. 创建 ReAct Agent
prompt = PromptTemplate.from_template(
    """Answer the following question as best you can. You have access to the following tools:
{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {input}
{agent_scratchpad}"""
)

agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)
🧠 解释create_react_agent 会自动按照 ReAct 格式要求 LLM 输出“思考-动作-观察”循环。handle_parsing_errors=True 可以处理 LLM 偶尔输出不规范导致的报错。

第三步:启动机器人并测试故障排查

robot.py 末尾添加交互循环:

if __name__ == "__main__":
    print("🤖 智能运维机器人已启动,请输入你的故障描述(输入 quit 退出)")
    while True:
        user_input = input("\n> ")
        if user_input.lower() in ["quit", "exit"]:
            break
        response = agent_executor.invoke({"input": user_input})
        print(f"\n📋 诊断结果:\n{response['output']}")

运行 python robot.py,输入模拟问题:

> nginx 无法访问,帮我看一下

机器人会依次执行 systemctl status nginxtail /var/log/nginx/error.log 等命令,并给出分析。
如果 nginx 真的挂了,它甚至会在工具里允许重启(可以在工具函数中增加 systemctl restart nginx,但要小心权限)。

第四步:验证结果与常见排错

验证方法很简单:故意制造一个简单故障(比如停止 nginx 服务 sudo systemctl stop nginx),然后让机器人排查。
正常应该看到类似:

Thought: nginx 服务未运行,尝试启动...
Action: ShellExecutor
Action Input: systemctl start nginx
Observation: 启动成功
Final Answer: 已检测到 nginx 服务停止,已自动重启,你可以通过 curl localhost 确认。

高频问题与解决:

  1. LLM 调用超时:检查 .env 中 API Key 是否有效,部分代理网络需要设置 OPENAI_API_BASE
  2. 命令执行无权限:工具函数内部默认以当前用户执行,如需 sudo 命令可在函数内加上 sudo,但生产环境建议通过专用用户或 sudoers 白名单控制。
  3. LLM 输出格式错误:升级 langchain 到最新版,或在创建 Agent 时加上 handle_parsing_errors=True
  4. 工具描述太模糊导致 LLM 不调用:每个工具的 description 要写清楚什么时候用、输入格式。

第五步:避坑与进阶方向

  • 限制命令范围:不要直接让机器人执行任意 shell 命令,可以考虑白名单模式,只允许 systemctltaildf 等安全命令。
  • 速率限制:免费 API 有每分钟请求数限制,可加入简单的令牌桶或睡眠等待。
  • 多工具协作:除了 Shell 工具,还可以添加日志读取工具(如 read_log(file_path))、数据库查询工具,机器人会自动选择。
  • 生产部署:建议用 FastAPI 包装成 Webhook,对接钉钉/企微机器人,实现自动响应告警。

如果你刚开始接触 AIOps,可以从本文的 ReAct 机器人起步,逐步添加自己的工具集。
遇到具体异常时,优先检查 API Key 和网络环境,大部分报错都能通过调整工具描述或增加示例解决。

分享到:
上一篇
定时休眠自动唤醒AI推理节省算力成本
下一篇
vLLM多GPU张量并行大模型推理教程:零基础也能上手
1
系统公告

机房迁移升级通知

尊敬的用户: IP 段 103.23.148.x、156.224.29.x 原香港一区线路波动、攻击频繁,平台定于 7 月 5 日凌晨分批迁移至香港 GIA 机房,硬件升级 AMD 铂金机型。 迁移均在凌晨操作,最大程度降低业务影响,迁移期间服务器临时关机; 升级后配置不降低、费用不涨价,数据默认同步迁移; 迁移后 IP 全部更换,请及时修改域名解析、防火墙白名单; 建议提前备份重要数据,有问题可联系在线客服。 感谢理解与支持! 泽御云科技 2026.06.30
服务中心
客服
在线客服
24小时为您服务
咨询
联系我们
联系我们,为您的业务提供专属服务。
24/7 技术支持
如果您遇到寻求进一步的帮助,请过工单与我们进行联系。
24/7 即时支持
泽御云
售前客服
泽御云
泽御云
售后客服
泽御云
技术支持
评价
您对当前页面的整体感受是否满意?
😞
非常不满意
😕
不满意
😐
一般
🙂
满意
😊
非常满意