知识引擎/Hermes 知识引擎/代码执行 (Execute Code)

The execute code tool lets the agent write Python scripts that call Hermes tools programmatically, collapsing multi-step workflows into a single LLM turn. The s

代码执行 (Execute Code)

> 📖 本文档翻译自 Hermes Agent 官方文档 > 最后更新:2026-04-16


The execute_code tool lets the agent write Python scripts that call Hermes tools programmatically, collapsing multi-step workflows into a single LLM turn. The script runs in a sandboxed child process on the agent host, communicating via Unix domain socket RPC.

工作原理

  1. The agent writes a Python script using from hermes_tools import ...
  2. Hermes generates a hermes_tools.py stub module with RPC functions
  3. Hermes opens a Unix domain socket and starts an RPC listener thread
  4. The script runs in a child process — tool calls travel over the socket back to Hermes
  5. Only the script's print() output is returned to the LLM; intermediate tool results never enter the context window
# The agent can write scripts like:
from hermes_tools import web_search, web_extract

results = web_search("Python 3.13 features", limit=5)
for r in results["data"]["web"]:
    content = web_extract([r["url"]])
    # ... filter and process ...
print(summary)

Available tools in sandbox: web_search, web_extract, read_file, write_file, search_files, patch, terminal (foreground only).

When the Agent Uses This

The agent uses execute_code when there are:

  • 3+ tool calls with processing logic between them
  • Bulk data filtering or conditional branching
  • Loops over results

The key benefit: intermediate tool results never enter the context window — only the final print() output comes back, dramatically reducing token usage.

Practical Examples

Data Processing Pipeline

from hermes_tools import search_files, read_file
import json

# Find all config files and extract database settings
matches = search_files("database", path=".", file_glob="*.yaml", limit=20)
configs = []
for match in matches.get("matches", []):
    content = read_file(match["path"])
    configs.append({"file": match["path"], "preview": content["content"][:200]})

print(json.dumps(configs, indent=2))

Multi-Step Web Research

from hermes_tools import web_search, web_extract
import json

# Search, extract, and summarize in one turn
results = web_search("Rust async runtime comparison 2025", limit=5)
summaries = []
for r in results["data"]["web"]:
    page = web_extract([r["url"]])
    for p in page.get("results", []):
        if p.get("content"):
            summaries.append({
                "title": r["title"],
                "url": r["url"],
                "excerpt": p["content"][:500]
            })

print(json.dumps(summaries, indent=2))

Bulk File Refactoring

from hermes_tools import search_files, read_file, patch

# Find all Python files using deprecated API and fix them
matches = search_files("old_api_call", path="src/", file_glob="*.py")
fixed = 0
for match in matches.get("matches", []):
    result = patch(
        path=match["path"],
        old_string="old_api_call(",
        new_string="new_api_call(",
        replace_all=True
    )
    if "error" not in str(result):
        fixed += 1

print(f"Fixed {fixed} files out of {len(matches.get('matches', []))} matches")

Build and Test Pipeline

from hermes_tools import terminal, read_file
import json

# Run tests, parse results, and report
result = terminal("cd /project && python -m pytest --tb=short -q 2>&1", timeout=120)
output = result.get("output", "")

# Parse test output
passed = output.count(" passed")
failed = output.count(" failed")
errors = output.count(" error")

report = {
    "passed": passed,
    "failed": failed,
    "errors": errors,
    "exit_code": result.get("exit_code", -1),
    "summary": output[-500:] if len(output) > 500 else output
}

print(json.dumps(report, indent=2))

Resource Limits

ResourceLimitNotes
Timeout5 minutes (300s)Script is killed with SIGTERM, then SIGKILL after 5s grace
Stdout50 KBOutput truncated with[output truncated at 50KB]notice
Stderr10 KBIncluded in output on non-zero exit for debugging
Tool calls50 per executionError returned when limit reached

All limits are configurable via config.yaml:

# In ~/.hermes/config.yaml
code_execution:
  timeout: 300       # Max seconds per script (default: 300)
  max_tool_calls: 50 # Max tool calls per execution (default: 50)

How Tool Calls Work Inside Scripts

When your script calls a function like web_search("query"):

  1. The call is serialized to JSON and sent over a Unix domain socket to the parent process
  2. The parent dispatches through the standard handle_function_call handler
  3. The result is sent back over the socket
  4. The function returns the parsed result

This means tool calls inside scripts behave identically to normal tool calls — same rate limits, same error handling, same capabilities. The only restriction is that terminal() is foreground-only (no background or pty parameters).

Error Handling

When a script fails, the agent receives structured error information:

  • Non-zero exit code: stderr is included in the output so the agent sees the full traceback
  • Timeout: Script is killed and the agent sees "Script timed out after 300s and was killed."
  • Interruption: If the user sends a new message during execution, the script is terminated and the agent sees [execution interrupted — user sent a new message]
  • Tool call limit: When the 50-call limit is hit, subsequent tool calls return an error message

The response always includes status (success/error/timeout/interrupted), output, tool_calls_made, and duration_seconds.

Security

:::caution

:::

Environment variables containing KEY, TOKEN, SECRET, PASSWORD, CREDENTIAL, PASSWD, or AUTH in their names are excluded. Only safe system variables (PATH, HOME, LANG, SHELL, PYTHONPATH, VIRTUAL_ENV, etc.) are passed through.

Skill Environment Variable Passthrough

When a skill declares required_environment_variables in its frontmatter, those variables are automatically passed through to both execute_code and terminal sandboxes after the skill is loaded. This lets skills use their declared API keys without weakening the security posture for arbitrary code.

For non-skill use cases, you can explicitly allowlist variables in config.yaml:

terminal:
  env_passthrough:
    - MY_CUSTOM_KEY
    - ANOTHER_TOKEN

See the Security guide for full details.

The script runs in a temporary directory that is cleaned up after execution. The child process runs in its own process group so it can be cleanly killed on timeout or interruption.

execute_code vs terminal

Use Caseexecute_codeterminal
Multi-step workflows with tool calls between
Simple shell command
Filtering/processing large tool outputs
Running a build or test suite
Looping over search results
Interactive/background processes
Needs API keys in environment⚠️ Only viapassthrough✅ (most pass through)

Rule of thumb: Use execute_code when you need to call Hermes tools programmatically with logic between calls. Use terminal for running shell commands, builds, and processes.

Platform Support

Code execution requires Unix domain sockets and is available on Linux and macOS only. It is automatically disabled on Windows — the agent falls back to regular sequential tool calls.

Continue Exploring

继续探索

这不是课程式的上一篇下一篇,而是从当前节点向外继续漫游。

使用指南

安全 (Security)

Hermes Agent is designed with a defense-in-depth security model. This page covers every security boundary — from command approval to container isolation to user

核心功能

工具与工具集 (Tools & Toolsets)

Tools are functions that extend the agent's capabilities. They're organized into logical toolsets that can be enabled or disabled per platform.

核心功能

记忆系统 (Memory System)

Hermes Agent has bounded, curated memory that persists across sessions. This lets it remember your preferences, your projects, your environment, and things it h

核心功能

技能系统 (Skill System)

技能是 Hermes 的可复用知识模块。每个技能都是一个 Markdown 文件,在激活时注入到 Agent 的上下文中——为其提供持久的工作流、领域知识和行为指南,而无需将这些内容塞入系统提示中。 技能是可热插拔的:你可以在会话中途安装、创建、编辑和切换技能。它们在 CLI、消息平台和 Gateway 后台任务中均可

核心功能

MCP 集成 (MCP Integration)

MCP 让 Hermes Agent 连接到外部工具服务器,使 Agent 能够使用 Hermes 本身之外的工具——GitHub、数据库、文件系统、浏览器栈、内部 API 等。 如果你曾想让 Hermes 使用一个已经存在于其他地方的工具,MCP 通常是最简洁的方式。 - 无需先编写原生 Hermes 工具即可访问外

核心功能

ACP 编辑器集成 (ACP Editor Integration)

Hermes Agent 可以作为 ACP 服务器运行,让 ACP 兼容的编辑器通过 stdio 与 Hermes 通信,并渲染: - 聊天消息 - 工具活动 - 文件差异 - 终端命令 - 审批提示 - 流式思考 / 响应片段 当你希望 Hermes 像编辑器原生的编程 Agent 一样工作,而不是独立的 CLI 或

Core Features

核心功能

Hermes 的能力核心:工具、记忆、技能、委派、自动化、语音、插件与浏览器控制。

31 篇文档30 个节点

当前节点

代码执行 (Execute Code)

同主题继续探索

工具与工具集 (Tools & Toolsets)

Tools are functions that extend the agent's capabilities. They're organized into logical toolsets that can be enabled or disabled per platform.

记忆系统 (Memory System)

Hermes Agent has bounded, curated memory that persists across sessions. This lets it remember your preferences, your projects, your environment, and things it h

技能系统 (Skill System)

技能是 Hermes 的可复用知识模块。每个技能都是一个 Markdown 文件,在激活时注入到 Agent 的上下文中——为其提供持久的工作流、领域知识和行为指南,而无需将这些内容塞入系统提示中。 技能是可热插拔的:你可以在会话中途安装、创建、编辑和切换技能。它们在 CLI、消息平台和 Gateway 后台任务中均可

MCP 集成 (MCP Integration)

MCP 让 Hermes Agent 连接到外部工具服务器,使 Agent 能够使用 Hermes 本身之外的工具——GitHub、数据库、文件系统、浏览器栈、内部 API 等。 如果你曾想让 Hermes 使用一个已经存在于其他地方的工具,MCP 通常是最简洁的方式。 - 无需先编写原生 Hermes 工具即可访问外

ACP 编辑器集成 (ACP Editor Integration)

Hermes Agent 可以作为 ACP 服务器运行,让 ACP 兼容的编辑器通过 stdio 与 Hermes 通信,并渲染: - 聊天消息 - 工具活动 - 文件差异 - 终端命令 - 审批提示 - 流式思考 / 响应片段 当你希望 Hermes 像编辑器原生的编程 Agent 一样工作,而不是独立的 CLI 或

API 服务器 (API Server)

The API server exposes hermes-agent as an OpenAI-compatible HTTP endpoint. Any frontend that speaks the OpenAI format — Open WebUI, LobeChat, LibreChat, NextCha

相关节点

安全 (Security)

Hermes Agent is designed with a defense-in-depth security model. This page covers every security boundary — from command approval to container isolation to user

工具与工具集 (Tools & Toolsets)

Tools are functions that extend the agent's capabilities. They're organized into logical toolsets that can be enabled or disabled per platform.

记忆系统 (Memory System)

Hermes Agent has bounded, curated memory that persists across sessions. This lets it remember your preferences, your projects, your environment, and things it h

技能系统 (Skill System)

技能是 Hermes 的可复用知识模块。每个技能都是一个 Markdown 文件,在激活时注入到 Agent 的上下文中——为其提供持久的工作流、领域知识和行为指南,而无需将这些内容塞入系统提示中。 技能是可热插拔的:你可以在会话中途安装、创建、编辑和切换技能。它们在 CLI、消息平台和 Gateway 后台任务中均可

MCP 集成 (MCP Integration)

MCP 让 Hermes Agent 连接到外部工具服务器,使 Agent 能够使用 Hermes 本身之外的工具——GitHub、数据库、文件系统、浏览器栈、内部 API 等。 如果你曾想让 Hermes 使用一个已经存在于其他地方的工具,MCP 通常是最简洁的方式。 - 无需先编写原生 Hermes 工具即可访问外

ACP 编辑器集成 (ACP Editor Integration)

Hermes Agent 可以作为 ACP 服务器运行,让 ACP 兼容的编辑器通过 stdio 与 Hermes 通信,并渲染: - 聊天消息 - 工具活动 - 文件差异 - 终端命令 - 审批提示 - 流式思考 / 响应片段 当你希望 Hermes 像编辑器原生的编程 Agent 一样工作,而不是独立的 CLI 或