hermes-agent-guide

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Hermes Agent Guide

Hermes Agent 中文指南

Skill by ara.so — Hermes Skills collection.
This skill provides comprehensive knowledge of the Hermes Agent framework based on the most extensive Chinese guide available. Hermes Agent is a powerful open-source AI Agent framework that inherits from OpenClaw with significant upgrades in architecture, memory systems, skill ecosystem, and automation capabilities.
ara.so提供的Skill — Hermes技能集合。
本Skill基于目前最详尽的中文指南,提供Hermes Agent框架的全面知识。Hermes Agent是一款功能强大的开源AI Agent框架,继承自OpenClaw并在架构、内存系统、技能生态和自动化能力方面进行了重大升级。

What is Hermes Agent

什么是Hermes Agent

Hermes Agent is an advanced AI Agent framework developed by Nous Research that enables:
  • Autonomous Task Execution: Agents can plan, execute, and learn from complex multi-step tasks
  • Three-Layer Memory System: Session memory, persistent memory, and skill-level memory
  • Rich Skill Ecosystem: 47+ built-in tools across 7 categories, plus Skills Hub integration
  • MCP Protocol Support: Access to 6000+ Model Context Protocol services
  • Multi-Platform Integration: Connect to Discord, Slack, WeChat, Feishu, and 15+ platforms
  • Multi-Agent Orchestration: Coordinate multiple agents for complex workflows
Hermes Agent是由Nous Research开发的高级AI Agent框架,具备以下能力:
  • 自主任务执行:Agent可规划、执行复杂多步骤任务并从中学习
  • 三层内存系统:会话内存、持久化内存和技能级内存
  • 丰富的技能生态:7大分类下的47+内置工具,以及Skills Hub集成
  • MCP协议支持:可访问6000+ Model Context Protocol服务
  • 多平台集成:连接Discord、Slack、微信、飞书等15+平台
  • 多Agent编排:协调多个Agent完成复杂工作流

Installation

安装

Local Installation (Recommended for Development)

本地安装(推荐用于开发)

bash
undefined
bash
undefined

Clone the repository

Clone the repository

Create virtual environment

Create virtual environment

python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate

Install dependencies

Install dependencies

pip install -r requirements.txt
pip install -r requirements.txt

Copy environment template

Copy environment template

cp .env.example .env
cp .env.example .env

Edit .env with your configuration

Edit .env with your configuration

Required: OPENAI_API_KEY or other LLM provider keys

Required: OPENAI_API_KEY or other LLM provider keys

undefined
undefined

Docker Installation (Recommended for Production)

Docker安装(推荐用于生产环境)

bash
undefined
bash
undefined

Pull the official image

Pull the official image

docker pull nousresearch/hermes-agent:latest
docker pull nousresearch/hermes-agent:latest

Create docker-compose.yml

Create docker-compose.yml

cat > docker-compose.yml << EOF version: '3.8' services: hermes: image: nousresearch/hermes-agent:latest environment: - OPENAI_API_KEY=${OPENAI_API_KEY} - HERMES_MEMORY_TYPE=persistent volumes: - ./data:/app/data - ./skills:/app/skills ports: - "8080:8080" restart: unless-stopped EOF
cat > docker-compose.yml << EOF version: '3.8' services: hermes: image: nousresearch/hermes-agent:latest environment: - OPENAI_API_KEY=${OPENAI_API_KEY} - HERMES_MEMORY_TYPE=persistent volumes: - ./data:/app/data - ./skills:/app/skills ports: - "8080:8080" restart: unless-stopped EOF

Start the service

Start the service

docker-compose up -d
undefined
docker-compose up -d
undefined

VPS Deployment

VPS部署

bash
undefined
bash
undefined

On Ubuntu/Debian

On Ubuntu/Debian

sudo apt update && sudo apt install -y python3.11 python3-pip git
sudo apt update && sudo apt install -y python3.11 python3-pip git

Clone and setup

Clone and setup

git clone https://github.com/NousResearch/hermes-agent.git cd hermes-agent pip3 install -r requirements.txt
git clone https://github.com/NousResearch/hermes-agent.git cd hermes-agent pip3 install -r requirements.txt

Setup systemd service

Setup systemd service

sudo tee /etc/systemd/system/hermes-agent.service << EOF [Unit] Description=Hermes Agent Service After=network.target
[Service] Type=simple User=$USER WorkingDirectory=$(pwd) Environment="OPENAI_API_KEY=${OPENAI_API_KEY}" ExecStart=$(which python3) main.py Restart=always
[Install] WantedBy=multi-user.target EOF
sudo systemctl enable hermes-agent sudo systemctl start hermes-agent
undefined
sudo tee /etc/systemd/system/hermes-agent.service << EOF [Unit] Description=Hermes Agent Service After=network.target
[Service] Type=simple User=$USER WorkingDirectory=$(pwd) Environment="OPENAI_API_KEY=${OPENAI_API_KEY}" ExecStart=$(which python3) main.py Restart=always
[Install] WantedBy=multi-user.target EOF
sudo systemctl enable hermes-agent sudo systemctl start hermes-agent
undefined

Core Architecture

核心架构

Hermes Agent uses a five-layer architecture:
Hermes Agent采用五层架构:

1. Interface Layer

1. 接口层

Handles user interactions across multiple platforms:
python
from hermes.interface import DiscordInterface, SlackInterface, CLIInterface
处理多平台的用户交互:
python
from hermes.interface import DiscordInterface, SlackInterface, CLIInterface

CLI interface

CLI interface

cli = CLIInterface() cli.start()
cli = CLIInterface() cli.start()

Discord bot

Discord bot

discord = DiscordInterface( token=os.getenv("DISCORD_BOT_TOKEN"), intents=["messages", "guilds"] ) discord.run()
discord = DiscordInterface( token=os.getenv("DISCORD_BOT_TOKEN"), intents=["messages", "guilds"] ) discord.run()

Slack app

Slack app

slack = SlackInterface( token=os.getenv("SLACK_BOT_TOKEN"), signing_secret=os.getenv("SLACK_SIGNING_SECRET") ) slack.start()
undefined
slack = SlackInterface( token=os.getenv("SLACK_BOT_TOKEN"), signing_secret=os.getenv("SLACK_SIGNING_SECRET") ) slack.start()
undefined

2. Orchestration Layer

2. 编排层

Manages agent lifecycle and task coordination:
python
from hermes.orchestrator import AgentOrchestrator
from hermes.agent import HermesAgent

orchestrator = AgentOrchestrator()
管理Agent生命周期和任务协调:
python
from hermes.orchestrator import AgentOrchestrator
from hermes.agent import HermesAgent

orchestrator = AgentOrchestrator()

Create and register agents

Create and register agents

research_agent = HermesAgent( name="research_assistant", model="gpt-4", skills=["web_search", "summarization"] )
code_agent = HermesAgent( name="code_assistant", model="claude-3-opus", skills=["code_generation", "code_review"] )
orchestrator.register_agent(research_agent) orchestrator.register_agent(code_agent)
research_agent = HermesAgent( name="research_assistant", model="gpt-4", skills=["web_search", "summarization"] )
code_agent = HermesAgent( name="code_assistant", model="claude-3-opus", skills=["code_generation", "code_review"] )
orchestrator.register_agent(research_agent) orchestrator.register_agent(code_agent)

Execute coordinated task

Execute coordinated task

result = await orchestrator.execute_task( "Research the latest AI frameworks and generate a comparison report", agents=["research_assistant", "code_assistant"] )
undefined
result = await orchestrator.execute_task( "Research the latest AI frameworks and generate a comparison report", agents=["research_assistant", "code_assistant"] )
undefined

3. Agent Core Layer

3. Agent核心层

The brain of each agent:
python
from hermes.agent import HermesAgent
from hermes.memory import MemoryConfig
from hermes.skills import SkillRegistry

agent = HermesAgent(
    name="my_assistant",
    model="gpt-4-turbo",
    temperature=0.7,
    memory_config=MemoryConfig(
        session_memory=True,
        persistent_memory=True,
        vector_store="chromadb"
    ),
    skill_registry=SkillRegistry.load_default(),
    system_prompt="""You are a helpful AI assistant with access to 
    various tools and a persistent memory system."""
)
每个Agent的核心大脑:
python
from hermes.agent import HermesAgent
from hermes.memory import MemoryConfig
from hermes.skills import SkillRegistry

agent = HermesAgent(
    name="my_assistant",
    model="gpt-4-turbo",
    temperature=0.7,
    memory_config=MemoryConfig(
        session_memory=True,
        persistent_memory=True,
        vector_store="chromadb"
    ),
    skill_registry=SkillRegistry.load_default(),
    system_prompt="""You are a helpful AI assistant with access to 
    various tools and a persistent memory system."""
)

Agent automatically plans and executes

Agent automatically plans and executes

response = await agent.chat("Analyze my project's GitHub issues and create a priority matrix")
undefined
response = await agent.chat("Analyze my project's GitHub issues and create a priority matrix")
undefined

4. Tool Layer

4. 工具层

47+ built-in tools organized in 7 categories:
python
from hermes.tools import (
    WebSearchTool, FileSystemTool, GitHubTool,
    DatabaseTool, CodeExecutionTool, APIRequestTool
)
7大分类下的47+内置工具:
python
from hermes.tools import (
    WebSearchTool, FileSystemTool, GitHubTool,
    DatabaseTool, CodeExecutionTool, APIRequestTool
)

Configure tools

Configure tools

tools = [ WebSearchTool(api_key=os.getenv("SERPER_API_KEY")), GitHubTool(token=os.getenv("GITHUB_TOKEN")), FileSystemTool(allowed_paths=["/workspace"]), CodeExecutionTool(sandbox_mode=True), DatabaseTool(connection_string=os.getenv("DATABASE_URL")) ]
tools = [ WebSearchTool(api_key=os.getenv("SERPER_API_KEY")), GitHubTool(token=os.getenv("GITHUB_TOKEN")), FileSystemTool(allowed_paths=["/workspace"]), CodeExecutionTool(sandbox_mode=True), DatabaseTool(connection_string=os.getenv("DATABASE_URL")) ]

Attach to agent

Attach to agent

agent.add_tools(tools)
undefined
agent.add_tools(tools)
undefined

5. Integration Layer

5. 集成层

Connects to external services via MCP:
python
from hermes.mcp import MCPClient

mcp = MCPClient()
通过MCP连接外部服务:
python
from hermes.mcp import MCPClient

mcp = MCPClient()

Add MCP servers

Add MCP servers

mcp.add_server("filesystem", "npx -y @modelcontextprotocol/server-filesystem /workspace") mcp.add_server("github", "npx -y @modelcontextprotocol/server-github") mcp.add_server("postgres", "npx -y @modelcontextprotocol/server-postgres")
mcp.add_server("filesystem", "npx -y @modelcontextprotocol/server-filesystem /workspace") mcp.add_server("github", "npx -y @modelcontextprotocol/server-github") mcp.add_server("postgres", "npx -y @modelcontextprotocol/server-postgres")

Use in agent

Use in agent

agent.connect_mcp(mcp)
undefined
agent.connect_mcp(mcp)
undefined

Memory System

内存系统

Session Memory

会话内存

Temporary conversation context:
python
from hermes.memory import SessionMemory

session = SessionMemory(
    max_tokens=4096,
    summarization_threshold=3000
)
临时对话上下文:
python
from hermes.memory import SessionMemory

session = SessionMemory(
    max_tokens=4096,
    summarization_threshold=3000
)

Automatically managed during conversation

Automatically managed during conversation

agent.memory.session = session
undefined
agent.memory.session = session
undefined

Persistent Memory

持久化内存

Long-term knowledge storage:
python
from hermes.memory import PersistentMemory

persistent = PersistentMemory(
    backend="chromadb",
    collection_name="hermes_memory",
    embedding_model="text-embedding-3-small"
)
长期知识存储:
python
from hermes.memory import PersistentMemory

persistent = PersistentMemory(
    backend="chromadb",
    collection_name="hermes_memory",
    embedding_model="text-embedding-3-small"
)

Store important information

Store important information

await persistent.store( content="User prefers Python for backend development", metadata={"type": "preference", "category": "development"} )
await persistent.store( content="User prefers Python for backend development", metadata={"type": "preference", "category": "development"} )

Query relevant memories

Query relevant memories

memories = await persistent.query( "What are the user's coding preferences?", top_k=5 )
undefined
memories = await persistent.query( "What are the user's coding preferences?", top_k=5 )
undefined

Skill-Level Memory

技能级内存

Memory specific to each skill:
python
from hermes.skills import Skill

class ProjectManagementSkill(Skill):
    def __init__(self):
        super().__init__(name="project_management")
        self.memory = self.get_skill_memory()
    
    async def track_project(self, project_name: str, status: str):
        await self.memory.store({
            "project": project_name,
            "status": status,
            "timestamp": datetime.now()
        })
    
    async def get_active_projects(self):
        return await self.memory.query(
            "status:active",
            filter_type="metadata"
        )
每个技能专属的内存:
python
from hermes.skills import Skill

class ProjectManagementSkill(Skill):
    def __init__(self):
        super().__init__(name="project_management")
        self.memory = self.get_skill_memory()
    
    async def track_project(self, project_name: str, status: str):
        await self.memory.store({
            "project": project_name,
            "status": status,
            "timestamp": datetime.now()
        })
    
    async def get_active_projects(self):
        return await self.memory.query(
            "status:active",
            filter_type="metadata"
        )

Skills System

技能系统

Using Built-in Skills

使用内置技能

python
from hermes.skills import SkillRegistry

registry = SkillRegistry()
python
from hermes.skills import SkillRegistry

registry = SkillRegistry()

Load specific skills

Load specific skills

web_skill = registry.get("web_automation") data_skill = registry.get("data_analysis")
web_skill = registry.get("web_automation") data_skill = registry.get("data_analysis")

Load all skills from category

Load all skills from category

dev_skills = registry.get_category("development")
dev_skills = registry.get_category("development")

Attach to agent

Attach to agent

agent.add_skills([web_skill, data_skill])
undefined
agent.add_skills([web_skill, data_skill])
undefined

Creating Custom Skills

创建自定义技能

python
from hermes.skills import Skill, skill_action

class CustomResearchSkill(Skill):
    """Advanced research skill with citation tracking"""
    
    name = "advanced_research"
    description = "Perform deep research with source tracking"
    
    def __init__(self):
        super().__init__()
        self.sources = []
    
    @skill_action(
        description="Search and summarize academic papers",
        parameters={
            "query": {"type": "string", "required": True},
            "max_results": {"type": "integer", "default": 10}
        }
    )
    async def search_papers(self, query: str, max_results: int = 10):
        # Implementation
        results = await self.tools.web_search(
            f"{query} site:arxiv.org OR site:scholar.google.com",
            max_results=max_results
        )
        
        # Track sources
        for result in results:
            self.sources.append({
                "title": result.title,
                "url": result.url,
                "timestamp": datetime.now()
            })
        
        summary = await self.summarize(results)
        return {
            "summary": summary,
            "sources": self.sources
        }
    
    @skill_action(description="Generate bibliography from tracked sources")
    async def generate_bibliography(self):
        return "\n".join([
            f"- {s['title']}: {s['url']}"
            for s in self.sources
        ])
python
from hermes.skills import Skill, skill_action

class CustomResearchSkill(Skill):
    """Advanced research skill with citation tracking"""
    
    name = "advanced_research"
    description = "Perform deep research with source tracking"
    
    def __init__(self):
        super().__init__()
        self.sources = []
    
    @skill_action(
        description="Search and summarize academic papers",
        parameters={
            "query": {"type": "string", "required": True},
            "max_results": {"type": "integer", "default": 10}
        }
    )
    async def search_papers(self, query: str, max_results: int = 10):
        # Implementation
        results = await self.tools.web_search(
            f"{query} site:arxiv.org OR site:scholar.google.com",
            max_results=max_results
        )
        
        # Track sources
        for result in results:
            self.sources.append({
                "title": result.title,
                "url": result.url,
                "timestamp": datetime.now()
            })
        
        summary = await self.summarize(results)
        return {
            "summary": summary,
            "sources": self.sources
        }
    
    @skill_action(description="Generate bibliography from tracked sources")
    async def generate_bibliography(self):
        return "\n".join([
            f"- {s['title']}: {s['url']}"
            for s in self.sources
        ])

Register and use

Register and use

registry.register(CustomResearchSkill())
undefined
registry.register(CustomResearchSkill())
undefined

Skills Hub Integration

Skills Hub集成

python
from hermes.skills import SkillsHub

hub = SkillsHub(api_key=os.getenv("SKILLS_HUB_API_KEY"))
python
from hermes.skills import SkillsHub

hub = SkillsHub(api_key=os.getenv("SKILLS_HUB_API_KEY"))

Search for skills

Search for skills

results = hub.search("data visualization")
results = hub.search("data visualization")

Install skill

Install skill

skill = hub.install("community/advanced-charts")
skill = hub.install("community/advanced-charts")

Add to agent

Add to agent

agent.add_skill(skill)
undefined
agent.add_skill(skill)
undefined

Tool Categories

工具分类

1. Web & Network Tools

1. Web与网络工具

python
from hermes.tools import WebSearchTool, WebScrapingTool, APIRequestTool
python
from hermes.tools import WebSearchTool, WebScrapingTool, APIRequestTool

Web search

Web search

search = WebSearchTool(provider="serper", api_key=os.getenv("SERPER_API_KEY")) results = await search.search("latest AI news")
search = WebSearchTool(provider="serper", api_key=os.getenv("SERPER_API_KEY")) results = await search.search("latest AI news")

Web scraping

Web scraping

scraper = WebScrapingTool(user_agent="Hermes-Agent/1.0") content = await scraper.scrape("https://example.com")
scraper = WebScrapingTool(user_agent="Hermes-Agent/1.0") content = await scraper.scrape("https://example.com")

API requests

API requests

api = APIRequestTool() response = await api.request( method="POST", url="https://api.example.com/data", headers={"Authorization": f"Bearer {os.getenv('API_TOKEN')}"}, json={"query": "data"} )
undefined
api = APIRequestTool() response = await api.request( method="POST", url="https://api.example.com/data", headers={"Authorization": f"Bearer {os.getenv('API_TOKEN')}"}, json={"query": "data"} )
undefined

2. File System Tools

2. 文件系统工具

python
from hermes.tools import FileSystemTool

fs = FileSystemTool(
    base_path="/workspace",
    allowed_operations=["read", "write", "list"]
)
python
from hermes.tools import FileSystemTool

fs = FileSystemTool(
    base_path="/workspace",
    allowed_operations=["read", "write", "list"]
)

Read file

Read file

content = await fs.read_file("project/README.md")
content = await fs.read_file("project/README.md")

Write file

Write file

await fs.write_file("output/report.txt", "Report content")
await fs.write_file("output/report.txt", "Report content")

List directory

List directory

files = await fs.list_directory("project/src")
undefined
files = await fs.list_directory("project/src")
undefined

3. Code Execution Tools

3. 代码执行工具

python
from hermes.tools import CodeExecutionTool

executor = CodeExecutionTool(
    sandbox_mode=True,
    timeout=30,
    allowed_imports=["requests", "pandas", "numpy"]
)
python
from hermes.tools import CodeExecutionTool

executor = CodeExecutionTool(
    sandbox_mode=True,
    timeout=30,
    allowed_imports=["requests", "pandas", "numpy"]
)

Execute Python code

Execute Python code

result = await executor.execute_python(""" import pandas as pd data = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) print(data.describe()) """)
print(result.stdout) print(result.return_value)
undefined
result = await executor.execute_python(""" import pandas as pd data = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) print(data.describe()) """)
print(result.stdout) print(result.return_value)
undefined

4. Database Tools

4. 数据库工具

python
from hermes.tools import DatabaseTool

db = DatabaseTool(
    connection_string=os.getenv("DATABASE_URL"),
    read_only=False
)
python
from hermes.tools import DatabaseTool

db = DatabaseTool(
    connection_string=os.getenv("DATABASE_URL"),
    read_only=False
)

Query

Query

results = await db.query("SELECT * FROM users WHERE active = true")
results = await db.query("SELECT * FROM users WHERE active = true")

Execute with parameters

Execute with parameters

await db.execute( "INSERT INTO logs (message, level) VALUES ($1, $2)", ["Operation completed", "INFO"] )
undefined
await db.execute( "INSERT INTO logs (message, level) VALUES ($1, $2)", ["Operation completed", "INFO"] )
undefined

5. Version Control Tools

5. 版本控制工具

python
from hermes.tools import GitHubTool

github = GitHubTool(token=os.getenv("GITHUB_TOKEN"))
python
from hermes.tools import GitHubTool

github = GitHubTool(token=os.getenv("GITHUB_TOKEN"))

Create issue

Create issue

issue = await github.create_issue( repo="owner/repo", title="Bug: Memory leak in agent loop", body="Detailed description...", labels=["bug", "priority-high"] )
issue = await github.create_issue( repo="owner/repo", title="Bug: Memory leak in agent loop", body="Detailed description...", labels=["bug", "priority-high"] )

Create pull request

Create pull request

pr = await github.create_pull_request( repo="owner/repo", title="Fix memory leak", head="feature-branch", base="main", body="This PR fixes the memory leak issue" )
undefined
pr = await github.create_pull_request( repo="owner/repo", title="Fix memory leak", head="feature-branch", base="main", body="This PR fixes the memory leak issue" )
undefined

6. Communication Tools

6. 通讯工具

python
from hermes.tools import EmailTool, SlackTool
python
from hermes.tools import EmailTool, SlackTool

Send email

Send email

email = EmailTool( smtp_host=os.getenv("SMTP_HOST"), smtp_port=587, username=os.getenv("SMTP_USER"), password=os.getenv("SMTP_PASS") )
await email.send( to=["user@example.com"], subject="Daily Report", body="Here is your daily report...", attachments=["/reports/daily.pdf"] )
email = EmailTool( smtp_host=os.getenv("SMTP_HOST"), smtp_port=587, username=os.getenv("SMTP_USER"), password=os.getenv("SMTP_PASS") )
await email.send( to=["user@example.com"], subject="Daily Report", body="Here is your daily report...", attachments=["/reports/daily.pdf"] )

Slack notification

Slack notification

slack = SlackTool(token=os.getenv("SLACK_BOT_TOKEN")) await slack.send_message( channel="#general", text="Task completed successfully!" )
undefined
slack = SlackTool(token=os.getenv("SLACK_BOT_TOKEN")) await slack.send_message( channel="#general", text="Task completed successfully!" )
undefined

7. Data Processing Tools

7. 数据处理工具

python
from hermes.tools import DataAnalysisTool, ImageProcessingTool
python
from hermes.tools import DataAnalysisTool, ImageProcessingTool

Data analysis

Data analysis

analyzer = DataAnalysisTool() stats = await analyzer.analyze_csv("/data/sales.csv")
analyzer = DataAnalysisTool() stats = await analyzer.analyze_csv("/data/sales.csv")

Image processing

Image processing

image_tool = ImageProcessingTool() await image_tool.resize("/images/photo.jpg", width=800, height=600) await image_tool.convert("/images/photo.jpg", format="webp")
undefined
image_tool = ImageProcessingTool() await image_tool.resize("/images/photo.jpg", width=800, height=600) await image_tool.convert("/images/photo.jpg", format="webp")
undefined

Multi-Platform Integration

多平台集成

Discord Bot

Discord机器人

python
from hermes.platforms import DiscordPlatform

discord = DiscordPlatform(
    token=os.getenv("DISCORD_BOT_TOKEN"),
    command_prefix="!hermes"
)
python
from hermes.platforms import DiscordPlatform

discord = DiscordPlatform(
    token=os.getenv("DISCORD_BOT_TOKEN"),
    command_prefix="!hermes"
)

Register agent

Register agent

discord.register_agent(agent)
discord.register_agent(agent)

Custom command

Custom command

@discord.command(name="analyze") async def analyze_command(ctx, *, query: str): result = await agent.chat(query) await ctx.send(result)
discord.run()
undefined
@discord.command(name="analyze") async def analyze_command(ctx, *, query: str): result = await agent.chat(query) await ctx.send(result)
discord.run()
undefined

Slack App

Slack应用

python
from hermes.platforms import SlackPlatform

slack = SlackPlatform(
    token=os.getenv("SLACK_BOT_TOKEN"),
    signing_secret=os.getenv("SLACK_SIGNING_SECRET")
)

slack.register_agent(agent)
python
from hermes.platforms import SlackPlatform

slack = SlackPlatform(
    token=os.getenv("SLACK_BOT_TOKEN"),
    signing_secret=os.getenv("SLACK_SIGNING_SECRET")
)

slack.register_agent(agent)

Event handler

Event handler

@slack.event("app_mention") async def handle_mention(event): response = await agent.chat(event["text"]) await slack.post_message(event["channel"], response)
slack.start()
undefined
@slack.event("app_mention") async def handle_mention(event): response = await agent.chat(event["text"]) await slack.post_message(event["channel"], response)
slack.start()
undefined

WeChat Integration

微信集成

python
from hermes.platforms import WeChatPlatform

wechat = WeChatPlatform(
    app_id=os.getenv("WECHAT_APP_ID"),
    app_secret=os.getenv("WECHAT_APP_SECRET")
)

wechat.register_agent(agent)

@wechat.message_handler()
async def handle_message(message):
    response = await agent.chat(message.content)
    return response

wechat.run()
python
from hermes.platforms import WeChatPlatform

wechat = WeChatPlatform(
    app_id=os.getenv("WECHAT_APP_ID"),
    app_secret=os.getenv("WECHAT_APP_SECRET")
)

wechat.register_agent(agent)

@wechat.message_handler()
async def handle_message(message):
    response = await agent.chat(message.content)
    return response

wechat.run()

MCP Protocol Integration

MCP协议集成

Connecting MCP Servers

连接MCP服务器

python
from hermes.mcp import MCPClient, MCPServer
python
from hermes.mcp import MCPClient, MCPServer

Initialize client

Initialize client

mcp = MCPClient()
mcp = MCPClient()

Add filesystem server

Add filesystem server

mcp.add_server( name="filesystem", command="npx -y @modelcontextprotocol/server-filesystem", args=["/workspace"] )
mcp.add_server( name="filesystem", command="npx -y @modelcontextprotocol/server-filesystem", args=["/workspace"] )

Add PostgreSQL server

Add PostgreSQL server

mcp.add_server( name="postgres", command="npx -y @modelcontextprotocol/server-postgres", env={"DATABASE_URL": os.getenv("DATABASE_URL")} )
mcp.add_server( name="postgres", command="npx -y @modelcontextprotocol/server-postgres", env={"DATABASE_URL": os.getenv("DATABASE_URL")} )

Add GitHub server

Add GitHub server

mcp.add_server( name="github", command="npx -y @modelcontextprotocol/server-github", env={"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")} )
mcp.add_server( name="github", command="npx -y @modelcontextprotocol/server-github", env={"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")} )

Connect to agent

Connect to agent

agent.connect_mcp(mcp)
agent.connect_mcp(mcp)

Agent can now use all MCP tools

Agent can now use all MCP tools

response = await agent.chat( "Read my database schema and create documentation in the workspace" )
undefined
response = await agent.chat( "Read my database schema and create documentation in the workspace" )
undefined

Custom MCP Server

自定义MCP服务器

python
from hermes.mcp import MCPServer, mcp_tool

class CustomMCPServer(MCPServer):
    name = "custom_analytics"
    
    @mcp_tool(
        name="analyze_metrics",
        description="Analyze custom business metrics"
    )
    async def analyze_metrics(self, metric_type: str, date_range: str):
        # Your implementation
        data = await self.fetch_metrics(metric_type, date_range)
        analysis = self.perform_analysis(data)
        return analysis
    
    @mcp_tool(name="generate_report")
    async def generate_report(self, template: str):
        # Implementation
        pass
python
from hermes.mcp import MCPServer, mcp_tool

class CustomMCPServer(MCPServer):
    name = "custom_analytics"
    
    @mcp_tool(
        name="analyze_metrics",
        description="Analyze custom business metrics"
    )
    async def analyze_metrics(self, metric_type: str, date_range: str):
        # Your implementation
        data = await self.fetch_metrics(metric_type, date_range)
        analysis = self.perform_analysis(data)
        return analysis
    
    @mcp_tool(name="generate_report")
    async def generate_report(self, template: str):
        # Implementation
        pass

Register and use

Register and use

mcp.register_server(CustomMCPServer())
undefined
mcp.register_server(CustomMCPServer())
undefined

Automation & Scheduling

自动化与调度

Cron Jobs

Cron任务

python
from hermes.automation import CronScheduler

scheduler = CronScheduler(agent)
python
from hermes.automation import CronScheduler

scheduler = CronScheduler(agent)

Daily report at 9 AM

Daily report at 9 AM

@scheduler.cron("0 9 * * *") async def daily_report(): report = await agent.chat( "Generate a summary of yesterday's activities and pending tasks" ) await send_report(report)
@scheduler.cron("0 9 * * *") async def daily_report(): report = await agent.chat( "Generate a summary of yesterday's activities and pending tasks" ) await send_report(report)

Hourly monitoring

Hourly monitoring

@scheduler.cron("0 * * * *") async def monitor_system(): status = await agent.chat("Check all system metrics and alert if anomalies") if "ALERT" in status: await notify_admin(status)
scheduler.start()
undefined
@scheduler.cron("0 * * * *") async def monitor_system(): status = await agent.chat("Check all system metrics and alert if anomalies") if "ALERT" in status: await notify_admin(status)
scheduler.start()
undefined

Event-Driven Automation

事件驱动自动化

python
from hermes.automation import EventTrigger

triggers = EventTrigger(agent)
python
from hermes.automation import EventTrigger

triggers = EventTrigger(agent)

On file change

On file change

@triggers.on_file_change("/workspace/config.yaml") async def config_changed(filepath): await agent.chat(f"Configuration file {filepath} was modified. Validate and reload.")
@triggers.on_file_change("/workspace/config.yaml") async def config_changed(filepath): await agent.chat(f"Configuration file {filepath} was modified. Validate and reload.")

On webhook

On webhook

@triggers.on_webhook("/hooks/deployment") async def deployment_hook(payload): await agent.chat(f"New deployment detected: {payload['version']}. Run tests and notify team.")
@triggers.on_webhook("/hooks/deployment") async def deployment_hook(payload): await agent.chat(f"New deployment detected: {payload['version']}. Run tests and notify team.")

On database change

On database change

@triggers.on_database_event("users", event_type="insert") async def new_user(record): await agent.chat(f"New user registered: {record['email']}. Send welcome sequence.")
triggers.start()
undefined
@triggers.on_database_event("users", event_type="insert") async def new_user(record): await agent.chat(f"New user registered: {record['email']}. Send welcome sequence.")
triggers.start()
undefined

Multi-Agent Orchestration

多Agent编排

Sequential Workflow

顺序工作流

python
from hermes.orchestrator import SequentialWorkflow

workflow = SequentialWorkflow()
python
from hermes.orchestrator import SequentialWorkflow

workflow = SequentialWorkflow()

Define agents

Define agents

researcher = HermesAgent(name="researcher", skills=["web_search", "summarization"]) writer = HermesAgent(name="writer", skills=["content_generation"]) reviewer = HermesAgent(name="reviewer", skills=["quality_check"])
researcher = HermesAgent(name="researcher", skills=["web_search", "summarization"]) writer = HermesAgent(name="writer", skills=["content_generation"]) reviewer = HermesAgent(name="reviewer", skills=["quality_check"])

Build workflow

Build workflow

workflow.add_step(researcher, "Research the topic thoroughly") workflow.add_step(writer, "Write a comprehensive article based on research") workflow.add_step(reviewer, "Review and improve the article")
workflow.add_step(researcher, "Research the topic thoroughly") workflow.add_step(writer, "Write a comprehensive article based on research") workflow.add_step(reviewer, "Review and improve the article")

Execute

Execute

result = await workflow.execute("Write an article about quantum computing")
undefined
result = await workflow.execute("Write an article about quantum computing")
undefined

Parallel Processing

并行处理

python
from hermes.orchestrator import ParallelWorkflow

workflow = ParallelWorkflow()
python
from hermes.orchestrator import ParallelWorkflow

workflow = ParallelWorkflow()

Create specialized agents

Create specialized agents

agent1 = HermesAgent(name="analyzer1", skills=["data_analysis"]) agent2 = HermesAgent(name="analyzer2", skills=["data_analysis"]) agent3 = HermesAgent(name="analyzer3", skills=["data_analysis"])
agent1 = HermesAgent(name="analyzer1", skills=["data_analysis"]) agent2 = HermesAgent(name="analyzer2", skills=["data_analysis"]) agent3 = HermesAgent(name="analyzer3", skills=["data_analysis"])

Run in parallel

Run in parallel

workflow.add_parallel_tasks([ (agent1, "Analyze sales data for Q1"), (agent2, "Analyze sales data for Q2"), (agent3, "Analyze sales data for Q3") ])
workflow.add_parallel_tasks([ (agent1, "Analyze sales data for Q1"), (agent2, "Analyze sales data for Q2"), (agent3, "Analyze sales data for Q3") ])

Aggregate results

Aggregate results

results = await workflow.execute_parallel() summary = await aggregator_agent.chat(f"Summarize these quarterly analyses: {results}")
undefined
results = await workflow.execute_parallel() summary = await aggregator_agent.chat(f"Summarize these quarterly analyses: {results}")
undefined

Hierarchical Organization

层级组织

python
from hermes.orchestrator import HierarchicalOrchestrator
python
from hermes.orchestrator import HierarchicalOrchestrator

Manager agent

Manager agent

manager = HermesAgent( name="manager", model="gpt-4", role="coordinator" )
manager = HermesAgent( name="manager", model="gpt-4", role="coordinator" )

Worker agents

Worker agents

workers = [ HermesAgent(name="dev1", skills=["code_generation"]), HermesAgent(name="dev2", skills=["testing"]), HermesAgent(name="dev3", skills=["documentation"]) ]
orchestrator = HierarchicalOrchestrator( manager=manager, workers=workers )
workers = [ HermesAgent(name="dev1", skills=["code_generation"]), HermesAgent(name="dev2", skills=["testing"]), HermesAgent(name="dev3", skills=["documentation"]) ]
orchestrator = HierarchicalOrchestrator( manager=manager, workers=workers )

Manager delegates tasks

Manager delegates tasks

result = await orchestrator.execute( "Build a REST API for user management with tests and documentation" )
undefined
result = await orchestrator.execute( "Build a REST API for user management with tests and documentation" )
undefined

Configuration

配置

Environment Variables

环境变量

bash
undefined
bash
undefined

Core configuration

Core configuration

HERMES_MODEL=gpt-4-turbo HERMES_TEMPERATURE=0.7 HERMES_MAX_TOKENS=4096
HERMES_MODEL=gpt-4-turbo HERMES_TEMPERATURE=0.7 HERMES_MAX_TOKENS=4096

LLM Provider keys

LLM Provider keys

OPENAI_API_KEY=your_openai_key ANTHROPIC_API_KEY=your_anthropic_key
OPENAI_API_KEY=your_openai_key ANTHROPIC_API_KEY=your_anthropic_key

Memory configuration

Memory configuration

HERMES_MEMORY_TYPE=persistent HERMES_VECTOR_STORE=chromadb CHROMADB_PATH=./data/chromadb
HERMES_MEMORY_TYPE=persistent HERMES_VECTOR_STORE=chromadb CHROMADB_PATH=./data/chromadb

Tools & Services

Tools & Services

SERPER_API_KEY=your_serper_key GITHUB_TOKEN=your_github_token DATABASE_URL=postgresql://user:pass@localhost/db
SERPER_API_KEY=your_serper_key GITHUB_TOKEN=your_github_token DATABASE_URL=postgresql://user:pass@localhost/db

Platform tokens

Platform tokens

DISCORD_BOT_TOKEN=your_discord_token SLACK_BOT_TOKEN=your_slack_token WECHAT_APP_ID=your_wechat_id WECHAT_APP_SECRET=your_wechat_secret
DISCORD_BOT_TOKEN=your_discord_token SLACK_BOT_TOKEN=your_slack_token WECHAT_APP_ID=your_wechat_id WECHAT_APP_SECRET=your_wechat_secret

MCP configuration

MCP configuration

MCP_ENABLED=true MCP_SERVERS_PATH=./mcp_servers
MCP_ENABLED=true MCP_SERVERS_PATH=./mcp_servers

Security

Security

HERMES_SANDBOX_MODE=true HERMES_ALLOWED_PATHS=/workspace,/data HERMES_MAX_EXECUTION_TIME=30
undefined
HERMES_SANDBOX_MODE=true HERMES_ALLOWED_PATHS=/workspace,/data HERMES_MAX_EXECUTION_TIME=30
undefined

Configuration File

配置文件

python
undefined
python
undefined

config.yaml

config.yaml

agent: name: my_hermes_agent model: gpt-4-turbo temperature: 0.7 max_iterations: 10
memory: type: persistent backend: chromadb collection_name: hermes_memory embedding_model: text-embedding-3-small
skills: auto_load: true categories: - development - research - communication custom_path: ./custom_skills
tools: web_search: provider: serper max_results: 10 code_execution: sandbox: true timeout: 30 database: read_only: false
platforms:
  • type: discord enabled: true
  • type: slack enabled: true
mcp: enabled: true servers: - name: filesystem command: npx -y @modelcontextprotocol/server-filesystem args: ["/workspace"] - name: github command: npx -y @modelcontextprotocol/server-github
agent: name: my_hermes_agent model: gpt-4-turbo temperature: 0.7 max_iterations: 10
memory: type: persistent backend: chromadb collection_name: hermes_memory embedding_model: text-embedding-3-small
skills: auto_load: true categories: - development - research - communication custom_path: ./custom_skills
tools: web_search: provider: serper max_results: 10 code_execution: sandbox: true timeout: 30 database: read_only: false
platforms:
  • type: discord enabled: true
  • type: slack enabled: true
mcp: enabled: true servers: - name: filesystem command: npx -y @modelcontextprotocol/server-filesystem args: ["/workspace"] - name: github command: npx -y @modelcontextprotocol/server-github

Load configuration

Load configuration

from hermes.config import load_config
config = load_config("config.yaml") agent = HermesAgent.from_config(config)
undefined
from hermes.config import load_config
config = load_config("config.yaml") agent = HermesAgent.from_config(config)
undefined

Common Patterns

常见模式

Error Handling & Retries

错误处理与重试

python
from hermes.utils import retry_with_backoff

@retry_with_backoff(max_retries=3, backoff_factor=2)
async def execute_task_with_retry(agent, task):
    try:
        result = await agent.chat(task)
        return result
    except Exception as e:
        agent.logger.error(f"Task failed: {e}")
        raise
python
from hermes.utils import retry_with_backoff

@retry_with_backoff(max_retries=3, backoff_factor=2)
async def execute_task_with_retry(agent, task):
    try:
        result = await agent.chat(task)
        return result
    except Exception as e:
        agent.logger.error(f"Task failed: {e}")
        raise

With custom error handling

With custom error handling

async def safe_execution(agent, task): try: result = await execute_task_with_retry(agent, task) await agent.memory.store({"task": task, "status": "success"}) return result except Exception as e: await agent.memory.store({"task": task, "status": "failed", "error": str(e)}) await notify_admin(f"Task failed: {task}") return None
undefined
async def safe_execution(agent, task): try: result = await execute_task_with_retry(agent, task) await agent.memory.store({"task": task, "status": "success"}) return result except Exception as e: await agent.memory.store({"task": task, "status": "failed", "error": str(e)}) await notify_admin(f"Task failed: {task}") return None
undefined

Streaming Responses

流式响应

python
async def stream_agent_response(agent, query):
    async for chunk in agent.chat_stream(query):
        print(chunk, end="", flush=True)
        # Or send to UI
        await websocket.send(chunk)
python
async def stream_agent_response(agent, query):
    async for chunk in agent.chat_stream(query):
        print(chunk, end="", flush=True)
        # Or send to UI
        await websocket.send(chunk)

Context Management

上下文管理

python
from hermes.context import ContextManager

async def task_with_context(agent, user_id):
    context = ContextManager(agent)
    
    # Load user context
    await context.load_user_context(user_id)
    
    # Add temporary context
    with context.temporary({
        "project": "current_project",
        "mode": "development"
    }):
        result = await agent.chat("Review the latest code changes")
    
    # Context automatically cleaned up
    return result
python
from hermes.context import ContextManager

async def task_with_context(agent, user_id):
    context = ContextManager(agent)
    
    # Load user context
    await context.load_user_context(user_id)
    
    # Add temporary context
    with context.temporary({
        "project": "current_project",
        "mode": "development"
    }):
        result = await agent.chat("Review the latest code changes")
    
    # Context automatically cleaned up
    return result

Monitoring & Logging

监控与日志

python
from hermes.monitoring import AgentMonitor

monitor = AgentMonitor(agent)
python
from hermes.monitoring import AgentMonitor

monitor = AgentMonitor(agent)

Track metrics

Track metrics

monitor.track_token_usage() monitor.track_response_time() monitor.track_success_rate()
monitor.track_token_usage() monitor.track_response_time() monitor.track_success_rate()

Export metrics

Export metrics

metrics = monitor.get_metrics() print(f"Total tokens: {metrics['total_tokens']}") print(f"Avg response time: {metrics['avg_response_time']}s") print(f"Success rate: {metrics['success_rate']}%")
metrics = monitor.get_metrics() print(f"Total tokens: {metrics['total_tokens']}") print(f"Avg response time: {metrics['avg_response_time']}s") print(f"Success rate: {metrics['success_rate']}%")

Log to file

Log to file

monitor.export_logs("agent_metrics.json")
undefined
monitor.export_logs("agent_metrics.json")
undefined

Troubleshooting

故障排查

Common Issues

常见问题

1. Agent not responding
python
undefined
1. Agent无响应
python
undefined

Check agent status

Check agent status

print(agent.is_active) print(agent.get_status())
print(agent.is_active) print(agent.get_status())

Reset agent state

Reset agent state

await agent.reset()
await agent.reset()

Check logs

Check logs

agent.logger.set_level("DEBUG")

**2. Memory issues**
```python
agent.logger.set_level("DEBUG")

**2. 内存问题**
```python

Clear session memory

Clear session memory

await agent.memory.clear_session()
await agent.memory.clear_session()

Rebuild vector store

Rebuild vector store

await agent.memory.persistent.rebuild_index()
await agent.memory.persistent.rebuild_index()

Check memory usage

Check memory usage

stats = await agent.memory.get_stats() print(f"Session tokens: {stats['session_tokens']}") print(f"Persistent entries: {stats['persistent_entries']}")

**3. Tool execution failures**
```python
stats = await agent.memory.get_stats() print(f"Session tokens: {stats['session_tokens']}") print(f"Persistent entries: {stats['persistent_entries']}")

**3. 工具执行失败**
```python

Validate tool configuration

Validate tool configuration

for tool in agent.tools: print(f"{tool.name}: {tool.is_configured()}")
for tool in agent.tools: print(f"{tool.name}: {tool.is_configured()}")

Test tool individually

Test tool individually

tool = agent.get_tool("web_search") result = await tool.test_connection() print(result)
tool = agent.get_tool("web_search") result = await tool.test_connection() print(result)

Enable sandbox mode

Enable sandbox mode

agent.config.sandbox_mode = True

**4. MCP connection issues**
```python
agent.config.sandbox_mode = True

**4. MCP连接问题**
```python

Check MCP servers

Check MCP servers

print(agent.mcp.list_servers())
print(agent.mcp.list_servers())

Test MCP server

Test MCP server

server_status = await agent.mcp.test_server("filesystem") print(server_status)
server_status = await agent.mcp.test_server("filesystem") print(server_status)

Restart MCP client

Restart MCP client

await agent.mcp.restart()

**5. High token usage**
```python
await agent.mcp.restart()

**5. Token使用量过高**
```python

Optimize memory settings

Optimize memory settings

agent.memory.session.max_tokens = 2000 agent.memory.session.enable_summarization = True
agent.memory.session.max_tokens = 2000 agent.memory.session.enable_summarization = True

Use cheaper model for simple tasks

Use cheaper model for simple tasks

agent.set_model("gpt-3.5-turbo")
agent.set_model("gpt-3.5-turbo")

Limit context window

Limit context window

agent.config.max_context_tokens = 3000
undefined
agent.config.max_context_tokens = 3000
undefined

Migration from OpenClaw

从OpenClaw迁移

Key Differences

主要差异

  1. Architecture: Five layers vs. three layers
  2. Memory: Three-tier system vs. two-tier
  3. Skills: Skills Hub vs. basic plugin system
  4. MCP: Native support vs. plugin-based
  5. Multi-agent: Built-in orchestration vs. manual coordination
  1. 架构:五层架构 vs 三层架构
  2. 内存:三层系统 vs 两层系统
  3. 技能:Skills Hub vs 基础插件系统
  4. MCP:原生支持 vs 基于插件
  5. 多Agent:内置编排 vs 手动协调

Migration Steps

迁移步骤

python
undefined
python
undefined

OpenClaw code

OpenClaw code

from openclaw import Agent
openclaw_agent = Agent( model="gpt-4", plugins=["web_search", "file_ops"] )
from openclaw import Agent
openclaw_agent = Agent( model="gpt-4", plugins=["web_search", "file_ops"] )

Equivalent Hermes code

Equivalent Hermes code

from hermes import HermesAgent
hermes_agent = HermesAgent( model="gpt-4", skills=["web_search", "file_operations"] )
from hermes import HermesAgent
hermes_agent = HermesAgent( model="gpt-4", skills=["web_search", "file_operations"] )

Memory migration

Memory migration

OpenClaw memory export

OpenClaw memory export

openclaw_memory = openclaw_agent.export_memory()
openclaw_memory = openclaw_agent.export_memory()

Import to Hermes

Import to Hermes

await hermes_agent.memory.import_from_openclaw(openclaw_memory)
await hermes_agent.memory.import_from_openclaw(openclaw_memory)

Plugin to Skill mapping

Plugin to Skill mapping

skill_mapping = { "web_search": "web_automation", "file_ops": "file_system", "code_runner": "code_execution" }
for openclaw_plugin, hermes_skill in skill_mapping.items(): if openclaw_plugin in openclaw_agent.plugins: hermes_agent.add_skill(hermes_skill)
undefined
skill_mapping = { "web_search": "web_automation", "file_ops": "file_system", "code_runner": "code_execution" }
for openclaw_plugin, hermes_skill in skill_mapping.items(): if openclaw_plugin in openclaw_agent.plugins: hermes_agent.add_skill(hermes_skill)
undefined

Best Practices

最佳实践

  1. Always use environment variables for secrets
  2. Enable sandbox mode for code execution in production
  3. Implement proper error handling and retries
  4. Monitor token usage and costs
  5. Use persistent memory for important user data
  6. Regularly backup memory stores
  7. Test agents in isolation before orchestration
  8. Use appropriate models for task complexity
  9. Implement rate limiting for external API calls
  10. Log all agent actions for debugging
  1. 始终使用环境变量存储密钥
  2. 生产环境中启用代码执行沙箱模式
  3. 实现完善的错误处理与重试机制
  4. 监控Token使用量与成本
  5. 使用持久化内存存储重要用户数据
  6. 定期备份内存存储
  7. 编排前单独测试每个Agent
  8. 根据任务复杂度选择合适的模型
  9. 对外部API调用实现速率限制
  10. 记录所有Agent操作以便调试

Resources

资源

Quick Reference

快速参考

python
undefined
python
undefined

Basic agent setup

Basic agent setup

from hermes import HermesAgent
agent = HermesAgent( model="gpt-4-turbo", temperature=0.7, skills=["web_search", "code_execution"], memory_type="persistent" )
from hermes import HermesAgent
agent = HermesAgent( model="gpt-4-turbo", temperature=0.7, skills=["web_search", "code_execution"], memory_type="persistent" )

Simple chat

Simple chat

response =
response =