本地可执行命令的智能体部署方案,目标是让大语言模型(LLM)在本地接收自然语言指令,并自动调用系统命令、脚本或应用程序,完成任务自动化。这类系统通常被称为 LLM Agent with Tool Use 或 本地 Agent 实体系统。
🧠 一、系统整体架构(LLM+Agent+Command执行)
┌────────────┐
│ 自然语言输入 │
└────┬───────┘
▼
┌────────────┐
│ LLM Agent │ ← 支持 Tool 使用
└────┬───────┘
▼
┌──────────────┐
│ 指令解析与规划 │
└────┬─────────┘
▼
┌────────────────────┐
│ 系统命令执行 (bash, python, etc.) │
└────────────────────┘
▼
┌────────────┐
│ 执行结果反馈 │
└────────────┘
🚀 二、部署方案选型
类型 | 模型支持 | 工具管理 | 优点 | 缺点 |
---|---|---|---|---|
LangChain + ChatGLM/Qwen + Tool | ✅ | ✅ | 生态成熟,可组合 | 配置复杂 |
AutoGPT / OpenAgents 本地版 | ✅ | ✅ | 任务自动规划 | 占资源多 |
Custom Agent(FastAPI + Shell) | 自定义 | 手动定义工具 | 控制强、轻量 | 需自建功能 |
推荐方案:LangChain + LLM + 本地工具调用 + FastAPI 接口包装。
⚙️ 三、核心实现步骤(LangChain 本地智能体)
1. 环境准备
conda create -n agent python=3.10 -y
conda activate agent
pip install langchain openai transformers auto-gptq faiss-cpu
pip install duckduckgo-search # optional web tool
2. 加载本地模型(Qwen/ChatGLM)
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-1_8B-Chat", trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-1_8B-Chat", trust_remote_code=True).half().cuda()
封装成 llm = HuggingFacePipeline(...)
,用于 langchain。
3. 定义可调用工具(如 shell 执行器)
from langchain.tools import Tool
import subprocess
def execute_shell(command: str) -> str:
try:
return subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT, timeout=10).decode("utf-8")
except subprocess.CalledProcessError as e:
return f"[Error]: {e.output.decode('utf-8')}"
shell_tool = Tool(name="shell", func=execute_shell, description="Execute shell command on local system")
4. 构建 Agent
from langchain.agents import initialize_agent, AgentType
from langchain.agents.agent_toolkits import Tool
tools = [shell_tool] # 你也可以加入 python 执行器、浏览器搜索器等
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
# 测试
response = agent.run("列出当前目录下的所有文件,并显示文件大小")
print(response)
5. FastAPI 封装成服务(可被Web调用)
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Request(BaseModel):
query: str
@app.post("/agent")
def run_agent(req: Request):
result = agent.run(req.query)
return {"result": result}
运行:
uvicorn agent_api:app --host 0.0.0.0 --port 8080
🔐 安全建议
项目 | 建议 |
---|---|
命令白名单 | 限制 LLM 只能调用指定命令(避免 rm -rf) |
沙盒执行 | 使用 docker 或 chroot 隔离指令 |
日志审计 | 记录调用历史 |
用户认证 | 增加 JWT 或 API Token |
📦 推荐工具扩展
- Python Executor Tool:解释 Python 代码(如计算器、数据分析)
- 文件系统工具:读写指定目录下的文本、Excel、PDF
- 网络爬虫 Tool:执行 requests/get 接口(需加认证)
- 插件系统:仿 OpenAI Function Call 的格式
✅ 示例自然语言任务
- 帮我统计当前目录下的 Python 文件数量
- 运行一个 Python 脚本,并返回输出
- 用 curl 请求一个 API 并展示返回内容
- 列出系统进程中占用内存最多的前5个
如果你需要我生成一个**完整部署项目(含工具定义、模型加载、API服务)**的代码压缩包,我可以立即打包给你。你希望使用哪种模型(如 Qwen-1.8B、ChatGLM2、Baichuan2)?