将 Hermes 作为 Python 库使用
Hermes 不仅是一个命令行工具。你也可以直接导入 AIAgent,在自己的 Python 脚本、Web 应用或自动化流水线中以编程方式使用它。本指南将展示如何操作。
安装
直接从仓库安装 Hermes:
pip install git+https://github.com/NousResearch/hermes-agent.git
或使用 uv:
uv pip install git+https://github.com/NousResearch/hermes-agent.git
你也可以在 requirements.txt 中固定版本:
hermes-agent @ git+https://github.com/NousResearch/hermes-agent.git
在作为库使用时,CLI 所用的相同环境变量也是必需的。至少需要设置 OPENROUTER_API_KEY(或使用直接提供方访问时设置 OPENAI_API_KEY / ANTHROPIC_API_KEY)。
基本用法
使用 Hermes 最简单的方式是 chat() 方法——传入一条消息,即可获得字符串响应:
from run_agent import AIAgent
agent = AIAgent(
model="anthropic/claude-sonnet-4",
quiet_mode=True,
)
response = agent.chat("What is the capital of France?")
print(response)
chat() 方法在内部处理完整的对话循环——工具调用、重试等所有操作,并仅返回最终的文本响应。
在将 Hermes 嵌入到你自己的代码中时,始终设置 quiet_mode=True。否则,该代理会打印 CLI 的旋转光标、进度指示器和其他终端输出,这将污染你应用程序的输出。
完整对话控制
如需对对话有更多控制,可直接使用 run_conversation()。它返回一个包含完整响应、消息历史和元数据的字典:
agent = AIAgent(
model="anthropic/claude-sonnet-4",
quiet_mode=True,
)
result = agent.run_conversation(
user_message="Search for recent Python 3.13 features",
task_id="my-task-1",
)
print(result["final_response"])
print(f"Messages exchanged: {len(result['messages'])}")
返回的字典包含:
final_response—— 代理的最终文本回复messages—— 完整的消息历史(系统、用户、助手、工具调用)task_id—— 用于虚拟机隔离的任务标识符
你还可以传入自定义系统消息,以覆盖该调用的临时系统提示:
result = agent.run_conversation(
user_message="Explain quicksort",
system_message="You are a computer science tutor. Use simple analogies.",
)
配置工具
使用 enabled_toolsets 或 disabled_toolsets 控制代理可访问的工具集:
# Only enable web tools (browsing, search)
agent = AIAgent(
model="anthropic/claude-sonnet-4",
enabled_toolsets=["web"],
quiet_mode=True,
)
# Enable everything except terminal access
agent = AIAgent(
model="anthropic/claude-sonnet-4",
disabled_toolsets=["terminal"],
quiet_mode=True,
)
当你希望代理具备最小化、受限的配置时(例如,研究机器人仅允许网络搜索),请使用 enabled_toolsets。当你希望拥有大部分功能但需要限制特定工具(例如,在共享环境中禁用终端访问)时,请使用 disabled_toolsets。
多轮对话
通过将消息历史传回,可在多轮对话中保持对话状态:
agent = AIAgent(
model="anthropic/claude-sonnet-4",
quiet_mode=True,
)
# First turn
result1 = agent.run_conversation("My name is Alice")
history = result1["messages"]
# Second turn — agent remembers the context
result2 = agent.run_conversation(
"What's my name?",
conversation_history=history,
)
print(result2["final_response"]) # "Your name is Alice."
conversation_history 参数接受前一次结果中的 messages 列表。代理会内部复制该列表,因此你原始的列表不会被修改。
保存对话轨迹
启用轨迹保存功能,以 ShareGPT 格式捕获对话——这对于生成训练数据或调试非常有用:
agent = AIAgent(
model="anthropic/claude-sonnet-4",
save_trajectories=True,
quiet_mode=True,
)
agent.chat("Write a Python function to sort a list")
# Saves to trajectory_samples.jsonl in ShareGPT format
每次对话都会作为单行 JSONL 追加,便于从自动化运行中收集数据集。
自定义系统提示
使用 ephemeral_system_prompt 设置自定义系统提示,以引导代理行为,但该提示不会保存到轨迹文件中(从而保持你的训练数据干净):
agent = AIAgent(
model="anthropic/claude-sonnet-4",
ephemeral_system_prompt="You are a SQL expert. Only answer database questions.",
quiet_mode=True,
)
response = agent.chat("How do I write a JOIN query?")
print(response)
这非常适合构建专用代理——代码审查员、文档撰写器、SQL 助手等,全部使用相同的底层工具。
批量处理
对于并行运行多个提示,Hermes 提供了 batch_runner.py。它管理并发的 AIAgent 实例,并确保资源隔离:
python batch_runner.py --input prompts.jsonl --output results.jsonl
每个提示都会获得独立的 task_id 和隔离环境。如果你需要自定义批量逻辑,也可以直接使用 AIAgent 构建自己的方案:
import concurrent.futures
from run_agent import AIAgent
prompts = [
"Explain recursion",
"What is a hash table?",
"How does garbage collection work?",
]
def process_prompt(prompt):
# Create a fresh agent per task for thread safety
agent = AIAgent(
model="anthropic/claude-sonnet-4",
quiet_mode=True,
skip_memory=True,
)
return agent.chat(prompt)
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
results = list(executor.map(process_prompt, prompts))
for prompt, result in zip(prompts, results):
print(f"Q: {prompt}\nA: {result}\n")
请为每个线程或任务创建一个新的 AIAgent 实例。该代理维护内部状态(对话历史、工具会话、迭代计数器),这些状态不支持线程共享。
集成示例
FastAPI 端点
from fastapi import FastAPI
from pydantic import BaseModel
from run_agent import AIAgent
app = FastAPI()
class ChatRequest(BaseModel):
message: str
model: str = "anthropic/claude-sonnet-4"
@app.post("/chat")
async def chat(request: ChatRequest):
agent = AIAgent(
model=request.model,
quiet_mode=True,
skip_context_files=True,
skip_memory=True,
)
response = agent.chat(request.message)
return {"response": response}
Discord 机器人
import discord
from run_agent import AIAgent
client = discord.Client(intents=discord.Intents.default())
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("!hermes "):
query = message.content[8:]
agent = AIAgent(
model="anthropic/claude-sonnet-4",
quiet_mode=True,
skip_context_files=True,
skip_memory=True,
platform="discord",
)
response = agent.chat(query)
await message.channel.send(response[:2000])
client.run("YOUR_DISCORD_TOKEN")
CI/CD 流水线步骤
#!/usr/bin/env python3
"""CI step: auto-review a PR diff."""
import subprocess
from run_agent import AIAgent
diff = subprocess.check_output(["git", "diff", "main...HEAD"]).decode()
agent = AIAgent(
model="anthropic/claude-sonnet-4",
quiet_mode=True,
skip_context_files=True,
skip_memory=True,
disabled_toolsets=["terminal", "browser"],
)
review = agent.chat(
f"Review this PR diff for bugs, security issues, and style problems:\n\n{diff}"
)
print(review)
关键构造函数参数
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
model | str | "anthropic/claude-opus-4.6" | OpenRouter 格式的模型 |
quiet_mode | bool | False | 抑制 CLI 输出 |
enabled_toolsets | List[str] | None | 白名单特定工具集 |
disabled_toolsets | List[str] | None | 黑名单特定工具集 |
save_trajectories | bool | False | 将对话保存为 JSONL |
ephemeral_system_prompt | str | None | 自定义系统提示(不保存到轨迹) |
max_iterations | int | 90 | 每次对话的最大工具调用迭代次数 |
skip_context_files | bool | False | 跳过加载 AGENTS.md 文件 |
skip_memory | bool | False | 禁用持久化内存的读写 |
api_key | str | None | API 密钥(会回退到环境变量) |
base_url | str | None | 自定义 API 端点 URL |
platform | str | None | 平台提示(如 "discord"、"telegram" 等) |
重要说明
- 如果不希望将工作目录中的
AGENTS.md文件加载到系统提示中,请设置skip_context_files=True。 - 若要阻止代理读取或写入持久化内存,请设置
skip_memory=True—— 建议用于无状态 API 端点。 platform参数(例如"discord"、"telegram")会注入平台特定的格式化提示,使代理能够调整其输出风格。
- 线程安全性:每个线程或任务应创建一个
AIAgent实例。切勿在并发调用之间共享实例。 - 资源清理:当对话结束时,代理会自动清理资源(终端会话、浏览器实例)。如果在长期运行的进程中运行,请确保每次对话都能正常完成。
- 迭代次数限制:默认的
max_iterations=90已经相当宽松。对于简单的问答用例,建议降低该值(例如设置为max_iterations=10),以防止工具调用循环失控并控制成本。