项目目标
本文完成以下目标:在本地部署 OpenClaw Agent 框架,并通过 5 个难度递增的实战项目,实现文件操作、自定义工具、日志分析、HTTP 调用和数据库查询等真实场景任务。最后提供将 Agent 部署到腾讯云 Serverless 环境、实现定时自动运行的方案。
最终效果
完成部署后,Agent 能够接收自然语言任务,自主调用 shell、文件、HTTP、数据库等工具,生成问候语、统计代码行数、巡检日志异常、查询天气并推送通知、从 SQLite 查询数据并生成 Markdown 报表。部署到腾讯云后,Agent 可 7×24 小时按预设计划执行任务。
技术方案
OpenClaw Agent 是一个轻量级 AI 智能体框架,基于 ReAct 循环(Reason → Act → Observe)驱动 LLM 调用工具完成任务。本文使用本地推理后端 Ollama 加载 Qwen2.5 7B 模型,通过 YAML 配置文件注册 shell_exec、file_io、http_request 等工具,并支持自定义 Python 工具扩展。
环境与依赖
- 操作系统:Ubuntu 20.04 / macOS / Windows WSL2
- Python 3.10 或以上
- 推理后端(二选一):
- Ollama(推荐本地):通过
curl -fsSL https://ollama.com/install.sh | sh安装,拉取模型ollama pull qwen2.5:7b-q4_K_M - OpenAI API(备选):需 API Key
- Ollama(推荐本地):通过
- Python 依赖包:
openclaw-agent、python-dotenv
项目结构
openclaw-lab/
├── .env
├── config.yaml
├── hello_agent.py
├── tools/
│ ├── code_stats.py
│ └── sqlite_tool.py
├── log_agent.py
├── weather_agent.py
└── report_agent.py
.env:环境变量,配置 Ollama 或 OpenAI 地址config.yaml:Agent 核心配置,指定 LLM 提供商、模型、工具列表、最大迭代次数- 各
.py文件:对应 5 个实战项目的 Agent 程序 tools/:自定义工具模块
核心实现
1. 最小配置文件
在项目根目录新建 .env(若使用 Ollama 则无需 KEY):
# 使用 Ollama
OLLAMA_BASE_URL=https://localhost:11434
# 或使用 OpenAI 兼容接口
# OPENAI_API_KEY=sk-xxx
# OPENAI_BASE_URL=https://api.openai.com/v1
新建 config.yaml:
llm:
provider: ollama # 或 openai
model: qwen2.5:7b-q4_K_M
temperature: 0.3
tools:
- shell_exec
- file_io
- http_request
max_iterations: 6
2. 项目 1:Hello World —— 自动生成并保存问候语
创建 hello_agent.py:
from openclaw import Agent
from openclaw.tools import FileTool
agent = Agent.from_config("config.yaml")
agent.register_tool(FileTool())
task = """
请用中文写一段欢迎语,包含当前日期,然后使用 file_io 保存到 /tmp/welcome.txt。
"""
agent.run(task)
运行方法:执行 python hello_agent.py。
结果验证:检查 /tmp/welcome.txt 文件内容是否包含中文欢迎语和当前日期。
3. 项目 2:代码行数统计器(自定义工具)
创建 tools/code_stats.py:
from pathlib import Path
import json
from openclaw.tool import Tool
class CodeStatsTool(Tool):
name = "code_stats"
description = "统计目录下代码文件行数,返回总行数及最多行数的前5个文件"
def run(self, directory: str = ".") -> str:
total = 0
files = []
for p in Path(directory).rglob("*"):
if p.suffix in [".py", ".js", ".ja va", ".go", ".c", ".cpp"] and p.is_file():
try:
lines = len(p.read_text(encoding="utf-8").splitlines())
total += lines
files.append((str(p), lines))
except:
continue
files.sort(key=lambda x: x[1], reverse=True)
return json.dumps({"total_lines": total, "top5": [{"file": f, "lines": l} for f, l in files[:5]]})
创建 stats_agent.py:
from openclaw import Agent
from tools.code_stats import CodeStatsTool
agent = Agent.from_config("config.yaml")
agent.register_tool(CodeStatsTool())
task = "使用 code_stats 分析 /path/to/your/project,将结果打印出来"
agent.run(task)
运行方法:执行 python stats_agent.py,将 /path/to/your/project 替换为实际代码目录。
结果验证:观察控制台输出,应包含总行数和前 5 大文件信息。
4. 项目 3:日志异常巡检员
创建 log_agent.py:
from openclaw import Agent
from openclaw.tools import FileTool, ShellTool
agent = Agent.from_config("config.yaml")
agent.register_tool(FileTool())
agent.register_tool(ShellTool())
task = """
1. 执行 shell_exec: tail -n 100 /var/log/syslog
2. 统计输出中包含 'ERROR' 的行数
3. 如果大于 3,则使用 file_io 写入 /tmp/alert.md,内容为 '发现错误数: ',否则写入 '日志正常'
"""
agent.run(task)
运行方法:执行 python log_agent.py(需确保有 /var/log/syslog 访问权限)。
结果验证:检查 /tmp/alert.md 文件内容是否正确反映日志状态。
5. 项目 4:多工具协作 —— 查询天气并发送通知
创建 weather_agent.py:
from openclaw import Agent
from openclaw.tools import HttpTool
agent = Agent.from_config("config.yaml")
agent.register_tool(HttpTool())
task = """
1. 使用 http_request GET https://wttr.in/Beijing?format=%C+%t 获取天气(如 'Sunny 5°C')
2. 将结果拼成 '当前北京天气:xxx'
3. 使用 http_request POST 到 https://localhost:9999/notify,body为{'msg': '...'}
"""
agent.run(task)
运行方法:执行 python weather_agent.py。需提前在本地启动一个 Webhook 服务监听 localhost:9999(可用 nc -l 9999 简单测试)。
结果验证:Webhook 服务端应收到包含天气信息的 POST 请求。
6. 项目 5:数据库查询 + 报表生成(含 SQLite)
创建 tools/sqlite_tool.py:
import sqlite3, json
from openclaw.tool import Tool
class SQLiteQueryTool(Tool):
name = "sql_query"
description = "执行只读 SQL 查询,返回 JSON 结果"
def run(self, db_path: str, sql: str) -> str:
conn = sqlite3.connect(db_path)
cur = conn.cursor()
cur.execute(sql)
rows = cur.fetchall()
cols = [d[0] for d in cur.description]
conn.close()
return json.dumps([dict(zip(cols, row)) for row in rows])
创建 report_agent.py:
from openclaw import Agent
from tools.sqlite_tool import SQLiteQueryTool
agent = Agent.from_config("config.yaml")
agent.register_tool(SQLiteQueryTool())
task = """
请查询 /data/sales.db 中,上月(2026-06)各品类的总销量,SQL 语句为:
SELECT category, SUM(quantity) FROM sales WHERE strftime('%Y-%m', date)='2026-06' GROUP BY category;
将结果转换为 Markdown 表格,保存到 /tmp/report.md。
"""
agent.run(task)
运行方法:执行 python report_agent.py。需准备一个包含 sales 表的 SQLite 数据库文件 /data/sales.db。
结果验证:检查 /tmp/report.md 文件是否包含 Markdown 格式的品类销量报表。
配置说明
- LLM 后端切换:修改
config.yaml中的provider为openai,并确保.env中配置了OPENAI_API_KEY和OPENAI_BASE_URL。 - 工具注册:内置工具(
FileTool、ShellTool、HttpTool)需在 Agent 中显式注册;自定义工具需先实例化后调用register_tool。 - 最大迭代次数:
max_iterations控制 ReAct 循环上限,复杂任务可能需要增大。 - 温度参数:
temperature: 0.3降低 LLM 随机性,提高任务执行稳定性。
运行方法
- 确保 Ollama 服务已启动,且模型
qwen2.5:7b-q4_K_M已拉取。 - 进入项目目录
openclaw-lab,激活虚拟环境(如已创建)。 - 按需执行对应项目的 Python 脚本,例如
python hello_agent.py。 - 观察终端输出,Agent 会逐步展示思考、行动和观察过程。
结果验证
- 项目 1:检查
/tmp/welcome.txt文件存在且内容符合预期。 - 项目 2:终端输出包含
total_lines和top5信息。 - 项目 3:检查
/tmp/alert.md文件内容(条件分支结果)。 - 项目 4:Webhook 服务端收到 POST 请求。
- 项目 5:检查
/tmp/report.md文件包含 Markdown 表格。
常见问题
- Ollama 模型未加载:运行
ollama list确认模型存在,若未拉取则执行ollama pull qwen2.5:7b-q4_K_M。 - 配置文件解析错误:检查
config.yaml缩进(YAML 要求空格对齐),工具列表项前加-。 - 工具未注册:注册内置工具时需导入对应类,例如
from openclaw.tools import FileTool。 - 自定义工具未找到:确保
tools/目录下有__init__.py文件(可为空),或直接在脚本中引用相对路径。 - 网络问题:使用 wttr.in 或 OpenAI API 时需确保网络可达。
后续优化
- 云端部署:将项目打包,改造入口函数为
main_handler(event, context),部署到腾讯云函数(SCF),配合定时触发器实现自动化运行。模型后端可切换为 OpenAI API 或腾讯混元 API。 - 持久化存储:将生成的文件上传至腾讯云对象存储(COS),使用 COS SDK 实现报告长期保存。
- 工具扩展:添加邮件发送、Docker 操作、企业微信/钉钉通知等工具,增强 Agent 能力。
- 知识库集成:结合向量数据库(如 Chroma、FAISS)实现本地知识问答,让 Agent 具备领域知识检索能力。
验证清单
- 确认 Ollama 服务运行正常,模型可用。
- 确认
.env和config.yaml配置正确。 - 依次运行 5 个项目脚本,每个脚本均能正常结束,无报错。
- 检查每个项目对应的输出文件或终端结果,确认 Agent 完成了任务描述。
