大模型人人都有,但让它在本地“动手干活”才是真正的生产力跃升。OpenClaw Agent 是一个轻量级、可编程的 AI 智能体框架,能让大模型调用 Shell、文件、HTTP、数据库等本地工具,自主完成复杂任务。本文面向零基础开发者,从安装部署到 5 个实战项目逐步拆解,帮你快速上手,并最后给出部署到腾讯云 Serverless 环境的方案,让数字员工 7×24 小时在线。
curl -fsSL https://ollama.com/install.sh | sh 并拉取模型 ollama pull qwen2.5:7b-q4_K_M# 创建项目目录
mkdir openclaw-lab && cd openclaw-lab
# 创建虚拟环境(可选)
python3 -m venv venv && source venv/bin/activate
# 安装核心包(假设开源版本)
pip install openclaw-agent python-dotenv在项目根目录新建 .env(若使用 Ollama 则无需 KEY):
# 使用 Ollama
OLLAMA_BASE_URL=http://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至此,环境已就绪。下面我们通过 5 个实战项目逐步熟悉 OpenClaw 的使用。
在动手前,理解三个关键点:
run 方法,供 Agent 调用。目标:让 Agent 写一段欢迎语并保存到文件。
代码 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 即看到生成内容。
意义:验证 Agent 能调用基础文件工具,完成任务拆解。
目标:统计指定目录下代码总行数,并输出前 5 大文件。
新建 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", ".java", ".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]]})组装 Agent:
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)收获:学会自定义工具,让 Agent 拥有领域能力。
目标:检查系统日志(/var/log/syslog)中最近 100 行的 ERROR,若超过 3 条则生成告警文件。
无需新工具,直接利用 shell_exec 和 file_io。
task = """
1. 执行 shell_exec: tail -n 100 /var/log/syslog
2. 统计输出中包含 'ERROR' 的行数
3. 如果大于 3,则使用 file_io 写入 /tmp/alert.md,内容为 '发现错误数: <count>',否则写入 '日志正常'
"""
agent.run(task)亮点:Agent 自主判断条件并分支执行。
目标:调用免费天气 API(如 wttr.in)获取某城市天气,通过 HTTP 工具推送至本地 Webhook。
工具:使用内置 HttpTool。
from openclaw.tools import HttpTool
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 到 http://localhost:9999/notify,body为{'msg': '...'}
"""
agent.run(task)关键:Agent 会解析第一次返回,再构造第二次请求,体现链式调用。
目标:连接本地 SQLite 数据库,查询上月销售数据,生成 Markdown 报表。
自定义工具 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])Agent 任务:
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)价值:模拟真实业务场景,Agent 需要理解 SQL 并格式化输出。
本地跑通后,如何让数字员工 7×24 运行?推荐 腾讯云函数(SCF) + 定时触发器。
openclaw-agent 等)打包为 .zip。main 逻辑封装为 main_handler(event, context),从环境变量读取配置。config.yaml。通过这种方式,你的 OpenClaw Agent 就成为云端永不停歇的数字员工,按预设节奏执行监控、分析、告警等任务。
通过以上 5 个项目,你已掌握:
下一步,你可以为 Agent 添加更多工具:发送邮件、操作 Docker、调用企业微信 API,甚至结合向量数据库构建本地知识问答。OpenClaw 的灵活设计让这一切变得简单。不要让你的大模型只停留在聊天窗,赋予它“手脚”,让它真正为你“干活”吧!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。