Tutorial 25: Code Execution
Tutorial 25: Code Execution โ easy-to-understand guide based on official docs
This is part of the Hermes Agent official tutorial series. View all tutorials
Imagine youโre baking a cake and instead of fetching ingredients one at a time, you write down the entire recipe, hand it to a helper, and they bring back only the finished cake. Thatโs exactly what Code Execution does for Hermes Agent โ it lets the agent run a full Python script that calls multiple tools inside, then returns only the final result to the conversation.
What Is Code Execution?
Normally, when Hermes needs to search the web, read a file, or run a command, it does each step one at a time โ and every intermediate result gets loaded into its โmemoryโ (the context window). Thatโs slow and wastes tokens.
With the execute_code tool, Hermes writes a Python script that can call tools programmatically โ like web_search, read_file, or patch โ all in one go. The script runs in a separate child process, and only the print() output comes back to the agent. All the messy intermediate data stays hidden.
How It Works: Step by Step
Step 1: The agent writes a Python script
It starts by importing tools from a special module:
from hermes_tools import web_search, web_extract
Step 2: Hermes creates a helper module
It automatically generates a hermes_tools.py stub that connects your script to the main agent.
Step 3: A communication channel opens
Hermes opens a Unix domain socket (a fast, local โphone lineโ between processes) and starts a listener thread.
Step 4: The script runs in a child process
Every tool call inside your script travels over that socket back to Hermes, which executes it and sends the result back.
Step 5: Only the print output returns
The scriptโs print() statements are the only thing the LLM sees. All the intermediate tool results never enter the context window โ saving massive amounts of tokens.
When Does Hermes Use This?
The agent automatically chooses execute_code when it spots:
- 3 or more tool calls with logic in between (like filtering or comparing)
- Bulk data processing โ e.g., searching many files and extracting snippets
- Loops โ repeating an action on many items
The big win? Token efficiency. Instead of feeding every search result back into the conversation, only the final summary comes through.
Practical Examples You Can Try
1. 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))
2. Multi-Step Web Research
from hermes_tools import web_search, web_extract
import json
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))
3. Bulk File Refactoring
from hermes_tools import search_files, read_file, patch
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")
4. Build and Test Pipeline
from hermes_tools import terminal
import json
result = terminal("cd /project && python -m pytest --tb=short -q 2>&1", timeout=120)
output = result.get("output", "")
passed = output.count(" passed")
failed = output.count(" failed")
print(json.dumps({"passed": passed, "failed": failed}, indent=2))
Key Points to Remember
- Available tools inside scripts:
web_search,web_extract,read_file,write_file,search_files,patch, andterminal(foreground only). - Only
print()output returns โ everything else stays hidden. - Great for loops, filtering, and multi-step workflows โ itโs like giving Hermes a mini-programming environment.
Summary
Code Execution turns Hermes from a step-by-step assistant into a batch processor. It writes a script, runs it, and gives you only the final answer โ saving time, tokens, and mental overhead. If you ever see Hermes doing a lot of repetitive tool calls, itโs probably using this feature under the hood.
Next up: Weโll explore how Hermes handles memory and context management โ how it decides what to remember and what to forget during long conversations. See you there!
๐ Official Docs
This article is based on the official Hermes Agent documentation:Official docs โบ user-guide/code-execution