Hermes Agent 微信对接部署指南

Hermes Agent 微信对接部署指南

微信与AI Agent对接示意

引言

在当今企业数字化转型浪潮中,微信作为中国最主流的即时通讯平台,拥有超过 13 亿月活用户,是企业内部协作和客户服务的核心渠道。而 Hermes Agent 作为 NousResearch 推出的开源自主代理框架,具备强大的任务编排、工具调用和定时调度能力,能够将 AI 能力无缝嵌入到各类业务场景中。

将 Hermes Agent 与微信打通,意味着你可以让 AI Agent 在微信群中自动回复问题、定时推送数据报表、接收指令执行运维操作——从”被动聊天”进化为”主动执行”。本文将详细讲解如何部署 Hermes Agent 与微信的对接方案,涵盖架构设计、环境搭建、代码实现、安全加固等关键环节。

官方文档参考:Hermes Agent Docs


一、整体架构设计

微信与 Hermes Agent 的对接本质上是一个消息桥接问题。微信没有开放的 Bot API(不同于 Slack/Telegram),因此需要借助第三方微信协议适配层,将微信消息转发至 Hermes Agent 的输入端,再将 Agent 的响应回传至微信。

架构拓扑

┌──────────┐     WebSocket      ┌──────────────┐     HTTP/API     ┌──────────────┐
│  微信客户端  │◄────────────────►│  WeChat Bridge │◄──────────────►│  Hermes Agent │
│ (个人/企业) │    (消息收发)      │  (wechaty等)   │   (LLM调用)     │  (核心引擎)    │
└──────────┘                    └──────────────┘                  └──────────────┘
                                      │                                │
                                      │  消息持久化                      │  工具/技能调用
                                      ▼                                ▼
                                ┌──────────────┐              ┌──────────────┐
                                │  Redis/SQLite │              │  外部服务/API │
                                │  (消息队列)    │              │  (运维/数据)  │
                                └──────────────┘              └──────────────┘

核心组件对比

组件 推荐方案 适用场景 许可证
微信协议层 Wechaty 个人号/企业微信 Apache-2.0
微信协议层 itchat 简单个人号测试 MIT
微信协议层 企业微信官方API 企业级生产环境 商用
消息桥接 自研 Flask/FastAPI 服务 所有场景
Agent框架 Hermes Agent 任务编排+定时调度 开源
消息持久化 Redis 高并发生产环境 BSD
消息持久化 SQLite 低流量/开发调试 Public Domain

二、环境搭建与依赖安装

2.1 基础环境要求

项目 要求
操作系统 Linux (Ubuntu 20.04+) / macOS
Python 3.10+
Node.js 18+ (Wechaty 依赖)
Hermes Agent 已安装并配置完成
Redis 7.0+ (可选,生产推荐)

2.2 安装 Hermes Agent

如果你尚未安装 Hermes Agent,可通过以下方式快速部署:

# 克隆仓库
git clone https://github.com/NousResearch/hermes-agent.git
cd hermes-agent

# 安装依赖
pip install -r requirements.txt

# 配置 LLM Provider(以 OpenAI 为例)
export OPENAI_API_KEY="sk-your-key-here"

# 启动 Agent
python -m hermes_agent.agent --profile default

更多安装细节请参考 Hermes Agent 安装文档

2.3 安装 Wechaty 及桥接服务

# 安装 Wechaty
npm install wechaty
npm install wechaty-puppet-wechat4u   # Web协议Puppet
# 或使用更稳定的UOS协议:
npm install wechaty-puppet-uos

# 安装 Python 桥接服务依赖
pip install fastapi uvicorn redis websockets aioredis

三、核心代码实现

3.1 Wechaty 消息监听服务(Node.js)

以下代码实现了一个 Wechaty Bot,监听微信群消息并通过 HTTP 转发给 Hermes Agent:

// bridge/wechaty-bot.js
const { WechatyBuilder } = require('wechaty');
const puppet = 'wechaty-puppet-wechat4u';

const bot = WechatyBuilder.build({ puppet });
const HERMES_ENDPOINT = 'http://localhost:8080/api/message';

bot
  .on('scan', (qrcode, status) => {
    console.log(`扫描二维码登录: ${status}n${qrcode}`);
    // 可将 qrcode 生成图片,发送到管理群提醒扫码
  })
  .on('login', user => console.log(`用户 ${user} 登录成功`))
  .on('message', async msg => {
    // 只处理文本消息,过滤群消息中非@Bot的内容
    if (msg.type() !== bot.Message.Type.Text) return;

    const text = msg.text();
    const room = msg.room();
    const from = msg.talker();

    // 群聊中只有 @Bot 才响应
    if (room && !text.includes('@Bot')) return;

    const payload = {
      text: text.replace('@Bot', '').trim(),
      from: from.name(),
      room: room ? room.topic() : 'direct',
      timestamp: Date.now()
    };

    try {
      const res = await fetch(HERMES_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const data = await res.json();
      const reply = data.reply || '处理中,请稍后...';

      if (room) {
        await room.say(reply);
      } else {
        await from.say(reply);
      }
    } catch (err) {
      console.error('Hermes Agent 调用失败:', err);
    }
  })
  .start();

3.2 Hermes Agent 消息处理服务(Python)

这是接收 Wechaty 转发消息并与 Hermes Agent 交互的 FastAPI 服务:

# bridge/hermes_gateway.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import httpx
import redis
import json

app = FastAPI(title="Hermes-WeChat Gateway")
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)

HERMES_API = "http://localhost:5000/v1/chat/completions"

class WeChatMessage(BaseModel):
    text: str
    from_: str  # 使用 from_ 避免与Python关键字冲突
    room: str
    timestamp: int

@app.post("/api/message")
async def handle_message(msg: WeChatMessage):
    """接收微信消息,转发至 Hermes Agent,返回响应"""
    # 1. 消息持久化
    r.setex(
        f"wechat:msg:{msg.timestamp}",
        3600,
        json.dumps(msg.dict())
    )

    # 2. 调用 Hermes Agent
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            resp = await client.post(
                HERMES_API,
                json={
                    "messages": [
                        {"role": "system", "content": "你是微信群的AI助手,简洁准确地回答问题。"},
                        {"role": "user", "content": msg.text}
                    ],
                    "context": {
                        "from": msg.from_,
                        "room": msg.room
                    }
                }
            )
            data = resp.json()
            reply = data.get("choices", [{}])[0].get("message", {}).get("content", "")
    except httpx.TimeoutException:
        reply = "⏳ Agent 响应超时,请稍后再试"
    except Exception as e:
        reply = f"⚠️ 内部错误: {str(e)}"
        raise HTTPException(status_code=500, detail=str(e))

    # 3. 响应持久化
    r.setex(
        f"wechat:reply:{msg.timestamp}",
        3600,
        json.dumps({"reply": reply, "original": msg.text})
    )

    return {"reply": reply, "timestamp": msg.timestamp}

@app.get("/api/history/{room}")
async def get_history(room: str, limit: int = 20):
    """查询某群的最近对话历史"""
    keys = r.keys(f"wechat:reply:*")
    history = []
    for k in keys[:limit]:
        item = json.loads(r.get(k))
        if item.get("original"):
            history.append(item)
    return {"room": room, "history": history}

启动桥接服务:

# 启动 Hermes Agent(如已运行则跳过)
python -m hermes_agent.agent --profile default &

# 启动 FastAPI Gateway
uvicorn hermes_gateway:app --host 0.0.0.0 --port 8080 &

# 启动 Wechaty Bot
node wechaty-bot.js &

四、定时任务与主动推送

Hermes Agent 的核心优势之一是其Cron 定时调度能力。我们可以利用此功能,让 Agent 在微信中主动推送信息,而非仅被动回复。

4.1 配置定时推送任务

在 Hermes Agent 的 Cron 配置中添加定时任务:

# ~/.hermes/profiles/default/cron/daily-report.yml
name: "每日数据报告推送"
schedule: "0 9 * * *"       # 每天早上9点
task: |
  调用内部数据API获取昨日业务数据,
  生成简洁的中文摘要报告,
  然后通过微信桥接服务推送到"管理层日报群"
destination: "wechat:room:管理层日报群"
enabled: true

4.2 主动推送 API 扩展

在 Gateway 中增加主动推送接口:

# bridge/hermes_gateway.py (追加)
@app.post("/api/push")
async def push_to_wechat(room: str, message: str):
    """Hermes Cron 任务调用此接口,主动向微信群推送消息"""
    # 此接口由 Wechaty Bot 的 HTTP 控制端实现
    async with httpx.AsyncClient(timeout=10.0) as client:
        resp = await client.post(
            "http://localhost:3000/send",  # Wechaty HTTP Pad
            json={"room": room, "message": message}
        )
    return {"status": "sent", "room": room}

定时推送场景一览

场景 Cron 表达式 推送内容
每日业务日报 0 9 * * * 关键指标汇总
每周安全扫描报告 0 10 * * 1 安全漏洞检查结果
服务器异常告警 实时(Webhook触发) CPU/内存/磁盘告警
会议纪要自动整理 30 17 * * 1-5 当日会议摘要
代码Review提醒 0 10 * * * 待Review PR列表

五、安全加固与生产部署

微信对接涉及敏感的账号与数据,安全措施不可忽视。

5.1 通信安全

# 1. 使用 HTTPS(Nginx反向代理)
server {
    listen 443 ssl;
    server_name your-domain.com;

    ssl_certificate     /etc/ssl/certs/your-cert.pem;
    ssl_certificate_key /etc/ssl/private/your-key.pem;

    location /api/ {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

# 2. API 认证 — 在 Gateway 中添加 Token 校验
# hermes_gateway.py 中增加认证中间件
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
security = HTTPBearer()

VALID_TOKENS = {"hermes-wechat-token-2026"}

async def verify_token(credentials: HTTPAuthorizationCredentials = None):
    if credentials and credentials.credentials in VALID_TOKENS:
        return True
    raise HTTPException(status_code=401, detail="Invalid token")

5.2 消息过滤与限流

# 敏感词过滤 + 频率限制
SENSITIVE_WORDS = ["密码", "token", "secret", "api_key"]
RATE_LIMIT = 5  # 每分钟最多5条消息

def filter_message(text: str) -> str:
    """过滤敏感信息,防止 Agent 泄露密钥"""
    for word in SENSITIVE_WORDS:
        if word.lower() in text.lower():
            return "⚠️ 消息包含敏感内容,已过滤处理"
    return text

@app.middleware("http")
async def rate_limiter(request, call_next):
    ip = request.client.host
    key = f"rate:{ip}"
    count = r.incr(key)
    if count == 1:
        r.expire(key, 60)
    if count > RATE_LIMIT:
        return JSONResponse(status_code=429, content={"error": "请求过于频繁"})
    return await call_next(request)

5.3 Docker Compose 生产部署

# docker-compose.yml
version: "3.9"
services:
  hermes-agent:
    image: nousresearch/hermes-agent:latest
    environment:
      - OPENAI_API_KEY=${OPENAI_API_KEY}
    volumes:
      - ./hermes-config:/root/.hermes
    ports:
      - "5000:5000"
    restart: always

  hermes-gateway:
    build: ./bridge
    environment:
      - REDIS_URL=redis://redis:6379/0
      - AUTH_TOKEN=${AUTH_TOKEN}
    ports:
      - "8080:8080"
    depends_on:
      - hermes-agent
      - redis
    restart: always

  redis:
    image: redis:7-alpine
    volumes:
      - redis-data:/data
    restart: always

  wechaty:
    image: wechaty/wechaty:latest
    environment:
      - WECHATY_PUPPET=wechaty-puppet-uos
      - WECHATY_PUPPET_PADLOCAL_TOKEN=${PADLOCAL_TOKEN}
    ports:
      - "3000:3000"
    depends_on:
      - hermes-gateway
    restart: always

volumes:
  redis-data:

启动全部服务:

docker-compose up -d
# 查看运行状态
docker-compose ps
# 查看日志
docker-compose logs -f hermes-gateway

总结

本文完整讲解了 Hermes Agent 与微信对接的部署方案,核心要点包括:

  1. 架构设计:Wechaty 作为微信协议层 → FastAPI Gateway 消息桥接 → Hermes Agent 智能处理,三层架构清晰分工
  2. 代码实现:提供了 Wechaty Bot 和 FastAPI Gateway 的完整代码,可直接部署使用
  3. 定时推送:利用 Hermes Agent 的 Cron 能力实现主动推送,突破被动响应的限制
  4. 安全加固:HTTPS加密、Token认证、敏感词过滤、频率限制四道防线保障生产安全
  5. 容器化部署:Docker Compose 方案一键启动全部服务,便于运维管理

微信与 AI Agent 的融合正在重塑企业沟通与自动化边界。Hermes Agent 的灵活技能系统和定时调度机制,使其成为微信场景下的理想 Agent 后端。期待你在实际业务中发掘更多可能性!


FAQ

Q: Wechaty 使用 Web 协议登录微信,会不会被封号?
A: Web 协议确实存在一定风险。生产环境建议使用企业微信官方 API(合规无风险),或购买 PadLocal Token 使用更稳定的 UOS 协议。Wechaty 官方也推荐优先使用企业微信 Puppet。

Q: Hermes Agent 是否支持企业微信?
A: 完全支持。只需将 Wechaty Puppet 替换为 wechaty-puppet-wxwork(企业微信),其余架构和代码无需改动。企业微信 API 更稳定,适合正式生产部署。

Q: 消息延迟怎么处理?LLM 响应太慢怎么办?
A: 可以采取三种策略:(1) 先发一条”正在思考…”的即时回复;(2) 在 Gateway 中设置 30s 超时,超时后返回提示;(3) 对于高频简单问题,建立缓存层直接命中回复,无需每次调用 LLM。

Q: 如何监控整个对接链路的健康状态?
A: 在 Gateway 中添加 /api/health 健康检查端点,监控 Redis 连接、Hermes Agent 可用性、Wechaty 在线状态。结合 Prometheus + Grafana 可实现可视化监控面板。

Q: 多个微信群如何分别配置不同的 Agent 行为?
A: 在 Hermes Agent 中创建多个 Profile(~/.hermes/profiles/<name>/),每个 Profile 配置不同的技能和 Prompt。Gateway 根据消息来源的 room 字段路由到对应的 Profile,实现群级个性化。

Q: 数据隐私合规方面有什么建议?
A: (1) 所有聊天数据本地存储,不上传第三方;(2) Redis 设置 TTL 自动过期;(3) 对涉及个人信息的内容做脱敏处理;(4) 遵守《个人信息保护法》,明确告知群成员 AI Agent 的存在和数据使用范围。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片快捷回复

    暂无评论内容