AI 深度技能之-解读Hermes Agent(二)- 简单案例

3 阅读2分钟

通过一个天气预报智能体的实战案例,了解一下它是如何从开发环境搭建到上线的全流程。

一、开发环境搭建

1.1 一键安装(最快方式)

# 适用于 macOS / Linux / WSL2
curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash -x

# 刷新环境变量
source ~/.bashrc  # 或 source ~/.zshrc

# 验证安装
hermes --version

安装脚本会自动处理 Python 3.10+、Node.js、uv 包管理器等所有依赖,典型耗时 3-5 分钟。

1.2 源码安装(开发者推荐)

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

# 创建虚拟环境
python3 -m venv venv
source venv/bin/activate

# 安装核心依赖
uv pip install -e ".[all,dev]"

# 运行测试验证
python -m pytest tests/ -q

1.3 Docker 部署(开发测试环境)

# 拉取镜像
docker pull registry.example.com/hermes-agent:latest

# 快速启动
docker run -d \
  --name hermes-agent \
  -p 8080:8080 \
  -v $(pwd)/data:/app/data \
  hermes-agent

1.4 基础配置

# 启动交互式配置向导
hermes setup

配置向导会引导完成:

  • 模型提供商选择:支持 OpenAI、Anthropic、OpenRouter、DeepSeek 等 200+ 模型
  • API Key 配置:AES-256 加密存储于 ~/.hermes/.env
  • 记忆系统:启用/禁用跨会话持久化记忆
  • 消息通道:配置 Telegram/Discord/Slack 等网关
# 验证安装和配置
hermes chat "你好,介绍一下你自己"
# 收到回复即代表成功

二、开发实例:创建天气预报智能体

2.1 项目目标

创建一个能自主查询天气、分析出行建议的智能体,具备以下能力:

  • 调用外部天气 API 获取实时数据
  • 根据天气情况自动给出出行建议
  • 记忆用户的城市偏好,下次直接复用

2.2 技能开发

~/.hermes/skills/ 目录下创建自定义技能。技能结构规范如下:

~/.hermes/skills/
└── weather_query/
    ├── config.yaml      # 技能元数据
    ├── handler.py       # 核心逻辑
    └── test_cases/      # 测试用例

技能配置 config.yaml

name: weather_query
description: 获取指定城市的实时天气和出行建议
version: 1.0.0
enabled: true

核心逻辑 handler.py

import requests
from datetime import datetime

# 使用 @skill 装饰器注册技能
@skill(name="weather_query", priority=1)
def query_weather(context):
    """查询天气的主函数"""
    city = context.get("city", "Beijing")
    
    # 调用天气 API
    api_key = os.getenv("WEATHER_API_KEY")
    url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    
    response = requests.get(url)
    data = response.json()
    
    if response.status_code == 200:
        temp = data["main"]["temp"]
        condition = data["weather"][0]["description"]
        
        # 智能出行建议
        advice = generate_advice(temp, condition)
        
        return {
            "city": city,
            "temperature": temp,
            "condition": condition,
            "advice": advice,
            "timestamp": datetime.now().isoformat()
        }
    else:
        return {"error": f"无法获取{city}的天气数据"}

def generate_advice(temp, condition):
    """根据天气生成出行建议"""
    if "rain" in condition.lower():
        return "🌧️ 有雨,建议带伞,注意路面湿滑"
    elif temp > 30:
        return "☀️ 高温天气,建议减少户外活动,注意补水"
    elif temp < 0:
        return "❄️ 寒冷天气,注意保暖,道路可能结冰"
    else:
        return "✅ 天气适宜,适合户外活动"

2.3 测试技能

# 列出所有已安装技能
hermes skill list --format json

# 直接在命令行测试技能调用
hermes skill run weather_query --params '{"city": "Shanghai"}'

2.4 让技能关联长期记忆

Hermes 内置三层记忆模型,能让技能记住用户偏好:

from hermes.memory import MemoryEngine

# 初始化记忆引擎
memory = MemoryEngine(
    vector_store="redis://localhost:6379/0",
    embedding_model="all-MiniLM-L6-v2"
)

@skill(name="remember_city")
def remember_user_city(context):
    """记住用户偏好的城市"""
    user_id = context.get("user_id")
    city = context.get("city")
    
    # 写入长期记忆
    memory.set(f"user:{user_id}:preferred_city", city)
    
    return {"status": "saved", "city": city}

@skill(name="get_city_from_memory")
def get_preferred_city(context):
    """从记忆读取用户偏好"""
    user_id = context.get("user_id")
    city = memory.get(f"user:{user_id}:preferred_city")
    return {"city": city} if city else {"error": "未找到偏好城市"}

2.5 构建天气智能体工作流

通过 YAML 定义完整的智能体工作流:

# weather_agent.yaml
workflow:
  name: daily_weather_report
  description: 每日天气报告与出行建议
  schedule: "0 7 * * *"  # 每天早上7点执行
  
  steps:
    - name: get_preferred_city
      type: memory_query
      params:
        key: "user:preferred_city"
    
    - name: query_weather
      type: skill_call
      skill: weather_query
      depends_on: get_preferred_city
      params:
        city: "{{ steps.get_preferred_city.result.city }}"
    
    - name: notify_user
      type: gateway_send
      platform: telegram
      depends_on: query_weather
      params:
        message: |
          🌤️ 早安!
          今日天气:{{ steps.query_weather.result.condition }}
          气温:{{ steps.query_weather.result.temperature }}°C
          建议:{{ steps.query_weather.result.advice }}

执行工作流:

hermes workflow start --file weather_agent.yaml

三、生产环境部署

3.1 系统硬件要求

生产环境建议配置:

配置项开发环境生产环境(推荐)
CPU2核4核以上
内存4GB8-16GB
磁盘10GB50-100GB SSD
网络普通开放 8080/9090 端口

3.2 Docker Compose 部署(推荐)

创建 docker-compose.yml

version: '3.8'

services:
  hermes-core:
    image: registry.example.com/hermes-agent:latest
    container_name: hermes-agent
    restart: unless-stopped
    environment:
      - TZ=Asia/Shanghai
      - MAX_CONCURRENT=10
      - LOG_LEVEL=INFO
    volumes:
      - ./data:/app/data           # 持久化数据
      - ./logs:/var/log/hermes     # 日志目录
      - ~/.hermes/config.yml:/app/config.yml  # 配置文件
    ports:
      - "8080:8080"  # API 端口
    deploy:
      resources:
        limits:
          cpus: '2.0'
          memory: 4G
        reservations:
          cpus: '1.0'
          memory: 2G
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/actuator/health"]
      interval: 30s
      timeout: 10s
      retries: 3

  # 可选:Redis 记忆存储
  redis:
    image: redis:7-alpine
    container_name: hermes-redis
    restart: unless-stopped
    volumes:
      - ./redis-data:/data
    ports:
      - "6379:6379"

启动服务:

docker-compose up -d
docker-compose logs -f hermes-core  # 查看日志

3.3 高可用集群部署(企业级)

对于高并发场景,推荐使用 Kubernetes 集群:

# k8s-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hermes-agent-cluster
spec:
  replicas: 3
  selector:
    matchLabels:
      app: hermes-agent
  template:
    metadata:
      labels:
        app: hermes-agent
    spec:
      containers:
      - name: hermes
        image: registry.example.com/hermes-agent:latest
        resources:
          requests:
            memory: "2Gi"
            cpu: "1000m"
          limits:
            memory: "4Gi"
            cpu: "2000m"
        env:
        - name: HERMES_CLUSTER_NAME
          value: "production"
        - name: HERMES_NODE_ID
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        ports:
        - containerPort: 8080
        livenessProbe:
          httpGet:
            path: /actuator/health
            port: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: hermes-agent-lb
spec:
  selector:
    app: hermes-agent
  ports:
  - port: 8080
    targetPort: 8080
  type: LoadBalancer

3.4 云服务一键部署

腾讯云 Lighthouse 提供 Hermes Agent 一键部署镜像:

  1. 进入 Lighthouse → 实例 → 重装系统
  2. 选择「应用镜像」→「AI智能体」→「Hermes Agent」
  3. 等待自动完成,无需手动安装

四、生产运维

4.1 监控与可观测性

Hermes Agent 内置 Prometheus 指标端点,集成 Grafana 可实时监控:

# prometheus.yml
scrape_configs:
  - job_name: 'hermes-agent'
    static_configs:
      - targets: ['localhost:8080']
    metrics_path: '/actuator/prometheus'

关键监控指标:

  • hermes_task_success_rate:任务成功率
  • hermes_llm_latency_seconds:模型响应延迟(P99)
  • hermes_memory_usage_bytes:内存占用
  • hermes_tool_calls_total:工具调用次数
# 健康检查
curl http://localhost:8080/actuator/health
# 预期返回:{"status":"UP"}

4.2 可视化 Dashboard

Hermes Agent 官方提供了可视化 Dashboard:

# 部署 Dashboard
git clone https://github.com/NousResearch/hermes-webui.git
cd hermes-webui
npm install --production
npm start

# 访问 http://localhost:8787 查看

Dashboard 支持实时监控、日志检索、配置在线编辑及版本控制。

4.3 日志管理

# 查看实时日志
docker logs -f hermes-agent

# 配置日志轮转(写入 /var/log/hermes/agent.log)
hermes config set logging.level INFO
hermes config set logging.rotation.size 100MB
hermes config set logging.rotation.backups 10

# 集成 ELK 栈集中管理
# 将日志输出到 Logstash 进行聚合分析

4.4 备份与恢复

# 备份配置和记忆数据
tar -czf hermes-backup-$(date +%Y%m%d).tar.gz ~/.hermes/

# 自动化定期备份(Cron)
echo "0 2 * * * tar -czf /backup/hermes-$(date +\\%Y\\%m\\%d).tar.gz ~/.hermes/" | crontab -

# 从备份恢复
tar -xzf hermes-backup-20260101.tar.gz -C ~/

4.5 安全加固

生产环境必须执行以下安全措施:

  1. 禁止 root 运行:创建专用用户 hermes,所有操作在该用户下执行
  2. 配置防火墙:仅开放必要端口(如 8080),限制访问源 IP
  3. API Key 加密存储:使用 AES-256 加密,定期轮换
  4. 技能白名单:限制可执行的技能范围,防止恶意技能被加载
  5. 操作审计:启用详细日志,记录所有关键操作

防火墙规则示例:

# 仅允许特定 IP 访问
ufw allow from 192.168.1.0/24 to any port 8080
ufw enable

五、总结与快速索引

阶段关键命令参考章节
安装curl -fsSL [install_url] | bash1.1
配置hermes setup1.4
开发技能创建 ~/.hermes/skills/ 目录2.2
测试hermes skill run <name> --params2.3
部署docker-compose up -d3.2
监控curl localhost:8080/actuator/health4.1
备份tar -czf hermes-backup.tar.gz ~/.hermes/4.4