在上一章代理协议实现,我们学会了让代理通过标准化协议与其他系统通信。但就像需要仪表盘才能驾驶汽车一样,用户需要一个直观的界面来监控代理的运行状态、查看日志,甚至通过聊天对话与代理交互。本章将教你如何为AutoGPT项目搭建可视化用户界面,让操作变得轻松简单!
想象你正在开发一个文件管理代理,但你希望:
用户界面集成就是这个“控制中心”,它:
✅ 提供Web页面展示代理状态
✅ 支持与代理的实时交互
✅ 通过代理协议与后端通信
作用:像汽车仪表盘,实时显示关键指标
示例功能:
- 当前运行的任务列表
- 代理CPU/内存使用率
- 最近10条日志记录
作用:像微信对话框,与代理直接对话
示例交互:
用户输入:“暂停当前任务”
代理响应:“任务已暂停,进度保存至文件/tmp/task1.log”
作用:像桥梁,连接前端与代理后端
工作原理:Web页面API端点代理协议通信代理后端
我们将使用Flask框架快速搭建一个前端,并通过API获取代理数据。
pip install flask requests
app.py
)from flask import Flask, jsonify
import requests
app = Flask(__name__)
# 假设代理运行在本地端口8000(参考第九章的协议)
AGENT_URL = "http://localhost:8000"
@app.route("/status")
def get_agent_status():
# 调用代理协议的/status端点(第九章定义)
response = requests.get(f"{AGENT_URL}/status")
return jsonify(response.json())
@app.route("/logs")
def get_agent_logs():
# 调用代理日志端点
response = requests.get(f"{AGENT_URL}/logs")
return jsonify(response.json())
if __name__ == "__main__":
app.run(port=5000)
templates/index.html
)DOCTYPE html>
<html>
<head><title>AutoGPT监控title>head>
<body>
<h1>代理状态监控h1>
<div id="status">div>
<div id="logs">div>
<script>
// 每2秒更新一次数据
setInterval(function() {
fetch('/status')
.then(response => response.json())
.then(data => {
document.getElementById('status').innerHTML =
`当前任务: ${data.data.current_task}
进度: ${data.data.progress}%`;
});
fetch('/logs')
.then(response => response.json())
.then(logs => {
let log_html = logs.data.slice(-5).reverse().map(log =>
`[${log.time}] ${log.message}`
).join('');
document.getElementById('logs').innerHTML = log_html;
});
}, 2000);
script>
body>
html>
python app.py
访问http://localhost:5000
,你会看到类似以下界面:
代理状态监控
当前任务: 生成销售报告
进度: 65%
日志:
[15:30:01] 正在读取销售数据...
[15:30:03] 创建临时文件/tmp/data.csv
[15:30:05] 开始生成图表...
以获取状态信息为例,流程如下:
app.py
)# 调用代理的/status接口
response = requests.get(f"{AGENT_URL}/status")
场景:用户通过Web页面发送指令“暂停任务”
# 新增的API端点(修改app.py)
@app.route("/send_command", methods=["POST"])
def send_command():
command = request.json.get("command")
# 调用代理的控制端点(参考第九章协议)
response = requests.post(f"{AGENT_URL}/control", json={"command": command})
return jsonify({"status": "success"})
# 对应的HTML表单(修改index.html)
<form>
<input type="text" id="command" placeholder="输入指令">
<button onclick="sendCommand()">发送</button>
</form>
<script>
function sendCommand() {
const command = document.getElementById('command').value;
fetch('/send_command', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({command})
});
}
</script>
通过本章,你已掌握:
✅ 通过Flask快速搭建Web监控界面
✅ 使用代理协议实现前后端通信
✅ 实现任务状态查看和指令发送功能
至此,你已完成了AutoGPT项目的全部核心功能学习!从命令行接口到用户界面,从代理核心到安全防护,你已具备开发和部署智能代理的完整知识体系。接下来可以尝试:
祝你在AI代理开发的道路上越走越远!